Skip to main content

mj_controller/controller/
provisioning.rs

1//! Session provisioning, rollback, and worker-side Git bootstrap.
2
3use std::collections::{BTreeMap, HashMap};
4use std::path::{Path, PathBuf};
5use std::process::{Command, Stdio};
6use std::sync::{Arc, Mutex, OnceLock};
7use std::time::Instant;
8
9use anyhow::{Context, Result, bail, ensure};
10
11use mj_core::config::{TargetTemplate, atomic_write, data_dir};
12use mj_core::state::{SessionState, State, TargetLocator};
13
14use crate::targets::{
15    self, CommandExecutor, CommandOutput, CommandSpec, ProvisionStage, ProvisionStageGuard,
16};
17
18use super::backend::{
19    ContainerOverrides, TargetCheck, backend_locator, backend_session_bundle, backend_target,
20    configure_github_token_environment, preflight_target, use_github_https_urls,
21};
22use super::git_cache;
23use super::readiness::{connect_started_worker, wait_for_native_session_in_stage};
24use super::worker_binary::{bridge_readiness_stage, start_worker_durably, worker_probe_diagnosis};
25use super::{Controller, execute_checked, now};
26
27const INHERITED_GIT_SETTINGS: &[&str] = &[
28    "diff.algorithm",
29    "fetch.prune",
30    "fetch.prunetags",
31    "init.defaultbranch",
32    "merge.conflictstyle",
33    "pull.ff",
34    "pull.rebase",
35    "push.autosetupremote",
36    "push.default",
37    "rebase.autostash",
38    "rerere.autoupdate",
39    "rerere.enabled",
40    "user.email",
41    "user.name",
42];
43
44/// How many sub-agent children may be brought up inside one container at the
45/// same time.
46///
47/// Starting a child means starting a harness, and a harness start inside a
48/// container is expensive, especially while its reviewer is active. Measured
49/// on a local Podman
50/// target, ten children started one after another each reached their harness
51/// in about seven seconds, while four started at once left two or three of
52/// them past the 300-second harness-startup wait. Admitting two at a time
53/// keeps a burst slower but finished, instead of fast and failed.
54const CONTAINER_START_ADMISSION: usize = 2;
55
56/// The admission gate for one container, created on first use.
57///
58/// Keyed by the container the children share. A bare target has no gate: a
59/// child there is an ordinary process on a whole machine, and twenty
60/// sequential and four concurrent starts measured 2.8 seconds each.
61pub(super) fn container_start_gate(
62    locator: &targets::TargetLocator,
63) -> Option<Arc<tokio::sync::Semaphore>> {
64    static GATES: OnceLock<Mutex<HashMap<String, Arc<tokio::sync::Semaphore>>>> = OnceLock::new();
65    let container = match locator {
66        targets::TargetLocator::LocalPodman { container_id, .. }
67        | targets::TargetLocator::LocalDocker { container_id, .. }
68        | targets::TargetLocator::AppleContainer { container_id, .. }
69        | targets::TargetLocator::SshPodman { container_id, .. }
70        | targets::TargetLocator::SshDocker { container_id, .. } => container_id.clone(),
71        targets::TargetLocator::LocalBare { .. }
72        | targets::TargetLocator::SshBare { .. }
73        | targets::TargetLocator::AwsEc2 { .. } => return None,
74    };
75    let gates = GATES.get_or_init(|| Mutex::new(HashMap::new()));
76    let mut gates = gates
77        .lock()
78        .unwrap_or_else(std::sync::PoisonError::into_inner);
79    Some(Arc::clone(gates.entry(container).or_insert_with(|| {
80        Arc::new(tokio::sync::Semaphore::new(CONTAINER_START_ADMISSION))
81    })))
82}
83
84/// Whether starting a child worker can be tried again.
85///
86/// Only a worker that provably never published its control socket qualifies:
87/// it owns no relay, no journal and no harness, so a second start cannot
88/// duplicate or corrupt work. A refusal is never retried, because it names a
89/// precondition that a second attempt would meet in exactly the same way, and
90/// a cancelled operation is not retried either.
91fn subagent_start_is_retryable(error: &anyhow::Error) -> bool {
92    if mj_core::refusal::Refusal::of(error).is_some() {
93        return false;
94    }
95    if format!("{error:#}").contains("operation cancelled") {
96        return false;
97    }
98    error
99        .downcast_ref::<super::readiness::WorkerStartupFailure>()
100        .is_some_and(|failure| !failure.reached_socket)
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Eq)]
104pub(super) enum ProvisioningFailureDisposition {
105    /// A freshly registered session has no durable history to retain.
106    Discard,
107    /// Resume owns rollback to the archived record and checkpoint lineage.
108    Preserve,
109}
110
111impl Controller {
112    pub async fn provision_session_controlled_with_commit(
113        &mut self,
114        session_id: &str,
115        executor: &(impl CommandExecutor + Sync),
116        grant_commit: impl FnOnce() -> Result<()>,
117    ) -> Result<()> {
118        crate::worker_lifecycle::run(
119            session_id,
120            "provision session controlled with commit",
121            executor,
122            async {
123                crate::worker_lifecycle::require(session_id)?.verify_cached_target(&self.state)?;
124                let github_token = self
125                    .github_token_for_session(session_id)
126                    .await
127                    .context("resolve GitHub credentials for session")?;
128                let repositories = self
129                    .provision_session_target_with_failure_disposition(
130                        session_id,
131                        executor,
132                        github_token.as_deref(),
133                        ProvisioningFailureDisposition::Discard,
134                    )
135                    .await?;
136                let setup = execute_concurrent_lanes(
137                    || execute_repository_setup(&repositories, executor),
138                    || self.install_worker_payload(session_id, executor),
139                );
140                let result = match setup {
141                    Ok(((), (backend, worker_root))) => {
142                        self.connect_and_start_worker(
143                            session_id,
144                            executor,
145                            &backend,
146                            &worker_root,
147                            true,
148                        )
149                        .await
150                    }
151                    Err(error) => Err(error),
152                };
153                match result {
154                    Ok(native_session_id) => {
155                        if let Err(error) = grant_commit() {
156                            return Err(self.rollback_failed_new_session(session_id, error)?);
157                        }
158                        self.mark_worker_connected(session_id, native_session_id)
159                    }
160                    Err(error) => Err(self.rollback_failed_new_session(session_id, error)?),
161                }
162            },
163        )
164        .await
165    }
166
167    /// Start a child worker inside an already-provisioned parent target.
168    /// Repository, target, and mount setup belong exclusively to the parent.
169    pub async fn provision_subagent_session_controlled(
170        &mut self,
171        session_id: &str,
172        executor: &(impl CommandExecutor + Sync),
173    ) -> Result<()> {
174        crate::worker_lifecycle::run(
175            session_id,
176            "provision subagent session controlled",
177            executor,
178            async {
179                crate::worker_lifecycle::require(session_id)?.verify_cached_target(&self.state)?;
180                // One retry, and only for a worker that provably never published a
181                // control socket. Such a worker has no relay, no durable journal and
182                // no harness, so starting another over the same root cannot duplicate
183                // or corrupt anything. A spawn is issued by a model that cannot see
184                // the target, so a transient start failure it could have retried by
185                // hand is better retried here.
186                let mut attempts: Vec<String> = Vec::new();
187                loop {
188                    let (result, placement) =
189                        self.attempt_subagent_start(session_id, executor).await;
190                    let error = match result {
191                        Ok(native_session_id) => {
192                            return self.mark_worker_connected(session_id, native_session_id);
193                        }
194                        Err(error) => error,
195                    };
196                    let retry = attempts.is_empty() && subagent_start_is_retryable(&error);
197                    let error = match &placement {
198                        Some((backend, _)) => super::subagent_park::explain_process_exhaustion(
199                            error, backend, session_id,
200                        ),
201                        None => error,
202                    };
203                    attempts.push(format!("{error:#}"));
204                    let error = if attempts.len() > 1 {
205                        anyhow::anyhow!(
206                            "{}",
207                            attempts
208                                .iter()
209                                .enumerate()
210                                .map(|(index, error)| format!("attempt {}: {error}", index + 1))
211                                .collect::<Vec<_>>()
212                                .join("; ")
213                        )
214                    } else {
215                        error
216                    };
217                    let diagnostic = note_new_session_launch_failure(session_id, &error);
218                    let previous = self
219                        .state
220                        .sessions
221                        .get(session_id)
222                        .context("failed child disappeared")?
223                        .clone();
224                    let record = self.state.sessions.get_mut(session_id).unwrap();
225                    record.state = SessionState::StartupCleanup;
226                    record.updated_at = now();
227                    record.last_error = Some(format!("sub-agent startup failed: {diagnostic}"));
228                    self.persist_session_transition_or_restore(
229                        session_id,
230                        &previous,
231                        "record failed startup before teardown",
232                    )?;
233                    let cleanup = super::failed_launch_cleanup_executor();
234                    if let Err(cleanup_error) =
235                        self.finish_failed_startup_controlled(session_id, &cleanup, retry)
236                    {
237                        return Err(error.context(format!(
238                            "startup cleanup remains pending: {cleanup_error:#}"
239                        )));
240                    }
241                    if !retry {
242                        return Err(error);
243                    }
244                    tracing::warn!(
245                        session_id,
246                        error = format!("{error:#}"),
247                        "sub-agent worker never started and was stopped; retrying once"
248                    );
249                }
250            },
251        )
252        .await
253    }
254
255    /// Finish a failed startup without reopening its relay or replaying work.
256    pub(crate) fn cleanup_failed_startup_controlled(
257        &mut self,
258        session_id: &str,
259        executor: &impl CommandExecutor,
260    ) -> Result<()> {
261        self.finish_failed_startup_controlled(session_id, executor, false)
262    }
263
264    fn finish_failed_startup_controlled(
265        &mut self,
266        session_id: &str,
267        executor: &impl CommandExecutor,
268        retry_after_stop: bool,
269    ) -> Result<()> {
270        crate::worker_lifecycle::run_blocking(
271            session_id,
272            "finish failed startup controlled",
273            executor,
274            || {
275                let previous = self
276                    .state
277                    .sessions
278                    .get(session_id)
279                    .context("cleanup session disappeared")?
280                    .clone();
281                ensure!(
282                    previous.state == SessionState::StartupCleanup,
283                    "session is not awaiting startup cleanup"
284                );
285                let child = self.state.subagents.contains_key(session_id);
286                ensure!(
287                    !retry_after_stop || child,
288                    "only unaccepted child startup may retry"
289                );
290                let outcome = (|| -> Result<()> {
291                    if let Some(locator) = &previous.target {
292                        let backend = backend_locator(locator, &previous, &self.config)?;
293                        if child {
294                            let root = targets::worker_root(&backend, session_id)?;
295                            super::worker_binary::stop_worker(
296                                &crate::worker_lifecycle::require(session_id)?,
297                                executor,
298                                &backend,
299                                &root,
300                            )?;
301                        } else {
302                            targets::close_plan(&backend, session_id)?.execute(executor)?;
303                        }
304                    }
305                    if !child {
306                        self.cleanup_new_session_worktree_after_failure(session_id, executor)?;
307                    }
308                    Ok(())
309                })();
310                let record = self.state.sessions.get_mut(session_id).unwrap();
311                record.updated_at = now();
312                let cause = previous
313                    .last_error
314                    .as_deref()
315                    .unwrap_or("startup failed")
316                    .split("; startup cleanup failed:")
317                    .next()
318                    .unwrap()
319                    .to_owned();
320                match &outcome {
321                    Ok(()) => {
322                        record.state = if retry_after_stop {
323                            SessionState::Provisioning
324                        } else {
325                            SessionState::Error
326                        };
327                        record.last_error = (!retry_after_stop).then_some(cause);
328                        if !child {
329                            record.target = None;
330                        }
331                    }
332                    Err(error) => {
333                        record.last_error =
334                            Some(format!("{cause}; startup cleanup failed: {error:#}"));
335                    }
336                }
337                let record = self.state.sessions.get_mut(session_id).unwrap();
338                if outcome.is_ok() && child && !retry_after_stop {
339                    record.archived = true;
340                }
341                if let Err(error) = crate::database::save_startup_cleanup_outcome(
342                    record,
343                    outcome.is_ok() && child && !retry_after_stop,
344                ) {
345                    self.state.sessions.insert(session_id.to_owned(), previous);
346                    return Err(error).context("record startup cleanup outcome");
347                }
348                outcome
349            },
350        )
351    }
352
353    /// One start of a child worker: place it, install its files, and wait for
354    /// its relay. The placement is returned even on failure, because the
355    /// caller needs it to stop a worker that may be half up.
356    async fn attempt_subagent_start(
357        &mut self,
358        session_id: &str,
359        executor: &(impl CommandExecutor + Sync),
360    ) -> (
361        Result<Option<String>>,
362        Option<(targets::TargetLocator, String)>,
363    ) {
364        // Placement failures must reach the same failure arm as startup
365        // failures; otherwise the child record stays `Provisioning` forever.
366        match self.worker_placement(session_id) {
367            Ok((backend, worker_root)) => {
368                let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
369                let prepared = self
370                    .prepare_worker_files(session_id, &backend, &worker_root, syncing)
371                    .and_then(|()| self.prepare_subagent_report_dir(session_id, &backend, syncing));
372                let result = match prepared {
373                    Ok(()) => {
374                        // Held across the harness startup wait, which is the
375                        // part that does not survive a crowd.
376                        let gate = container_start_gate(&backend);
377                        let _admitted = match &gate {
378                            Some(gate) => gate.acquire().await.ok(),
379                            None => None,
380                        };
381                        self.connect_and_start_worker(
382                            session_id,
383                            executor,
384                            &backend,
385                            &worker_root,
386                            false,
387                        )
388                        .await
389                    }
390                    Err(error) => Err(error),
391                };
392                (result, Some((backend, worker_root)))
393            }
394            Err(error) => (Err(error), None),
395        }
396    }
397
398    fn rollback_failed_new_session(
399        &mut self,
400        session_id: &str,
401        error: anyhow::Error,
402    ) -> Result<anyhow::Error> {
403        self.rollback_failed_new_session_with(
404            session_id,
405            error,
406            // Rollback must remain possible after the foreground operation's
407            // cancellation token has been set.
408            &super::failed_launch_cleanup_executor(),
409        )
410    }
411
412    fn rollback_failed_new_session_with(
413        &mut self,
414        session_id: &str,
415        error: anyhow::Error,
416        target_cleanup_executor: &impl CommandExecutor,
417    ) -> Result<anyhow::Error> {
418        let session = self
419            .state
420            .sessions
421            .get(session_id)
422            .with_context(|| format!("unknown session {session_id}"))?
423            .clone();
424        // The failure goes on record before anything the record points at is
425        // removed. Removing the worker and its checkout can outlast a daemon
426        // that is stopping, and a daemon that exits partway would otherwise
427        // leave a record naming a worker that no longer exists, which every
428        // later daemon keeps reconnecting to. A failed record that still
429        // names its target is one Destroy knows how to clean up.
430        let original = note_new_session_launch_failure(session_id, &error);
431        apply_failed_new_session_launch(&mut self.state, session_id, &original);
432        self.persist_session_transition_or_restore(
433            session_id,
434            &session,
435            "record the failed launch before removing its target",
436        )
437        .map_err(|persist_error| {
438            persist_error.context(format!(
439                "{original}; its target was left in place because the failure could not be recorded"
440            ))
441        })?;
442        let target_cleanup = match session.target.as_ref() {
443            Some(locator) => (|| -> Result<()> {
444                let backend = backend_locator(locator, &session, &self.config)?;
445                targets::close_plan(&backend, session_id)?
446                    .execute(target_cleanup_executor)
447                    .map(|_| ())
448            })(),
449            None => Ok(()),
450        };
451        // A failed stop leaves the harness able to write its checkout. Keep
452        // that checkout until a later cleanup confirms process termination.
453        let cleanup_error = target_cleanup
454            .and_then(|()| {
455                self.cleanup_new_session_worktree_after_failure(session_id, target_cleanup_executor)
456            })
457            .err()
458            .map(|error| format!("{error:#}"));
459        if let Some(cleanup_error) = &cleanup_error {
460            tracing::warn!(
461                session_id,
462                error = %cleanup_error,
463                "new-session rollback cleanup reported failures"
464            );
465        }
466        let failure = apply_failed_new_session_rollback(
467            &mut self.state,
468            session_id,
469            &original,
470            cleanup_error,
471        );
472        self.persist_session_state(session_id)?;
473        Ok(failure)
474    }
475
476    pub(super) async fn provision_session_with_failure_disposition(
477        &mut self,
478        session_id: &str,
479        executor: &(impl CommandExecutor + Sync),
480        github_token: Option<&str>,
481        failure_disposition: ProvisioningFailureDisposition,
482    ) -> Result<()> {
483        let repositories = self
484            .provision_session_target_with_failure_disposition(
485                session_id,
486                executor,
487                github_token,
488                failure_disposition,
489            )
490            .await?;
491        match execute_repository_setup(&repositories, executor) {
492            Ok(()) => Ok(()),
493            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
494                Err(self.rollback_failed_new_session(session_id, error)?)
495            }
496            Err(error) => Err(error),
497        }
498    }
499
500    async fn provision_session_target_with_failure_disposition(
501        &mut self,
502        session_id: &str,
503        executor: &(impl CommandExecutor + Sync),
504        github_token: Option<&str>,
505        failure_disposition: ProvisioningFailureDisposition,
506    ) -> Result<targets::CommandPlan> {
507        crate::worker_lifecycle::run(session_id, "provision session target with failure disposition", executor, async {
508        let session = self
509            .state
510            .sessions
511            .get(session_id)
512            .with_context(|| format!("unknown session {session_id}"))?
513            .clone();
514        if session.state != SessionState::Provisioning {
515            bail!("session {session_id} is not provisioning");
516        }
517        if let Some(plan) = self.adopt_prepared_ec2_destination(session_id)? {
518            return Ok(plan);
519        }
520        let preparation = (|| {
521            let selected = self
522                .config
523                .targets
524                .get(&session.target_template_id)
525                .context("target template disappeared before provisioning")?;
526            // Before the runtime is recorded, so a container never starts
527            // without an entry whose secret is missing.
528            selected.ensure_ready(&session.target_template_id)?;
529            self.config
530                .profiles
531                .get(&session.last_profile)
532                .context("harness profile disappeared before provisioning")?
533                .ensure_ready(&session.last_profile)?;
534            let runtime = mj_core::state::TargetRuntimeSettings::from(selected);
535            if let Some(recorded) = &session.target_runtime {
536                ensure!(
537                    recorded == &runtime,
538                    "target access settings changed before provisioning; retry with the selected target"
539                );
540            } else {
541                self.state
542                    .sessions
543                    .get_mut(session_id)
544                    .unwrap()
545                    .target_runtime = Some(runtime);
546                self.persist_session_state(session_id)?;
547            }
548            let template = self
549                .config
550                .targets
551                .get(&session.target_template_id)
552                .context("target template disappeared during provisioning")?;
553            let profile = self
554                .config
555                .profiles
556                .get(&session.last_profile)
557                .context("harness profile disappeared during provisioning")?;
558            super::worker_binary::preflight_worker_binary(template, executor)?;
559            super::worker_binary::preflight_harness(template, profile, executor)?;
560            self.prepare_managed_raw_worktree(session_id, executor)
561        })();
562        let created_worktree = match preparation {
563            Ok(created) => created,
564            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
565                return Err(self.fail_new_session_with_cleanup(session_id, error, executor)?);
566            }
567            Err(error) => return Err(error),
568        };
569        let session = self
570            .state
571            .sessions
572            .get(session_id)
573            .expect("session retained after managed worktree preparation")
574            .clone();
575        let checkout = self.state.checkout(session_id)?;
576        let project_directory = checkout.project_directory();
577        // Keep planning, preflight, creation, and locator discovery in one
578        // result so the caller's failure disposition applies to every error.
579        let result = (|| {
580            let template = self
581                .config
582                .targets
583                .get(&session.target_template_id)
584                .context("target template disappeared during provisioning")?;
585            if matches!(template, TargetTemplate::AwsEc2 { .. }) {
586                for resource in &session.additional_mounts {
587                    ensure!(
588                        resource.source.is_dir(),
589                        "attached resource source is not a directory: {}",
590                        resource.source.display()
591                    );
592                }
593            }
594            let mut target = backend_target(
595                template,
596                session.resource_allocation.as_ref(),
597                ContainerOverrides::for_session(&session),
598            )?;
599            let mut runtime_mounts = if matches!(target, targets::TargetTemplate::AwsEc2(_)) {
600                Vec::new()
601            } else {
602                session.additional_mounts.clone()
603            };
604            // The mounts this container runs with, not the ones the session
605            // stores: a forced downgrade belongs to the host the container
606            // lands on, so it is decided here every time and never written
607            // over the user's choice.
608            for notice in enforce_overlay_capable_mounts(&target, &mut runtime_mounts, executor) {
609                executor.notify_notice(&notice);
610            }
611            let mut bundle = if project_directory.is_some() {
612                None
613            } else if let Some(bundle) = self.move_destination_bundle(session_id)? {
614                Some(bundle)
615            } else if failure_disposition == ProvisioningFailureDisposition::Preserve {
616                Some(super::network_git::checkpoint_bundle(&session)?)
617            } else {
618                Some(backend_session_bundle(&session, &self.config, executor)?)
619            };
620            let container_github_token =
621                github_token.filter(|_| configure_github_token_environment(&mut target));
622            if container_github_token.is_some()
623                && let Some(bundle) = bundle.as_mut()
624            {
625                use_github_https_urls(bundle);
626            }
627            preflight_target(template, executor, TargetCheck::Launch)?;
628            let resource_name = crate::database::load_move_operation(session_id)?
629                .filter(|op| {
630                    op.workspace_transfer.is_some()
631                        && op.phase == mj_core::state::MovePhase::ResumingDestination
632                })
633                .map(|op| targets::move_resource_name(session_id, &op.operation_id))
634                .unwrap_or_else(|| targets::resource_name(session_id))?;
635            let moving_workspace = resource_name != targets::resource_name(session_id)?;
636            let prepared_cache = bundle
637                .as_mut()
638                .filter(|_| !moving_workspace)
639                .and_then(|bundle| {
640                    git_cache::prepare(
641                        &target,
642                        session_id,
643                        bundle,
644                        &mut runtime_mounts,
645                        container_github_token,
646                        executor,
647                    )
648                });
649            // Mounts are fixed when the container is created, so the build
650            // cache is decided here, before the provisioning plan is built.
651            let build_cache = super::mbx::prepare(
652                &target,
653                &session,
654                bundle.as_ref(),
655                prepared_cache.as_ref(),
656                &mut runtime_mounts,
657                executor,
658            );
659            let provision = if let Some(project_directory) = project_directory {
660                targets::provision_bare_project_plan(
661                    &target,
662                    session_id,
663                    &project_directory.to_string_lossy(),
664                )
665            } else {
666                bundle
667                    .as_ref()
668                    .context("project bundle disappeared during provisioning")
669                    .and_then(|bundle| {
670                        targets::provision_plan_named(
671                            &target,
672                            session_id,
673                            bundle,
674                            &runtime_mounts,
675                            session.container_workspace.as_deref(),
676                            &resource_name,
677                        )
678                    })
679            };
680            let mut provision = match provision {
681                Ok(provision) => provision,
682                Err(error) => {
683                    if let Some(cache) = &prepared_cache {
684                        let _ = cache.cleanup(executor);
685                    }
686                    return Err(error);
687                }
688            };
689            if let Some(token) = container_github_token
690                && let Err(error) =
691                    provision.provide_target_environment_secret(&target, "GH_TOKEN", token)
692            {
693                if let Some(cache) = &prepared_cache {
694                    let _ = cache.cleanup(executor);
695                }
696                return Err(error);
697            }
698
699            let started = Instant::now();
700            let result = provision_target_creation_named(
701                &provision,
702                &target,
703                session_id,
704                executor,
705                &resource_name,
706                |outputs| {
707                    super::backend::locator_after_provision_named(
708                        template,
709                        &target,
710                        session_id,
711                        outputs.first(),
712                        executor,
713                        &resource_name,
714                    )
715                },
716            )
717            .map(|(locator, remainder)| (locator, remainder, bundle, build_cache));
718            if result.is_err()
719                && let Some(cache) = &prepared_cache
720            {
721                if let Some(locator) =
722                    provisioned_locator_named(&target, session_id, None, &resource_name)
723                {
724                    let _ = targets::close_plan(&locator, session_id)
725                        .and_then(|plan| plan.execute(executor).map(|_| ()));
726                } else {
727                    let _ = cache.cleanup(executor);
728                }
729            }
730            tracing::debug!(
731                session_id,
732                elapsed_ms = started.elapsed().as_millis(),
733                "provisioning plan execution completed"
734            );
735            result
736        })();
737        drop(checkout);
738        let result = match result {
739            Err(error)
740                if created_worktree
741                    && failure_disposition == ProvisioningFailureDisposition::Discard =>
742            {
743                return Err(self.fail_new_session_with_cleanup(session_id, error, executor)?);
744            }
745            Err(error) if failure_disposition == ProvisioningFailureDisposition::Preserve => {
746                Err(error)
747            }
748            Err(error) => {
749                // This arm (no managed worktree to unwind) is the one a
750                // provisioning failure such as a dropped target connection
751                // hits; record the diagnostic and the session-id log here too.
752                let detail = note_new_session_launch_failure(session_id, &error);
753                {
754                    let record = self.state.sessions.get_mut(session_id).unwrap();
755                    record.state = SessionState::Error;
756                    record.target = None;
757                    record.updated_at = super::now();
758                    record.last_error = Some(format!("session provisioning failed: {detail}"));
759                }
760                return match self.persist_session_state(session_id) {
761                    Ok(()) => Err(error),
762                    Err(persistence_error) => Err(error.context(format!(
763                        "persist removal of failed provisioning session {session_id}: {persistence_error:#}"
764                    ))),
765                };
766            }
767            Ok((locator, remainder, bundle, build_cache)) => {
768                apply_new_session_provisioning_result(&mut self.state, session_id, Ok(locator))?;
769                self.state
770                    .sessions
771                    .get_mut(session_id)
772                    .expect("session retained after provisioning")
773                    .build_cache = build_cache;
774                let session = &self.state.sessions[session_id];
775                let backend = backend_locator(
776                    session
777                        .target
778                        .as_ref()
779                        .context("provisioned target disappeared")?,
780                    session,
781                    &self.config,
782                )?;
783                if matches!(backend, targets::TargetLocator::AwsEc2 { .. }) {
784                    targets::provision_on_locator_plan(
785                        &backend,
786                        session_id,
787                        bundle
788                            .as_ref()
789                            .context("AWS provisioning requires a project bundle")?,
790                    )
791                } else {
792                    Ok(remainder)
793                }
794            }
795        };
796        let result = match result {
797            Err(error) if failure_disposition == ProvisioningFailureDisposition::Discard => {
798                return Err(self.rollback_failed_new_session(session_id, error)?);
799            }
800            result => result,
801        };
802        if result.is_ok() {
803            let target_template_id = self
804                .state
805                .sessions
806                .get(session_id)
807                .map(|session| session.target_template_id.clone());
808            let directory = match self.state.checkout(session_id)?.effective() {
809                mj_core::state::Checkout::ManagedWorktree { worktree, .. } => {
810                    Some(worktree.source_project_directory.clone())
811                }
812                mj_core::state::Checkout::Attached { path } => Some(path.to_path_buf()),
813                mj_core::state::Checkout::ManagedWorkspace => None,
814                mj_core::state::Checkout::Borrowed { .. } => {
815                    unreachable!("effective checkout resolves borrowing")
816                }
817            };
818            let host = target_template_id
819                .as_deref()
820                .and_then(|id| self.config.targets.get(id))
821                .and_then(|template| match template {
822                    TargetTemplate::LocalBare => Some("local".to_owned()),
823                    TargetTemplate::SshBare { ssh, .. } => Some(ssh.host.clone()),
824                    _ => None,
825                });
826            if let (Some(directory), Some(host)) = (directory, host) {
827                self.state.remember_project_directory(&host, &directory);
828                crate::database::remember_project_directory(&host, &directory)?;
829            }
830        }
831        self.persist_session_state(session_id)?;
832        result
833
834        }).await
835    }
836
837    pub fn mark_worker_connected(
838        &mut self,
839        session_id: &str,
840        native_session_id: Option<String>,
841    ) -> Result<()> {
842        let session = self
843            .state
844            .sessions
845            .get(session_id)
846            .with_context(|| format!("unknown session {session_id}"))?;
847        if session.target.is_none() {
848            bail!("session {session_id} has no provisioned target");
849        }
850        let updated_at = now();
851        crate::database::mark_session_worker_connected(
852            session_id,
853            native_session_id.as_deref(),
854            &updated_at,
855        )?;
856        let session = self
857            .state
858            .sessions
859            .get_mut(session_id)
860            .expect("session disappeared after its worker connection was saved");
861        session.state = SessionState::Running;
862        if native_session_id.is_some() {
863            session.native_session_id = native_session_id;
864        }
865        session.updated_at = updated_at;
866        session.last_error = None;
867        Ok(())
868    }
869
870    fn install_worker_payload(
871        &self,
872        session_id: &str,
873        executor: &impl CommandExecutor,
874    ) -> Result<(targets::TargetLocator, String)> {
875        // Worker/profile installation is independent of repository cloning.
876        let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
877        let (backend, worker_root) = self.worker_placement(session_id)?;
878        self.prepare_worker_files(session_id, &backend, &worker_root, syncing)?;
879        install_attached_resources(&self.state, session_id, &backend, &worker_root, syncing)?;
880        Ok((backend, worker_root))
881    }
882
883    async fn connect_and_start_worker(
884        &self,
885        session_id: &str,
886        executor: &impl CommandExecutor,
887        backend: &targets::TargetLocator,
888        worker_root: &str,
889        initialize_workspace: bool,
890    ) -> Result<Option<String>> {
891        crate::worker_lifecycle::run(session_id, "connect and start worker", executor, async {
892            let syncing = &StagedExecutor::new(executor, ProvisionStage::Syncing);
893            if initialize_workspace {
894                install_inherited_git_settings(executor, backend, session_id)?;
895                self.initialize_network_workspaces(session_id, backend, syncing)?;
896            }
897            let session = self
898                .state
899                .sessions
900                .get(session_id)
901                .with_context(|| format!("unknown session {session_id}"))?;
902            let profile = self
903                .config
904                .profiles
905                .get(&session.last_profile)
906                .with_context(|| format!("unknown profile {}", session.last_profile))?;
907            let readiness_stage = bridge_readiness_stage(profile);
908            let reconnect = &targets::reconnect_plan(backend, session_id)?.commands[0];
909            let readiness = async {
910                let mut relay = {
911                    let _starting = ProvisionStageGuard::new(executor, ProvisionStage::Starting);
912                    start_worker_durably(
913                        &crate::worker_lifecycle::require(session_id)?,
914                        self.state.sessions[session_id]
915                            .target
916                            .as_ref()
917                            .context("worker start has no durable target")?,
918                        executor,
919                        backend,
920                        worker_root,
921                    )?;
922                    connect_started_worker(reconnect, session_id, executor, backend, worker_root)
923                        .await?
924                };
925                let native_session_id = wait_for_native_session_in_stage(
926                    &mut relay,
927                    executor,
928                    readiness_stage,
929                    profile.kind,
930                )
931                .await?;
932                let owner = crate::worker_lifecycle::require(session_id)?;
933                crate::database::finish_worker_restart(session_id, owner.operation_id())?;
934                Ok(Some(native_session_id))
935            }
936            .await;
937            match readiness {
938                Ok(native_session_id) => Ok(native_session_id),
939                Err(error) => {
940                    // The diagnosis reads the worker's state, so it runs before the
941                    // worker is stopped.
942                    let error = worker_probe_diagnosis(executor, backend, worker_root, error);
943                    Err(error)
944                }
945            }
946        })
947        .await
948    }
949}
950
951const MAX_LAUNCH_DIAGNOSTIC_BYTES: usize = 64 * 1024;
952
953const RETAINED_LAUNCH_DIAGNOSTICS: usize = 20;
954
955/// Record a failed new-session launch consistently across every failure arm:
956/// log the failure with the session id (so `logs/mj-*.log` names the session)
957/// and save the local diagnostic file. Returns the underlying error chain
958/// annotated with the diagnostic path, which the caller stores in `last_error`
959/// so the reason travels to `mj sessions`, `mj wait`, and `mj events`.
960pub(super) fn note_new_session_launch_failure(session_id: &str, error: &anyhow::Error) -> String {
961    note_new_session_launch_failure_in(&data_dir().join("diagnostics"), session_id, error)
962}
963
964fn note_new_session_launch_failure_in(
965    directory: &Path,
966    session_id: &str,
967    error: &anyhow::Error,
968) -> String {
969    let original = format!("{error:#}");
970    tracing::warn!(session_id, error = %original, "session launch failed");
971    match persist_launch_failure_to(directory, session_id, &original) {
972        Ok(path) => format!("{original}; full diagnostic saved to {}", path.display()),
973        Err(save_error) => {
974            format!("{original}; saving the local diagnostic failed: {save_error:#}")
975        }
976    }
977}
978
979fn persist_launch_failure_to(directory: &Path, session_id: &str, detail: &str) -> Result<PathBuf> {
980    mj_core::config::validate_id("session", session_id)?;
981    std::fs::create_dir_all(directory).with_context(|| {
982        format!(
983            "create launch diagnostics directory {}",
984            directory.display()
985        )
986    })?;
987    #[cfg(unix)]
988    {
989        use std::os::unix::fs::PermissionsExt;
990        std::fs::set_permissions(directory, std::fs::Permissions::from_mode(0o700))?;
991    }
992    let path = directory.join(format!("{session_id}-launch-error.txt"));
993    let detail = bounded_launch_diagnostic(detail);
994    let body = format!(
995        "Mjolnir session launch failure\nsession: {session_id}\nat: {}\n\n{detail}\n",
996        now()
997    );
998    atomic_write(&path, body.as_bytes())?;
999    prune_launch_diagnostics(directory)?;
1000    Ok(path)
1001}
1002
1003fn bounded_launch_diagnostic(detail: &str) -> String {
1004    if detail.len() <= MAX_LAUNCH_DIAGNOSTIC_BYTES {
1005        return detail.to_owned();
1006    }
1007    let mut head_end = MAX_LAUNCH_DIAGNOSTIC_BYTES / 4;
1008    while !detail.is_char_boundary(head_end) {
1009        head_end -= 1;
1010    }
1011    let tail_bytes = MAX_LAUNCH_DIAGNOSTIC_BYTES - head_end;
1012    let mut tail_start = detail.len() - tail_bytes;
1013    while !detail.is_char_boundary(tail_start) {
1014        tail_start += 1;
1015    }
1016    format!(
1017        "{}\n\n[... launch diagnostic truncated ...]\n\n{}",
1018        &detail[..head_end],
1019        &detail[tail_start..]
1020    )
1021}
1022
1023fn prune_launch_diagnostics(directory: &Path) -> Result<()> {
1024    let mut diagnostics = Vec::new();
1025    for entry in std::fs::read_dir(directory)? {
1026        let entry = entry?;
1027        if !entry
1028            .file_name()
1029            .to_str()
1030            .is_some_and(|name| name.ends_with("-launch-error.txt"))
1031        {
1032            continue;
1033        }
1034        diagnostics.push((entry.metadata()?.modified()?, entry.path()));
1035    }
1036    diagnostics.sort_by_key(|entry| std::cmp::Reverse(entry.0));
1037    for (_, path) in diagnostics.into_iter().skip(RETAINED_LAUNCH_DIAGNOSTICS) {
1038        std::fs::remove_file(&path)
1039            .with_context(|| format!("prune old launch diagnostic {}", path.display()))?;
1040    }
1041    Ok(())
1042}
1043
1044fn apply_new_session_provisioning_result(
1045    state: &mut State,
1046    session_id: &str,
1047    result: Result<TargetLocator>,
1048) -> Result<()> {
1049    match result {
1050        Ok(locator) => {
1051            let record = state.sessions.get_mut(session_id).unwrap();
1052            record.target = Some(locator);
1053            // Provisioning has completed, but Running is reserved for a
1054            // successful worker handshake.
1055            record.state = SessionState::Disconnected;
1056            record.updated_at = now();
1057            record.last_error = None;
1058            Ok(())
1059        }
1060        Err(error) => {
1061            let record = state.sessions.get_mut(session_id).unwrap();
1062            record.state = SessionState::Error;
1063            record.target = None;
1064            record.updated_at = now();
1065            record.last_error = Some(format!("session provisioning failed: {error:#}"));
1066            Err(error)
1067        }
1068    }
1069}
1070
1071/// Mark a new session's launch failed while it still names its target, so the
1072/// record is true while the rollback removes that target.
1073fn apply_failed_new_session_launch(state: &mut State, session_id: &str, original_error: &str) {
1074    let record = state.sessions.get_mut(session_id).unwrap();
1075    record.state = SessionState::StartupCleanup;
1076    record.updated_at = now();
1077    record.last_error = Some(format!("worker bootstrap failed: {original_error}"));
1078}
1079
1080pub(super) fn apply_failed_new_session_rollback(
1081    state: &mut State,
1082    session_id: &str,
1083    original_error: &str,
1084    cleanup_error: Option<String>,
1085) -> anyhow::Error {
1086    match cleanup_error {
1087        None => {
1088            let record = state.sessions.get_mut(session_id).unwrap();
1089            record.state = SessionState::Error;
1090            record.target = None;
1091            record.updated_at = now();
1092            record.last_error = Some(format!("worker bootstrap failed: {original_error}"));
1093            anyhow::anyhow!("{original_error}; partial target removed and failed session retained")
1094        }
1095        Some(cleanup_error) => {
1096            let failure = format!(
1097                "{original_error}; cleanup of the failed session target failed: {cleanup_error}"
1098            );
1099            let record = state.sessions.get_mut(session_id).unwrap();
1100            record.state = SessionState::StartupCleanup;
1101            record.updated_at = now();
1102            record.last_error = Some(format!("worker bootstrap failed: {failure}"));
1103            anyhow::anyhow!(failure)
1104        }
1105    }
1106}
1107
1108pub(super) fn install_attached_resources(
1109    state: &State,
1110    session_id: &str,
1111    backend: &targets::TargetLocator,
1112    worker_root: &str,
1113    executor: &impl CommandExecutor,
1114) -> Result<()> {
1115    let targets::TargetLocator::AwsEc2 { .. } = backend else {
1116        return Ok(());
1117    };
1118    let session = state
1119        .sessions
1120        .get(session_id)
1121        .with_context(|| format!("unknown session {session_id}"))?;
1122    if session.additional_mounts.is_empty() {
1123        return Ok(());
1124    }
1125    for resource in &session.additional_mounts {
1126        let install = targets::command_on_locator(
1127            backend,
1128            session_id,
1129            vec![
1130                format!("{worker_root}/hel"),
1131                "worker".into(),
1132                "install-resource".into(),
1133                "--destination".into(),
1134                resource.destination.to_string_lossy().into_owned(),
1135            ],
1136            "stream attached resource",
1137        )?;
1138        mj_checkpoint::resources::stream_resource(&resource.source, |stream| {
1139            execute_checked_with_stdin(executor, &install, stream).map(|_| ())
1140        })
1141        .with_context(|| format!("stream attached resource {}", resource.source.display()))?;
1142    }
1143    Ok(())
1144}
1145
1146/// Run two independent target setup lanes at the same time and wait for both.
1147/// The first lane's failure wins deterministically when both fail, and neither
1148/// lane is abandoned while it may still own a transfer or subprocess.
1149pub(super) fn execute_concurrent_lanes<A: Send, B: Send>(
1150    first: impl FnOnce() -> Result<A> + Send,
1151    second: impl FnOnce() -> Result<B> + Send,
1152) -> Result<(A, B)> {
1153    std::thread::scope(|scope| {
1154        let owner = crate::worker_lifecycle::capture();
1155        let second = scope.spawn(move || match owner {
1156            Some(owner) => owner.scope_blocking(second),
1157            None => second(),
1158        });
1159        let first = first();
1160        let second = second.join().unwrap_or_else(|panic| {
1161            Err(anyhow::anyhow!(
1162                "concurrent target lane panicked: {}",
1163                targets::command_thread_panic_message(panic.as_ref())
1164            ))
1165        });
1166        match (first, second) {
1167            (Err(error), _) => Err(error),
1168            (Ok(_), Err(error)) => Err(error),
1169            (Ok(first), Ok(second)) => Ok((first, second)),
1170        }
1171    })
1172}
1173
1174fn execute_repository_setup(
1175    plan: &targets::CommandPlan,
1176    executor: &(impl CommandExecutor + Sync),
1177) -> Result<()> {
1178    if plan.commands.is_empty() {
1179        return Ok(());
1180    }
1181    let _cloning = ProvisionStageGuard::new(executor, ProvisionStage::Cloning);
1182    plan.execute_concurrent(executor).map(|_| ())
1183}
1184
1185/// Run a provisioning plan and discover the locator it produced, tearing the
1186/// target down again if anything after its creation fails.
1187///
1188/// Creation is the boundary that matters. A step that fails before the target
1189/// exists has left nothing behind; every failure after it — a later plan step
1190/// or locator discovery — owns a target no session record will point at.
1191#[cfg(test)]
1192fn provision_target(
1193    plan: &targets::CommandPlan,
1194    target: &targets::TargetTemplate,
1195    session_id: &str,
1196    executor: &(impl CommandExecutor + Sync),
1197    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1198) -> Result<TargetLocator> {
1199    let Some((creation, remainder)) = plan.split_at_target_creation() else {
1200        // Nothing this plan runs can leave a target behind.
1201        return discover(&plan.execute_concurrent(executor)?);
1202    };
1203    let mut outputs = creation.execute_concurrent(executor)?;
1204    let result = match remainder.execute_concurrent(executor) {
1205        Ok(rest) => {
1206            outputs.extend(rest);
1207            discover(&outputs)
1208        }
1209        Err(error) => Err(error),
1210    };
1211    result.map_err(|error| {
1212        match cleanup_failed_provision(target, session_id, outputs.first(), executor) {
1213            Some(note) => error.context(note),
1214            None => error,
1215        }
1216    })
1217}
1218
1219/// Bring the target into existence and return the commands that populate its
1220/// repositories. The caller may overlap that remainder with worker/profile
1221/// installation once it has persisted the discovered locator.
1222#[cfg(test)]
1223fn provision_target_creation(
1224    plan: &targets::CommandPlan,
1225    target: &targets::TargetTemplate,
1226    session_id: &str,
1227    executor: &(impl CommandExecutor + Sync),
1228    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1229) -> Result<(TargetLocator, targets::CommandPlan)> {
1230    provision_target_creation_named(
1231        plan,
1232        target,
1233        session_id,
1234        executor,
1235        &targets::resource_name(session_id)?,
1236        discover,
1237    )
1238}
1239
1240fn provision_target_creation_named(
1241    plan: &targets::CommandPlan,
1242    target: &targets::TargetTemplate,
1243    session_id: &str,
1244    executor: &(impl CommandExecutor + Sync),
1245    name: &str,
1246    discover: impl FnOnce(&[CommandOutput]) -> Result<TargetLocator>,
1247) -> Result<(TargetLocator, targets::CommandPlan)> {
1248    let Some((creation, remainder)) = plan.split_at_target_creation() else {
1249        // Nothing this plan runs can leave a target behind, so its commands
1250        // must still finish before the locator is usable.
1251        let outputs = crate::image_pull_gate::with_image_ready(target, executor, || {
1252            plan.execute_concurrent(executor)
1253        })?;
1254        return discover(&outputs).map(|locator| {
1255            (
1256                locator,
1257                targets::CommandPlan {
1258                    description: plan.description.clone(),
1259                    commands: Vec::new(),
1260                },
1261            )
1262        });
1263    };
1264    // Creating the container is what downloads the image on Docker, and the
1265    // probe just before it is what downloads it on Podman. Either way, a
1266    // background download of the same image must finish first.
1267    let outputs = crate::image_pull_gate::with_image_ready(target, executor, || {
1268        creation.execute_concurrent(executor)
1269    })?;
1270    discover(&outputs)
1271        .map(|locator| (locator, remainder))
1272        .map_err(|error| {
1273            match cleanup_failed_provision_named(
1274                target,
1275                session_id,
1276                outputs.first(),
1277                executor,
1278                name,
1279            ) {
1280                Some(note) => error.context(note),
1281                None => error,
1282            }
1283        })
1284}
1285
1286/// Best-effort teardown of a target whose creation succeeded but whose
1287/// provisioning failed before a locator was recorded. Returns a note
1288/// describing what happened for inclusion in the session error.
1289///
1290/// The teardown is the session's own close plan, so a failed launch and an
1291/// ordinary close can never disagree about what removing a target means.
1292#[cfg(test)]
1293fn cleanup_failed_provision(
1294    target: &targets::TargetTemplate,
1295    session_id: &str,
1296    create_output: Option<&CommandOutput>,
1297    executor: &impl CommandExecutor,
1298) -> Option<String> {
1299    cleanup_failed_provision_named(
1300        target,
1301        session_id,
1302        create_output,
1303        executor,
1304        &targets::resource_name(session_id).ok()?,
1305    )
1306}
1307
1308fn cleanup_failed_provision_named(
1309    target: &targets::TargetTemplate,
1310    session_id: &str,
1311    create_output: Option<&CommandOutput>,
1312    executor: &impl CommandExecutor,
1313    name: &str,
1314) -> Option<String> {
1315    let locator = provisioned_locator_named(target, session_id, create_output, name)?;
1316
1317    let leak = format!(
1318        "the resource may still exist; find it via its dev.mj.session={session_id} label/tag"
1319    );
1320    let cleanup = if name == targets::resource_name(session_id).ok()? {
1321        targets::close_plan(&locator, session_id)
1322    } else {
1323        targets::retire_move_target_plan(&locator, session_id)
1324    };
1325    let plan = match cleanup {
1326        Ok(plan) => plan,
1327        Err(error) => {
1328            tracing::warn!(
1329                session_id,
1330                error = format!("{error:#}"),
1331                "could not build provisioning cleanup plan"
1332            );
1333            return Some(format!("cleanup FAILED: {error:#}; {leak}"));
1334        }
1335    };
1336    let purpose = plan
1337        .commands
1338        .iter()
1339        .map(|command| command.purpose.clone())
1340        .collect::<Vec<_>>()
1341        .join("; ");
1342    let Err(error) = plan.execute(executor) else {
1343        return Some(format!("cleanup succeeded: {purpose}"));
1344    };
1345    match targets::cleanup_target_is_confirmed_absent(&locator, session_id, executor) {
1346        Ok(true) => Some(format!("cleanup succeeded: {purpose}")),
1347        Ok(false) => {
1348            tracing::warn!(
1349                session_id,
1350                error = format!("{error:#}"),
1351                "provisioning cleanup failed and the target may still exist"
1352            );
1353            Some(format!("cleanup FAILED ({purpose}): {error:#}; {leak}"))
1354        }
1355        Err(confirm_error) => {
1356            tracing::warn!(
1357                session_id,
1358                error = format!("{confirm_error:#}"),
1359                "could not confirm whether the failed provisioning target was removed"
1360            );
1361            Some(format!(
1362                "cleanup FAILED ({purpose}): {error:#}; checking whether it was removed also failed: {confirm_error:#}; {leak}"
1363            ))
1364        }
1365    }
1366}
1367
1368/// The locator a provisioning plan's creating command brought into existence.
1369///
1370/// Every target but AWS is named before its plan runs; an EC2 instance
1371/// reports its own ID in the launch response.
1372fn provisioned_locator_named(
1373    target: &targets::TargetTemplate,
1374    session_id: &str,
1375    create_output: Option<&CommandOutput>,
1376    name: &str,
1377) -> Option<targets::TargetLocator> {
1378    let container_id = || Some(name.to_owned());
1379
1380    Some(match target {
1381        // A bare project directory belongs to the user: provisioning creates
1382        // nothing that a failure could leak.
1383        targets::TargetTemplate::LocalBare => return None,
1384        targets::TargetTemplate::LocalPodman(container) => targets::TargetLocator::LocalPodman {
1385            borrowed_from: None,
1386            container_id: container_id()?,
1387            workspace_storage: targets::podman_workspace_locator_named(container, name).ok()?,
1388        },
1389        targets::TargetTemplate::LocalDocker(_) => targets::TargetLocator::LocalDocker {
1390            borrowed_from: None,
1391            container_id: container_id()?,
1392        },
1393        targets::TargetTemplate::AppleContainer(_) => targets::TargetLocator::AppleContainer {
1394            borrowed_from: None,
1395            container_id: container_id()?,
1396        },
1397        targets::TargetTemplate::SshPodman { ssh, container } => {
1398            targets::TargetLocator::SshPodman {
1399                borrowed_from: None,
1400                ssh: ssh.clone(),
1401                container_id: container_id()?,
1402                workspace_storage: targets::podman_workspace_locator_named(container, name).ok()?,
1403            }
1404        }
1405        targets::TargetTemplate::SshDocker { ssh, .. } => targets::TargetLocator::SshDocker {
1406            borrowed_from: None,
1407            ssh: ssh.clone(),
1408            container_id: container_id()?,
1409        },
1410        targets::TargetTemplate::SshBare { ssh, .. } => targets::TargetLocator::SshBare {
1411            ssh: ssh.clone(),
1412            workspace: targets::workspace_for(target, session_id).ok()?,
1413            worker_id: None,
1414        },
1415        targets::TargetTemplate::AwsEc2(aws) => targets::TargetLocator::AwsEc2 {
1416            profile: aws.profile.clone(),
1417            region: aws.region.clone(),
1418            instance_id: serde_json::from_slice::<serde_json::Value>(&create_output?.stdout)
1419                .ok()?
1420                .pointer("/Instances/0/InstanceId")?
1421                .as_str()?
1422                .to_owned(),
1423            ssh: aws.ssh.clone(),
1424            workspace: targets::workspace_for(target, session_id).ok()?,
1425        },
1426    })
1427}
1428
1429/// Attach read-only whatever the selected container overlay cannot hold, and
1430/// say so.
1431///
1432/// The filesystem is probed on the host that runs the container, because that
1433/// is where the overlay would be built. A probe that cannot answer leaves the
1434/// overlay alone: a failed probe is no evidence of an unsupported filesystem,
1435/// and refusing to provision over one would cost the user their session.
1436///
1437/// Apple's `container` engine already mounts every extra directory read-only,
1438/// and EC2 copies the directory instead of mounting it, so neither is probed.
1439pub(super) fn enforce_overlay_capable_mounts(
1440    target: &targets::TargetTemplate,
1441    mounts: &mut [targets::AdditionalMount],
1442    executor: &impl CommandExecutor,
1443) -> Vec<String> {
1444    let ssh = match target {
1445        targets::TargetTemplate::LocalPodman(_) | targets::TargetTemplate::LocalDocker(_) => None,
1446        targets::TargetTemplate::SshPodman { ssh, .. }
1447        | targets::TargetTemplate::SshDocker { ssh, .. } => Some(ssh),
1448        _ => return Vec::new(),
1449    };
1450    let overlaid = mounts
1451        .iter()
1452        .filter(|mount| mount.access == targets::MountAccess::Cow)
1453        .map(|mount| mount.source.clone())
1454        .collect::<Vec<_>>();
1455    if overlaid.is_empty() {
1456        return Vec::new();
1457    }
1458    // `stat` on this host cannot see what a VM-hosted Docker daemon mounts.
1459    if matches!(target, targets::TargetTemplate::LocalDocker(_)) {
1460        match targets::local_docker_vm_share(executor) {
1461            Ok(Some(reason)) => {
1462                return mounts
1463                    .iter_mut()
1464                    .filter(|mount| mount.access == targets::MountAccess::Cow)
1465                    .map(|mount| {
1466                        mount.access = mount.access.without_overlay();
1467                        format!(
1468                            "Mounted {} read-only: {reason}, which cannot back the \
1469                             copy-on-write overlay.",
1470                            mount.source.display()
1471                        )
1472                    })
1473                    .collect();
1474            }
1475            Ok(None) => {}
1476            Err(error) => tracing::warn!(
1477                error = format!("{error:#}"),
1478                "could not identify the Docker daemon platform; probing this host's filesystems"
1479            ),
1480        }
1481    }
1482    let filesystems = match targets::probe_filesystem_types(ssh, &overlaid, executor) {
1483        Ok(filesystems) => filesystems,
1484        Err(error) => {
1485            tracing::warn!(
1486                error = format!("{error:#}"),
1487                "could not probe attached-directory filesystems; preserving overlay mounts"
1488            );
1489            return vec![format!(
1490                "Could not read the filesystem under the attached directories, so they keep the \
1491                 copy-on-write overlay: {error:#}"
1492            )];
1493        }
1494    };
1495    let mut notices = Vec::new();
1496    for (mount, filesystem) in mounts
1497        .iter_mut()
1498        .filter(|mount| mount.access == targets::MountAccess::Cow)
1499        .zip(filesystems)
1500    {
1501        let Some(reason) = targets::overlay_unsupported_filesystem(&filesystem) else {
1502            continue;
1503        };
1504        mount.access = mount.access.without_overlay();
1505        notices.push(format!(
1506            "Mounted {} read-only: the overlay is unreliable on {filesystem} ({reason}).",
1507            mount.source.display()
1508        ));
1509    }
1510    notices
1511}
1512
1513/// Reports every command an installer issues as one launch stage, so progress
1514/// stays accurate without threading the stage through each `CommandSpec`.
1515/// A command that already names a stage keeps it.
1516pub(super) struct StagedExecutor<'a, E: CommandExecutor> {
1517    inner: &'a E,
1518    stage: ProvisionStage,
1519    _guard: ProvisionStageGuard<'a, E>,
1520}
1521
1522impl<'a, E: CommandExecutor> StagedExecutor<'a, E> {
1523    pub(crate) fn new(inner: &'a E, stage: ProvisionStage) -> Self {
1524        Self {
1525            inner,
1526            stage: stage.clone(),
1527            _guard: ProvisionStageGuard::new(inner, stage.clone()),
1528        }
1529    }
1530
1531    fn staged(&self, command: &CommandSpec) -> CommandSpec {
1532        if command.stage.is_some() {
1533            return command.clone();
1534        }
1535        command.clone().stage(self.stage.clone())
1536    }
1537}
1538
1539impl<E: CommandExecutor> CommandExecutor for StagedExecutor<'_, E> {
1540    fn execute(&self, command: &CommandSpec) -> Result<CommandOutput> {
1541        self.inner.execute(&self.staged(command))
1542    }
1543
1544    fn cancellation_requested(&self) -> bool {
1545        self.inner.cancellation_requested()
1546    }
1547
1548    fn stage_started(&self, stage: ProvisionStage) {
1549        self.inner.stage_started(stage);
1550    }
1551
1552    fn stage_finished(&self, stage: ProvisionStage) {
1553        self.inner.stage_finished(stage);
1554    }
1555
1556    fn notify_notice(&self, notice: &str) {
1557        self.inner.notify_notice(notice);
1558    }
1559
1560    fn execute_with_stdin(
1561        &self,
1562        command: &CommandSpec,
1563        input: &mut (dyn std::io::Read + Send),
1564    ) -> Result<CommandOutput> {
1565        self.inner.execute_with_stdin(&self.staged(command), input)
1566    }
1567}
1568
1569fn execute_checked_with_stdin(
1570    executor: &impl CommandExecutor,
1571    command: &CommandSpec,
1572    input: &mut (dyn std::io::Read + Send),
1573) -> Result<CommandOutput> {
1574    let output = executor.execute_with_stdin(command, input)?;
1575    if output.status != 0 {
1576        bail!(
1577            "{} failed with status {}: {}",
1578            command.purpose,
1579            output.status,
1580            String::from_utf8_lossy(&output.stderr)
1581        );
1582    }
1583    Ok(output)
1584}
1585
1586pub(super) fn install_inherited_git_settings(
1587    executor: &impl CommandExecutor,
1588    locator: &targets::TargetLocator,
1589    session_id: &str,
1590) -> Result<()> {
1591    let settings = if inherits_controller_git_settings(locator) {
1592        controller_git_settings()?
1593    } else {
1594        BTreeMap::new()
1595    };
1596    for command in inherited_git_setting_commands(locator, session_id, settings)? {
1597        execute_checked(executor, command)?;
1598    }
1599    Ok(())
1600}
1601
1602fn inherits_controller_git_settings(locator: &targets::TargetLocator) -> bool {
1603    !matches!(
1604        locator,
1605        targets::TargetLocator::LocalBare { .. } | targets::TargetLocator::SshBare { .. }
1606    )
1607}
1608
1609fn inherited_git_setting_commands(
1610    locator: &targets::TargetLocator,
1611    session_id: &str,
1612    settings: BTreeMap<String, String>,
1613) -> Result<Vec<CommandSpec>> {
1614    if matches!(locator, targets::TargetLocator::SshBare { .. }) {
1615        return Ok(Vec::new());
1616    }
1617    settings
1618        .into_iter()
1619        .map(|(key, value)| {
1620            let args = vec![
1621                "git".into(),
1622                "config".into(),
1623                "--global".into(),
1624                "--replace-all".into(),
1625                "--".into(),
1626                key.clone(),
1627                value,
1628            ];
1629            targets::command_on_locator(
1630                locator,
1631                session_id,
1632                args,
1633                format!("inherit Git setting {key}"),
1634            )
1635        })
1636        .collect()
1637}
1638
1639fn controller_git_settings() -> Result<BTreeMap<String, String>> {
1640    let output = match Command::new("git")
1641        .args(["config", "--global", "--includes", "--null", "--list"])
1642        .stdin(Stdio::null())
1643        .output()
1644    {
1645        Ok(output) => output,
1646        Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(BTreeMap::new()),
1647        Err(error) => return Err(error).context("read controller Git configuration"),
1648    };
1649    if !output.status.success() {
1650        bail!(
1651            "read controller Git configuration failed with status {}: {}",
1652            output.status,
1653            String::from_utf8_lossy(&output.stderr).trim()
1654        );
1655    }
1656    parse_inherited_git_settings(&output.stdout)
1657}
1658
1659fn parse_inherited_git_settings(output: &[u8]) -> Result<BTreeMap<String, String>> {
1660    let mut settings = BTreeMap::new();
1661    for entry in output
1662        .split(|byte| *byte == 0)
1663        .filter(|entry| !entry.is_empty())
1664    {
1665        let entry = std::str::from_utf8(entry).context("decode controller Git configuration")?;
1666        let (key, value) = entry
1667            .split_once('\n')
1668            .with_context(|| format!("controller Git returned malformed entry {entry:?}"))?;
1669        let key = key.to_ascii_lowercase();
1670        if INHERITED_GIT_SETTINGS.contains(&key.as_str()) {
1671            settings.insert(key, value.to_owned());
1672        }
1673    }
1674    Ok(settings)
1675}
1676
1677#[cfg(test)]
1678mod tests;