Skip to main content

mj_controller/
controller.rs

1//! Controller-side lifecycle transitions and canonical-to-backend conversion.
2
3mod backend;
4mod cache_host;
5pub(crate) mod checkpoint;
6mod git_cache;
7mod lifecycle;
8pub mod local_profile_homes;
9mod mbx;
10pub mod move_session;
11mod network_git;
12mod new_session_preflight;
13pub use new_session_preflight::{NewSessionPreflight, NewSessionRepository};
14mod path_completion;
15pub mod profile_config;
16mod provisioning;
17pub(crate) mod publication;
18mod readiness;
19pub(crate) use readiness::NATIVE_SESSION_STARTUP_TIMEOUT;
20mod recovery_scan;
21mod resume;
22mod reviewer;
23mod subagent_park;
24pub use subagent_park::ParkOutcome;
25mod subagents;
26#[cfg(test)]
27pub(crate) mod test_support;
28pub mod update;
29mod worker_binary;
30mod worker_restart;
31mod worktree;
32
33use std::collections::{BTreeMap, BTreeSet};
34use std::fs::{self, File, OpenOptions};
35use std::path::{Path, PathBuf};
36
37use anyhow::{Context, Result, bail, ensure};
38use chrono::Utc;
39
40use mj_core::config::{
41    Config, ProjectBundle, ProjectRepository, TargetTemplate, atomic_write, container_size_host,
42    data_dir, is_bare_project_target, mount_history_host,
43};
44
45use crate::import::{
46    RepositoryIdentity, bundle_matches, configured_bundle_for_local, configured_bundle_for_origin,
47    setup_style_id,
48};
49use crate::setup::github_repository_from_origin;
50
51const CONFIG_RENAME_JOURNAL: &str = "config-rename.json";
52
53#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
54#[serde(rename_all = "snake_case")]
55enum ConfigRenameKind {
56    Profile,
57    Target,
58}
59
60#[derive(Debug, serde::Serialize, serde::Deserialize)]
61#[serde(deny_unknown_fields)]
62struct ConfigRenameJournal {
63    kind: ConfigRenameKind,
64    old_id: String,
65    new_id: String,
66}
67use mj_core::state::{
68    HostContainerSize, SessionRecord, SessionResourceAllocation, SessionState, State,
69    new_session_id, normalize_session_title,
70};
71
72use crate::targets::{
73    self, AdditionalMount, CommandExecutor, CommandOutput, CommandSpec, SshTarget,
74};
75
76pub(crate) use backend::controller_github_token;
77pub use backend::image_refresh_plan;
78use backend::validate_resource_allocation;
79pub(crate) use backend::{LocalEngineReadiness, local_engine_readiness};
80pub use mbx::preview_build_cache;
81pub(crate) use mbx::{DoctorHostMbxStatus, MBX_VERSION, doctor_host_mbx};
82use provisioning::apply_failed_new_session_rollback;
83pub(crate) use worker_binary::refresh_target_worker_binary_if_stale;
84pub(crate) use worktree::path_exists_on_managed_target;
85
86pub use checkpoint::{
87    CheckpointArtifact, CheckpointDeferred, IdleWorkspaceLease, SessionExportLayout,
88    checkpoint_was_deferred, reconcile_managed_checkpoint_archives,
89};
90pub use lifecycle::{
91    BeforeClose, BranchDisposition, CheckoutDisposition, has_nothing_to_checkpoint,
92};
93pub use recovery_scan::{RecoveryCandidate, RecoveryScan};
94pub use resume::{
95    ResumeRepositorySourceMismatch, ResumeRepositorySourcePreflight, ResumeRepositorySourceReceipt,
96    raw_conversion_preview_for,
97};
98pub use reviewer::reviewer_stager;
99pub use subagents::{RegisterSubagentRequest, stopped_subagent, subagent_has_handed_back};
100pub use worker_binary::{
101    WorkerBinaryAvailability, native_worker_binary_prerequisite, pin_worker_binary_sources,
102    worker_binary_prerequisite_for_arch,
103};
104pub use worker_restart::WorkerUpgradeOutcome;
105pub use worktree::{ResumePlan, local_project_repository, resume_compatibility};
106
107pub struct Controller {
108    pub config: Config,
109    pub state: State,
110}
111
112/// Machine-wide advisory lock for one controller data store. This prevents a
113/// dashboard, server, or CLI lifecycle command from concurrently acting as a
114/// second controller against the same SQLite state and relay sessions.
115#[derive(Debug)]
116pub struct ControllerStoreGuard {
117    file: File,
118}
119
120impl ControllerStoreGuard {
121    pub fn acquire() -> Result<Self> {
122        let directory = data_dir();
123        Self::acquire_at(&directory)
124    }
125
126    fn acquire_at(directory: &Path) -> Result<Self> {
127        Self::try_acquire_at(directory)?.with_context(|| {
128            format!(
129                "another Mjolnir controller is already using {}; stop it before starting this command",
130                directory.display()
131            )
132        })
133    }
134
135    /// Probe exclusivity without treating an owner that is still exiting as an error.
136    pub fn try_acquire() -> Result<Option<Self>> {
137        Self::try_acquire_at(&data_dir())
138    }
139
140    fn try_acquire_at(directory: &Path) -> Result<Option<Self>> {
141        std::fs::create_dir_all(directory)
142            .with_context(|| format!("create controller data directory {}", directory.display()))?;
143        let path = directory.join("controller.lock");
144        let mut options = OpenOptions::new();
145        options.create(true).read(true).write(true);
146        #[cfg(unix)]
147        {
148            use std::os::unix::fs::OpenOptionsExt;
149            options.mode(0o600);
150        }
151        let file = options
152            .open(&path)
153            .with_context(|| format!("open controller lock {}", path.display()))?;
154        match file.try_lock() {
155            Ok(()) => {}
156            Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
157            Err(std::fs::TryLockError::Error(error)) => {
158                return Err(error)
159                    .with_context(|| format!("lock controller store {}", directory.display()));
160            }
161        }
162        Ok(Some(Self { file }))
163    }
164
165    /// Start the sole production SQLite writer after controller exclusivity
166    /// has been established by this guard.
167    pub fn start_database_writer(&self) -> Result<crate::database::DatabaseWriterOwner> {
168        crate::database::start_database_writer()
169    }
170}
171
172impl Drop for ControllerStoreGuard {
173    fn drop(&mut self) {
174        // Make release explicit. `File` also unlocks on close, but an explicit
175        // unlock keeps same-process handoff deterministic across platforms.
176        let _ = self.file.unlock();
177    }
178}
179
180/// The durable result of creating a quick bundle. The returned config is the
181/// same fresh config that was written, allowing a serving projection to publish
182/// the new bundle before acknowledging the request that created it.
183#[derive(Debug)]
184pub struct QuickBundleCreation {
185    pub config: Config,
186    pub bundle_id: String,
187}
188
189/// Failure stages exposed to a viewer request without exposing the underlying
190/// filesystem/configuration error. The detailed error remains available to
191/// the caller for logs and terminal notices.
192#[derive(Debug)]
193pub enum QuickBundleFailure {
194    InvalidSource(anyhow::Error),
195    Persistence(anyhow::Error),
196}
197
198impl std::fmt::Display for QuickBundleFailure {
199    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        match self {
201            Self::InvalidSource(error) => write!(formatter, "invalid repository source: {error}"),
202            Self::Persistence(error) => write!(formatter, "persist quick bundle: {error}"),
203        }
204    }
205}
206
207impl std::error::Error for QuickBundleFailure {
208    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
209        match self {
210            Self::InvalidSource(error) | Self::Persistence(error) => Some(error.root_cause()),
211        }
212    }
213}
214
215/// Create a quick bundle from a local repository or GitHub source and persist
216/// it as one serialized fresh-config transaction. Identical sources reuse the
217/// existing configured bundle, matching the terminal's behavior. The returned
218/// config is the same fresh config that was written, allowing a serving
219/// projection to publish the new bundle before acknowledging the request.
220pub fn create_quick_bundle(
221    source: &str,
222) -> std::result::Result<QuickBundleCreation, QuickBundleFailure> {
223    let (config, bundle_id) = Config::update(|config| {
224        create_quick_bundle_in_config(config, source)
225            .map_err(|error| anyhow::Error::new(QuickBundleFailure::InvalidSource(error)))
226    })
227    .map_err(|error| {
228        error
229            .downcast::<QuickBundleFailure>()
230            .unwrap_or_else(QuickBundleFailure::Persistence)
231    })?;
232    Ok(QuickBundleCreation { config, bundle_id })
233}
234
235/// Add a quick bundle to an already-loaded config. The helper still performs
236/// the local repository canonicalization/GitHub-source parsing, but callers
237/// that persist a config should use [`create_quick_bundle`] so concurrent saves
238/// cannot clobber one another.
239pub fn create_quick_bundle_in_config(config: &mut Config, source: &str) -> Result<String> {
240    let source = interpret_repository_source(source)?;
241    let existing = match &source.kind {
242        RepositorySourceKind::Local(root) => configured_bundle_for_local(config, root),
243        RepositorySourceKind::Github(repository) => {
244            configured_bundle_for_origin(config, repository)
245        }
246    };
247    if let Some(existing) = existing {
248        return Ok(existing);
249    }
250    let repository_id = setup_style_id(&source.name);
251    let mut bundle_id = repository_id.clone();
252    for suffix in 2_u32.. {
253        if !config.bundles.contains_key(&bundle_id) {
254            break;
255        }
256        bundle_id = format!("{repository_id}-{suffix}");
257    }
258    config.bundles.insert(
259        bundle_id.clone(),
260        ProjectBundle {
261            primary_repo: repository_id.clone(),
262            repositories: vec![source.into_project_repository(repository_id.clone())],
263        },
264    );
265    config.validate()?;
266    Ok(bundle_id)
267}
268
269/// Create one bundle from one or more local repositories or GitHub sources.
270///
271/// All sources are interpreted and checked before the config transaction can
272/// write anything. An existing bundle is reused only when its repository set
273/// and primary repository exactly match the request; this keeps selecting one
274/// repository from a larger bundle from silently changing the wizard's choice.
275pub fn create_bundle_from_sources(
276    sources: &[String],
277) -> std::result::Result<QuickBundleCreation, QuickBundleFailure> {
278    let (config, bundle_id) = Config::update(|config| {
279        create_bundle_from_sources_in_config(config, sources)
280            .map_err(|error| anyhow::Error::new(QuickBundleFailure::InvalidSource(error)))
281    })
282    .map_err(|error| {
283        error
284            .downcast::<QuickBundleFailure>()
285            .unwrap_or_else(QuickBundleFailure::Persistence)
286    })?;
287    Ok(QuickBundleCreation { config, bundle_id })
288}
289
290/// Add a bundle for all `sources` to an already-loaded config. The source
291/// interpretation is shared with the persisted [`create_bundle_from_sources`]
292/// entry point and the legacy quick-bundle helper.
293pub fn create_bundle_from_sources_in_config(
294    config: &mut Config,
295    sources: &[String],
296) -> Result<String> {
297    let sources = sources
298        .iter()
299        .map(|source| interpret_repository_source(source))
300        .collect::<Result<Vec<_>>>()?;
301    if sources.is_empty() {
302        bail!("at least one repository source is required");
303    }
304
305    let mut identities = BTreeSet::new();
306    for source in &sources {
307        if !identities.insert(source.identity()) {
308            bail!("duplicate repository source {:?}", source.display_name);
309        }
310    }
311
312    if let Some(existing) = exact_configured_bundle(config, &sources) {
313        return Ok(existing);
314    }
315
316    // Build and validate a candidate before replacing the caller's config, so
317    // a later validation error cannot leave an in-memory partial mutation.
318    let mut updated = config.clone();
319    let mut used_repository_ids = BTreeSet::new();
320    let mut repositories = Vec::with_capacity(sources.len());
321    for source in sources {
322        let base = setup_style_id(&source.name);
323        let repository_id = unique_id(&base, |candidate| used_repository_ids.contains(candidate));
324        used_repository_ids.insert(repository_id.clone());
325        repositories.push(source.into_project_repository(repository_id));
326    }
327    let primary_repo = repositories
328        .first()
329        .map(|repository| repository.id.clone())
330        .context("at least one repository source is required")?;
331    let bundle_id = unique_id(&primary_repo, |candidate| {
332        updated.bundles.contains_key(candidate)
333    });
334    updated.bundles.insert(
335        bundle_id.clone(),
336        ProjectBundle {
337            primary_repo,
338            repositories,
339        },
340    );
341    updated.validate()?;
342    *config = updated;
343    Ok(bundle_id)
344}
345
346#[derive(Debug, Clone)]
347enum RepositorySourceKind {
348    Github(crate::setup::GithubRepository),
349    Local(PathBuf),
350}
351
352#[derive(Debug, Clone)]
353struct InterpretedRepositorySource {
354    display_name: String,
355    name: String,
356    kind: RepositorySourceKind,
357}
358
359impl InterpretedRepositorySource {
360    fn identity(&self) -> RepositoryIdentity {
361        match &self.kind {
362            RepositorySourceKind::Github(repository) => RepositoryIdentity::Github(
363                repository.owner.to_ascii_lowercase(),
364                repository.repository.to_ascii_lowercase(),
365            ),
366            RepositorySourceKind::Local(root) => RepositoryIdentity::Local(root.clone()),
367        }
368    }
369
370    fn into_project_repository(self, id: String) -> ProjectRepository {
371        let (github, local) = match self.kind {
372            RepositorySourceKind::Github(repository) => (
373                Some(format!("{}/{}", repository.owner, repository.repository)),
374                None,
375            ),
376            RepositorySourceKind::Local(root) => (None, Some(root)),
377        };
378        ProjectRepository {
379            id: id.clone(),
380            github,
381            local,
382            destination: PathBuf::from(id),
383            git_ref: None,
384        }
385    }
386}
387
388/// Interpret a source once, including local Git canonicalization and GitHub
389/// parsing, so all creation paths use exactly the same source semantics.
390fn interpret_repository_source(source: &str) -> Result<InterpretedRepositorySource> {
391    let source = source.trim();
392    if source.is_empty() {
393        bail!("repository source cannot be empty");
394    }
395    let expanded = mj_core::path_input::expand_local(Path::new(source))?;
396    let candidate = expanded.as_path();
397    if candidate.exists() {
398        let root = mj_core::local_git::canonical_repository(candidate)?;
399        let name = root
400            .file_name()
401            .and_then(|name| name.to_str())
402            .context("local repository has no usable directory name")?
403            .to_owned();
404        return Ok(InterpretedRepositorySource {
405            display_name: source.to_owned(),
406            name,
407            kind: RepositorySourceKind::Local(root),
408        });
409    }
410    if candidate.is_absolute() || source.starts_with('.') || source.starts_with('~') {
411        bail!("local repository path {source:?} does not exist");
412    }
413    let repository = github_repository_from_origin(source).context(format!(
414        "{source:?} is not a GitHub owner/repository or URL"
415    ))?;
416    Ok(InterpretedRepositorySource {
417        display_name: source.to_owned(),
418        name: repository.repository.clone(),
419        kind: RepositorySourceKind::Github(repository),
420    })
421}
422
423fn exact_configured_bundle(
424    config: &Config,
425    requested: &[InterpretedRepositorySource],
426) -> Option<String> {
427    let requested_identities = requested
428        .iter()
429        .map(InterpretedRepositorySource::identity)
430        .collect::<BTreeSet<_>>();
431    let primary = requested.first()?.identity();
432    config.bundles.iter().find_map(|(id, bundle)| {
433        if bundle.repositories.len() != requested.len()
434            || bundle
435                .repositories
436                .iter()
437                .any(|repository| repository.git_ref.is_some())
438        {
439            return None;
440        }
441        bundle_matches(bundle, &requested_identities, &primary).then(|| id.clone())
442    })
443}
444
445fn unique_id(base: &str, mut is_used: impl FnMut(&str) -> bool) -> String {
446    if !is_used(base) {
447        return base.to_owned();
448    }
449    for suffix in 2_u32.. {
450        let suffix = format!("-{suffix}");
451        let prefix_len = 64usize.saturating_sub(suffix.len());
452        let prefix = base.chars().take(prefix_len).collect::<String>();
453        let candidate = format!("{prefix}{suffix}");
454        if !is_used(&candidate) {
455            return candidate;
456        }
457    }
458    unreachable!("u32 repository/bundle id suffixes exhausted")
459}
460
461pub struct SessionLaunchOptions {
462    pub create_managed_worktree: Option<bool>,
463    pub launch_base: Option<String>,
464    pub launch_branch: Option<String>,
465    pub mjolnir_subagents: Option<bool>,
466    pub initial_prompt: Option<String>,
467    pub workspace_id: String,
468    pub additional_mounts: Vec<AdditionalMount>,
469    pub resource_allocation: Option<SessionResourceAllocation>,
470    pub project_directory: Option<PathBuf>,
471    pub session_title_override: Option<String>,
472}
473
474pub struct SessionResumeOptions {
475    pub additional_mounts: Option<Vec<AdditionalMount>>,
476    pub resource_allocation: Option<SessionResourceAllocation>,
477    pub discard_queue: bool,
478}
479
480fn selected_host_container_size(
481    template: &TargetTemplate,
482    allocation: Option<&SessionResourceAllocation>,
483) -> Option<(String, HostContainerSize)> {
484    let host = container_size_host(template)?;
485    let SessionResourceAllocation::Container { cpus, memory_bytes } = allocation? else {
486        return None;
487    };
488    Some((
489        host.to_owned(),
490        HostContainerSize {
491            cpus: *cpus,
492            memory_bytes: *memory_bytes,
493        },
494    ))
495}
496
497impl Controller {
498    pub fn load() -> Result<Self> {
499        let config = Config::load()?;
500        let state = crate::database::load_state()?;
501        // Missing session dependencies must not lock users out of the tools
502        // needed to repair them. Operations validate the session they act on.
503        state.validate()?;
504        for session in state.sessions.values() {
505            if let Some(issue) = session.configuration_issue(&config) {
506                tracing::warn!(session_id = %session.id, "{issue}");
507            }
508        }
509        let mut controller = Self { config, state };
510        controller.backfill_target_runtime()?;
511        Ok(controller)
512    }
513
514    pub fn reload(&mut self) -> Result<()> {
515        // Capture legacy settings from the previous config before a manual
516        // edit removes them. Only fill missing metadata, never overwrite it.
517        self.backfill_target_runtime()?;
518        *self = Self::load()?;
519        Ok(())
520    }
521
522    fn backfill_target_runtime(&mut self) -> Result<()> {
523        for session in self.state.sessions.values_mut() {
524            if session.target_runtime.is_some() {
525                continue;
526            }
527            match session.target_runtime_settings(&self.config) {
528                Ok(runtime) => {
529                    let runtime = runtime.into_owned();
530                    session.target_runtime = crate::database::backfill_target_runtime(
531                        &session.id,
532                        &session.target_template_id,
533                        &runtime,
534                    )?;
535                }
536                Err(error) => {
537                    tracing::warn!(session_id = %session.id, %error, "target access needs configuration repair")
538                }
539            }
540        }
541        Ok(())
542    }
543
544    fn persist_session_state(&self, session_id: &str) -> Result<()> {
545        match self.state.sessions.get(session_id) {
546            Some(session) => crate::database::save_lifecycle_session(session),
547            None => crate::database::delete_session(session_id),
548        }
549    }
550
551    fn persist_session_transition_or_restore(
552        &mut self,
553        session_id: &str,
554        previous: &SessionRecord,
555        context: &'static str,
556    ) -> Result<()> {
557        persist_session_record_transition_or_restore(
558            &mut self.state,
559            session_id,
560            previous,
561            context,
562            &crate::database::save_lifecycle_session,
563        )
564    }
565
566    fn restore_prior_session_after_persistence_failure(
567        &mut self,
568        session_id: &str,
569        previous: &SessionRecord,
570        primary: anyhow::Error,
571    ) -> anyhow::Error {
572        restore_session_after_persistence_failure(
573            &mut self.state,
574            session_id,
575            previous,
576            primary,
577            crate::database::save_lifecycle_session,
578        )
579    }
580
581    /// Resolve an entered path on its owning host. Call only from background work.
582    pub fn resolve_input_path(
583        &self,
584        target_id: &str,
585        path: &Path,
586        executor: &impl CommandExecutor,
587    ) -> Result<PathBuf> {
588        let target = self
589            .config
590            .targets
591            .get(target_id)
592            .context("Unknown path target")?;
593        resolve_target_input_path(target, path, executor)
594    }
595
596    /// Verify a mount source on the host where Mjolnir will consume it, and report
597    /// the filesystem reason it must be attached read-only, if there is one.
598    ///
599    /// The probe runs in the same round trip as the existence check so the
600    /// editor learns both answers without a second wait. A probe that cannot
601    /// answer reports no reason: provisioning decides that authoritatively.
602    pub fn validate_mount_source(
603        &self,
604        target_id: &str,
605        source: &Path,
606        executor: &impl CommandExecutor,
607    ) -> Result<Option<String>> {
608        let target = self
609            .config
610            .targets
611            .get(target_id)
612            .with_context(|| format!("unknown target template {target_id:?}"))?;
613        let exists = match target {
614            TargetTemplate::LocalPodman { .. }
615            | TargetTemplate::LocalDocker { .. }
616            | TargetTemplate::AppleContainer { .. }
617            | TargetTemplate::AwsEc2 { .. } => std::fs::metadata(source)
618                .map(|metadata| metadata.is_dir())
619                .or_else(|error| {
620                    if error.kind() == std::io::ErrorKind::NotFound {
621                        Ok(false)
622                    } else {
623                        Err(error)
624                    }
625                })
626                .with_context(|| format!("inspect resource source {}", source.display()))?,
627            TargetTemplate::SshPodman { ssh, .. } | TargetTemplate::SshDocker { ssh, .. } => {
628                targets::ssh_directory_exists(&SshTarget::from(ssh), source, executor)?
629            }
630            TargetTemplate::LocalBare | TargetTemplate::SshBare { .. } => {
631                bail!("resource attachments are unsupported for bare targets")
632            }
633        };
634        ensure!(
635            exists,
636            "source path {} does not exist or is not a directory",
637            source.display()
638        );
639        Ok(self.forced_read_only_reason(target, source, executor))
640    }
641
642    /// The `filesystem (reason)` label for a source the runtime cannot overlay.
643    fn forced_read_only_reason(
644        &self,
645        target: &TargetTemplate,
646        source: &Path,
647        executor: &impl CommandExecutor,
648    ) -> Option<String> {
649        let ssh = match target {
650            TargetTemplate::LocalPodman { .. } | TargetTemplate::LocalDocker { .. } => None,
651            TargetTemplate::SshPodman { ssh, .. } | TargetTemplate::SshDocker { ssh, .. } => {
652                Some(SshTarget::from(ssh))
653            }
654            // Apple Container already mounts read-only, and EC2 copies instead
655            // of mounting, so neither has an overlay to lose.
656            _ => return None,
657        };
658        let filesystem = targets::probe_filesystem_types(
659            ssh.as_ref(),
660            std::slice::from_ref(&source.to_path_buf()),
661            executor,
662        )
663        .map_err(|error| {
664            tracing::debug!(
665                source = %source.display(),
666                error = format!("{error:#}"),
667                "could not probe the filesystem under a mount source"
668            );
669        })
670        .ok()?
671        .pop()?;
672        let reason = targets::overlay_unsupported_filesystem(&filesystem)?;
673        Some(format!("{filesystem} ({reason})"))
674    }
675
676    fn fail_new_session_with_cleanup(
677        &mut self,
678        session_id: &str,
679        error: anyhow::Error,
680        executor: &impl CommandExecutor,
681    ) -> Result<anyhow::Error> {
682        let original = provisioning::note_new_session_launch_failure(session_id, &error);
683        let cleanup_error = self
684            .cleanup_new_session_worktree_after_failure(session_id, executor)
685            .err()
686            .map(|cleanup_error| format!("{cleanup_error:#}"));
687        if let Some(cleanup_error) = &cleanup_error {
688            tracing::warn!(
689                session_id,
690                error = %cleanup_error,
691                "new-session worktree rollback reported a cleanup failure"
692            );
693        }
694        let failure = apply_failed_new_session_rollback(
695            &mut self.state,
696            session_id,
697            &original,
698            cleanup_error,
699        );
700        self.persist_session_state(session_id)?;
701        Ok(failure)
702    }
703
704    pub fn register_session_with_resources(
705        &mut self,
706        profile_id: &str,
707        bundle_id: &str,
708        target_id: &str,
709        title: impl Into<String>,
710        options: SessionLaunchOptions,
711    ) -> Result<String> {
712        let SessionLaunchOptions {
713            create_managed_worktree,
714            launch_base,
715            launch_branch,
716            mjolnir_subagents,
717            initial_prompt,
718            workspace_id,
719            additional_mounts,
720            resource_allocation,
721            project_directory,
722            session_title_override,
723        } = options;
724        let launch_base = match launch_base {
725            Some(base) => {
726                let base = base.trim();
727                if base.is_empty() {
728                    bail!("launch base must not be empty");
729                }
730                Some(base.to_owned())
731            }
732            None => None,
733        };
734        let launch_branch = match launch_branch {
735            Some(branch) => {
736                let branch = branch.trim();
737                ensure!(!branch.is_empty(), "launch branch must not be empty");
738                Some(branch.to_owned())
739            }
740            None => None,
741        };
742        if launch_base.is_some() && create_managed_worktree == Some(false) {
743            bail!("a launch base requires a managed worktree or a bundle session");
744        }
745        let session_title_override = match session_title_override {
746            Some(title) => {
747                Some(normalize_session_title(&title).context("session name cannot be empty")?)
748            }
749            None => None,
750        };
751        let profile = self
752            .config
753            .profiles
754            .get(profile_id)
755            .with_context(|| format!("unknown profile {profile_id:?}"))?;
756        ensure!(profile.enabled, "profile {profile_id:?} is disabled");
757        let template = self
758            .config
759            .targets
760            .get(target_id)
761            .with_context(|| format!("unknown target template {target_id:?}"))?;
762        if create_managed_worktree == Some(true) && !is_bare_project_target(template) {
763            bail!("managed worktree creation requires a bare Git project");
764        }
765        if project_directory.is_some() != is_bare_project_target(template) {
766            bail!("raw project directories require a bare target, and bare targets require one");
767        }
768        if let Some(path) = &project_directory
769            && (!path.is_absolute()
770                || path
771                    .components()
772                    .any(|part| part == std::path::Component::ParentDir))
773        {
774            bail!("bare project directory must be an absolute safe path");
775        }
776        let bundle = project_directory
777            .is_none()
778            .then(|| self.config.bundles.get(bundle_id))
779            .flatten();
780        if project_directory.is_none() && bundle.is_none() {
781            bail!("unknown bundle {bundle_id:?}");
782        }
783        if profile.kind == mj_core::config::HarnessKind::Muse
784            && (!additional_mounts.is_empty()
785                || bundle.is_some_and(|bundle| bundle.repositories.len() > 1))
786        {
787            bail!(
788                "{} ACP supports one workspace root; use a single-repository bundle without attached directories",
789                profile.kind.display_name()
790            );
791        }
792        if let Some(bundle) = bundle {
793            for repository in &bundle.repositories {
794                mj_core::remote_git::resolve_repository(
795                    repository,
796                    &targets::CancellableProcessExecutor::with_timeout(
797                        std::time::Duration::from_secs(15),
798                    ),
799                )
800                .with_context(|| format!("repository {:?}", repository.id))?;
801            }
802        }
803        validate_resource_allocation(template, resource_allocation.as_ref())?;
804        let selected_container_size =
805            selected_host_container_size(template, resource_allocation.as_ref());
806        if !additional_mounts.is_empty() && mount_history_host(template).is_none() {
807            bail!("attached resources are unsupported for this target");
808        }
809        targets::validate_additional_mounts(&additional_mounts)?;
810        let id = new_session_id()?;
811        let now = now();
812        let record = SessionRecord {
813            target_runtime: Some(template.into()),
814            build_cache: None,
815            create_managed_worktree,
816            launch_base,
817            launch_branch,
818            publication: None,
819            mjolnir_subagents,
820            archived: false,
821            container_cpus: None,
822            container_memory: None,
823            // Recorded for every new session, container-backed or not, so a
824            // later move into a container already knows the path its checkout
825            // will occupy. Only sessions that predate per-session container
826            // workspaces leave it unset.
827            container_workspace: Some(targets::new_container_workspace(&id)?),
828            id: id.clone(),
829            workspace_id,
830            title: title.into(),
831            harness_kind: profile.kind,
832            last_profile: profile_id.to_string(),
833            bundle_id: bundle_id.to_string(),
834            project_directory,
835            managed_worktree: None,
836            target_template_id: target_id.to_string(),
837            resource_allocation,
838            additional_mounts: additional_mounts.clone(),
839            state: SessionState::Provisioning,
840            target: None,
841            native_session_id: None,
842            acp_session_title: None,
843            session_title_override,
844            created_at: now.clone(),
845            updated_at: now,
846            viewed_through_event_ordinal: 0,
847            draft_input: initial_prompt.unwrap_or_default(),
848            last_error: None,
849            last_checkpoint_error: None,
850            checkpoint: None,
851        };
852        // Creation authors the whole record, so it writes the whole row. The
853        // record reaches memory only once it is durable: a session this process
854        // alone knows about is one the database can never resume or clean up.
855        if let Some((host, size)) = selected_container_size.as_ref() {
856            crate::database::save_session_with_container_size(&record, host, *size)?;
857        } else {
858            crate::database::save_session(&record)?;
859        }
860        self.state.sessions.insert(id.clone(), record);
861        if let Some((host, size)) = selected_container_size {
862            self.state.remember_container_size(&host, size);
863        }
864        if let Some(host) = mount_history_host(template) {
865            // Mount history only seeds the attach dialog's suggestions. The
866            // session row is already committed, so a failed suggestion write is
867            // reported rather than turned into a failed registration.
868            match crate::database::remember_mount_sources(host, &additional_mounts) {
869                Ok(()) => self.state.remember_mount_sources(host, &additional_mounts),
870                Err(error) => tracing::warn!(
871                    session_id = id,
872                    error = format!("{error:#}"),
873                    "could not remember the attached resource directories for later suggestions"
874                ),
875            }
876        }
877        Ok(id)
878    }
879
880    pub fn rename_session(&mut self, session_id: &str, title: &str) -> Result<String> {
881        let title = normalize_session_title(title).context("session name cannot be empty")?;
882        ensure!(
883            self.state.sessions.contains_key(session_id),
884            "unknown session {session_id}"
885        );
886        let updated_at = now();
887        crate::database::set_session_title_override(session_id, &title, &updated_at)?;
888        let record = self
889            .state
890            .sessions
891            .get_mut(session_id)
892            .expect("session was checked before updating its title");
893        record.session_title_override = Some(title.clone());
894        record.updated_at = updated_at;
895        Ok(title)
896    }
897
898    pub fn rename_profile_id(&mut self, old_id: &str, new_id: &str) -> Result<()> {
899        mj_core::config::validate_id("profile", new_id)?;
900        if old_id == new_id {
901            ensure!(
902                self.config.profiles.contains_key(old_id),
903                "unknown profile {old_id:?}"
904            );
905            return Ok(());
906        }
907        let journal = ConfigRenameJournal {
908            kind: ConfigRenameKind::Profile,
909            old_id: old_id.to_owned(),
910            new_id: new_id.to_owned(),
911        };
912        write_config_rename_journal(&journal)?;
913        let (config, ()) = match Config::update(|config| {
914            ensure!(
915                config.profiles.contains_key(old_id),
916                "unknown profile {old_id:?}"
917            );
918            ensure!(
919                !config.profiles.contains_key(new_id),
920                "profile {new_id:?} already exists"
921            );
922            let profile = config
923                .profiles
924                .remove(old_id)
925                .expect("profile was checked in the transaction");
926            config.profiles.insert(new_id.to_owned(), profile);
927            Ok(())
928        }) {
929            Ok(result) => result,
930            Err(error) => {
931                remove_config_rename_journal()
932                    .context("remove profile rename journal after config save failed")?;
933                return Err(error).context("save renamed profile configuration");
934            }
935        };
936        self.config = config;
937        mj_core::test_hooks::reach_test_hook("config_replacement_before_reference_migration")?;
938        if let Err(error) = crate::database::rename_profile_references(old_id, new_id) {
939            let restore = Config::update(|config| {
940                let profile = config
941                    .profiles
942                    .remove(new_id)
943                    .with_context(|| format!("renamed profile {new_id:?} is missing"))?;
944                ensure!(
945                    !config.profiles.contains_key(old_id),
946                    "cannot restore profile rename: both {old_id:?} and {new_id:?} exist"
947                );
948                config.profiles.insert(old_id.to_owned(), profile);
949                Ok(())
950            });
951            let restored = match restore {
952                Ok((config, ())) => config,
953                Err(restore_error) => {
954                    return Err(error).context(format!(
955                        "rename profile references; additionally failed to restore config: {restore_error:#}"
956                    ));
957                }
958            };
959            self.config = restored;
960            if let Err(restore_error) = remove_config_rename_journal() {
961                return Err(error).context(format!(
962                    "rename profile references; additionally failed to remove rename journal: {restore_error:#}"
963                ));
964            }
965            return Err(error).context("rename profile references");
966        }
967        for session in self.state.sessions.values_mut() {
968            if session.last_profile == old_id {
969                session.last_profile = new_id.to_owned();
970            }
971        }
972        remove_config_rename_journal()?;
973        Ok(())
974    }
975
976    pub fn rename_target_id(&mut self, old_id: &str, new_id: &str) -> Result<()> {
977        mj_core::config::validate_id("target template", new_id)?;
978        if old_id == new_id {
979            ensure!(
980                self.config.targets.contains_key(old_id),
981                "unknown target {old_id:?}"
982            );
983            return Ok(());
984        }
985        let journal = ConfigRenameJournal {
986            kind: ConfigRenameKind::Target,
987            old_id: old_id.to_owned(),
988            new_id: new_id.to_owned(),
989        };
990        write_config_rename_journal(&journal)?;
991        let (config, ()) = match Config::update(|config| {
992            ensure!(
993                config.targets.contains_key(old_id),
994                "unknown target {old_id:?}"
995            );
996            ensure!(
997                !config.targets.contains_key(new_id),
998                "target {new_id:?} already exists"
999            );
1000            let target = config
1001                .targets
1002                .remove(old_id)
1003                .expect("target was checked in the transaction");
1004            config.targets.insert(new_id.to_owned(), target);
1005            Ok(())
1006        }) {
1007            Ok(result) => result,
1008            Err(error) => {
1009                remove_config_rename_journal()
1010                    .context("remove target rename journal after config save failed")?;
1011                return Err(error).context("save renamed target configuration");
1012            }
1013        };
1014        self.config = config;
1015        mj_core::test_hooks::reach_test_hook("config_replacement_before_reference_migration")?;
1016        if let Err(error) = crate::database::rename_target_references(old_id, new_id) {
1017            let restore = Config::update(|config| {
1018                let target = config
1019                    .targets
1020                    .remove(new_id)
1021                    .with_context(|| format!("renamed target {new_id:?} is missing"))?;
1022                ensure!(
1023                    !config.targets.contains_key(old_id),
1024                    "cannot restore target rename: both {old_id:?} and {new_id:?} exist"
1025                );
1026                config.targets.insert(old_id.to_owned(), target);
1027                Ok(())
1028            });
1029            let restored = match restore {
1030                Ok((config, ())) => config,
1031                Err(restore_error) => {
1032                    return Err(error).context(format!(
1033                        "rename target references; additionally failed to restore config: {restore_error:#}"
1034                    ));
1035                }
1036            };
1037            self.config = restored;
1038            if let Err(restore_error) = remove_config_rename_journal() {
1039                return Err(error).context(format!(
1040                    "rename target references; additionally failed to remove rename journal: {restore_error:#}"
1041                ));
1042            }
1043            return Err(error).context("rename target references");
1044        }
1045        for session in self.state.sessions.values_mut() {
1046            if session.target_template_id == old_id {
1047                session.target_template_id = new_id.to_owned();
1048            }
1049        }
1050        remove_config_rename_journal()?;
1051        Ok(())
1052    }
1053
1054    /// Finish a profile/target id rename interrupted between the atomic config
1055    /// replacement and SQLite transaction. Each step is idempotent, so a
1056    /// second crash leaves the same intent available for the next startup.
1057    pub fn recover_config_id_rename() -> Result<bool> {
1058        let path = config_rename_journal_path();
1059        let body = match fs::read(&path) {
1060            Ok(body) => body,
1061            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1062            Err(error) => return Err(error).context(format!("read {}", path.display())),
1063        };
1064        let journal: ConfigRenameJournal =
1065            serde_json::from_slice(&body).with_context(|| format!("parse {}", path.display()))?;
1066        match journal.kind {
1067            ConfigRenameKind::Profile => {
1068                Config::update(|config| {
1069                    finish_config_map_rename(
1070                        &mut config.profiles,
1071                        &journal.old_id,
1072                        &journal.new_id,
1073                        "profile",
1074                    )?;
1075                    Ok(())
1076                })?;
1077                crate::database::rename_profile_references(&journal.old_id, &journal.new_id)?;
1078            }
1079            ConfigRenameKind::Target => {
1080                // The file's own entries, not `Config::update`'s view: that one
1081                // adds the standard local targets, so after a built-in id such
1082                // as `localhost` was renamed away, its default would reappear
1083                // beside the new id and read as a rename that cannot finish.
1084                Config::update_to(&mj_core::config::config_path(), |config| {
1085                    finish_config_map_rename(
1086                        &mut config.targets,
1087                        &journal.old_id,
1088                        &journal.new_id,
1089                        "target",
1090                    )?;
1091                    Ok(())
1092                })?;
1093                crate::database::rename_target_references(&journal.old_id, &journal.new_id)?;
1094            }
1095        }
1096        remove_config_rename_journal()?;
1097        Ok(true)
1098    }
1099
1100    /// Record the per-session container size overrides and attached
1101    /// directories. Nothing is applied to a running container: the values are
1102    /// read the next time the session's container is created.
1103    pub fn update_session_container_settings(
1104        &mut self,
1105        session_id: &str,
1106        cpus: Option<String>,
1107        memory: Option<String>,
1108        additional_mounts: Vec<targets::AdditionalMount>,
1109        mount_history: Vec<std::path::PathBuf>,
1110        executor: &impl CommandExecutor,
1111    ) -> Result<()> {
1112        let session = self
1113            .state
1114            .sessions
1115            .get(session_id)
1116            .with_context(|| format!("unknown session {session_id}"))?;
1117        // A directory the runtime cannot find is created by Docker, owned by
1118        // root, when the container is recreated (launch finding J-24). Check
1119        // each newly attached source where the container will read it: on
1120        // this host for a local runtime, over the machine's connection for an
1121        // SSH one. A directory already attached was checked when it was
1122        // added, and a size change must not fail because it has since gone.
1123        for mount in &additional_mounts {
1124            if session
1125                .additional_mounts
1126                .iter()
1127                .any(|attached| attached.source == mount.source)
1128            {
1129                continue;
1130            }
1131            self.validate_mount_source(&session.target_template_id, &mount.source, executor)?;
1132        }
1133        let cpus = cpus.filter(|value| !value.trim().is_empty());
1134        let memory = memory.filter(|value| !value.trim().is_empty());
1135        let updated_at = now();
1136        crate::database::set_session_container_settings(
1137            session_id,
1138            cpus.as_deref(),
1139            memory.as_deref(),
1140            &additional_mounts,
1141            &updated_at,
1142        )?;
1143        if let Some(host) = self
1144            .config
1145            .targets
1146            .get(
1147                &self.state.sessions[session_id]
1148                    .target_template_id
1149                    .to_owned(),
1150            )
1151            .and_then(mj_core::config::mount_history_host)
1152        {
1153            let host = host.to_owned();
1154            // The dialog owns the suggestion list, so forgetting a directory
1155            // there has to survive the mounts being remembered right after.
1156            crate::database::replace_mount_history(&host, &mount_history)?;
1157            crate::database::remember_mount_sources(&host, &additional_mounts)?;
1158            self.state.mount_history.insert(host.clone(), mount_history);
1159            self.state.remember_mount_sources(&host, &additional_mounts);
1160        }
1161        let record = self
1162            .state
1163            .sessions
1164            .get_mut(session_id)
1165            .expect("session was checked before updating its container settings");
1166        record.container_cpus = cpus;
1167        record.container_memory = memory;
1168        record.additional_mounts = additional_mounts;
1169        record.updated_at = updated_at;
1170        Ok(())
1171    }
1172}
1173
1174fn config_rename_journal_path() -> PathBuf {
1175    data_dir().join(CONFIG_RENAME_JOURNAL)
1176}
1177
1178fn write_config_rename_journal(journal: &ConfigRenameJournal) -> Result<()> {
1179    let path = config_rename_journal_path();
1180    let body = serde_json::to_vec(journal).context("serialize config rename journal")?;
1181    atomic_write(&path, &body).with_context(|| format!("write {}", path.display()))
1182}
1183
1184fn remove_config_rename_journal() -> Result<()> {
1185    let path = config_rename_journal_path();
1186    match fs::remove_file(&path) {
1187        Ok(()) => Ok(()),
1188        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1189        Err(error) => Err(error).with_context(|| format!("remove {}", path.display())),
1190    }
1191}
1192
1193fn finish_config_map_rename<T>(
1194    entries: &mut BTreeMap<String, T>,
1195    old_id: &str,
1196    new_id: &str,
1197    kind: &str,
1198) -> Result<()> {
1199    if let Some(entry) = entries.remove(old_id) {
1200        ensure!(
1201            !entries.contains_key(new_id),
1202            "cannot recover {kind} rename: both {old_id:?} and {new_id:?} exist"
1203        );
1204        entries.insert(new_id.to_owned(), entry);
1205    } else {
1206        ensure!(
1207            entries.contains_key(new_id),
1208            "cannot recover {kind} rename: neither {old_id:?} nor {new_id:?} exists"
1209        );
1210    }
1211    Ok(())
1212}
1213
1214/// Where this session's harness reads and writes its profile inside the target.
1215///
1216/// This is the per-session root [`removable_profile_root`] names, on every
1217/// target: a session always runs from a staged copy of its profile, never from
1218/// the profile home itself. Muse keeps its state in a `muse` subdirectory of
1219/// the root, because its ACP adapter owns the directory it is given.
1220#[cfg(test)]
1221pub(crate) fn target_profile_home_for_test(
1222    locator: &targets::TargetLocator,
1223    session_id: &str,
1224    profile: &mj_core::config::HarnessProfile,
1225) -> String {
1226    target_profile_home(locator, session_id, profile)
1227}
1228
1229fn target_profile_home(
1230    locator: &targets::TargetLocator,
1231    session_id: &str,
1232    profile: &mj_core::config::HarnessProfile,
1233) -> String {
1234    let root = removable_profile_root(locator, session_id, profile);
1235    if profile.kind == mj_core::config::HarnessKind::Muse {
1236        PathBuf::from(root)
1237            .join("muse")
1238            .to_string_lossy()
1239            .into_owned()
1240    } else {
1241        root
1242    }
1243}
1244
1245/// The per-session profile directory a session's harness home lives in, which
1246/// the session owns and an in-place harness replacement or teardown may delete.
1247///
1248/// This is the root that [`target_profile_home`] derives its answer from, not
1249/// that answer itself: a Muse session's home is a `muse` subdirectory of a
1250/// per-session root, and the whole root is what belongs to the session.
1251pub(super) fn removable_profile_root(
1252    locator: &targets::TargetLocator,
1253    session_id: &str,
1254    profile: &mj_core::config::HarnessProfile,
1255) -> String {
1256    match locator {
1257        targets::TargetLocator::LocalBare { .. }
1258            if profile.kind == mj_core::config::HarnessKind::Muse =>
1259        {
1260            targets::local_muse_profile_root(session_id)
1261                .to_string_lossy()
1262                .into_owned()
1263        }
1264        targets::TargetLocator::LocalBare { worker_root } => Path::new(worker_root)
1265            .join("profile")
1266            .to_string_lossy()
1267            .into_owned(),
1268        targets::TargetLocator::LocalPodman { .. }
1269        | targets::TargetLocator::LocalDocker { .. }
1270        | targets::TargetLocator::AppleContainer { .. }
1271        | targets::TargetLocator::SshPodman { .. }
1272        | targets::TargetLocator::SshDocker { .. } => {
1273            format!("/var/lib/hel/profiles/{session_id}")
1274        }
1275        targets::TargetLocator::AwsEc2 { .. } | targets::TargetLocator::SshBare { .. } => {
1276            format!(".local/share/hel/profiles/{session_id}")
1277        }
1278    }
1279}
1280
1281/// Resolve the login home on the machine that owns an editable path.
1282pub fn resolve_target_input_path(
1283    target: &TargetTemplate,
1284    path: &Path,
1285    executor: &impl CommandExecutor,
1286) -> Result<PathBuf> {
1287    if !mj_core::path_input::needs_home(path)? {
1288        return Ok(path.to_path_buf());
1289    }
1290    let host = cache_host::CacheHost::for_path_target(target)?;
1291    mj_core::path_input::expand_home(path, Some(&host.home(executor)?))
1292}
1293
1294/// Resolve the login home on a configured machine, for the Settings screen's
1295/// path fields. A machine, not a runtime, is what owns a home directory.
1296pub fn resolve_machine_input_path(
1297    machine: &mj_core::config::Machine,
1298    path: &Path,
1299    executor: &impl CommandExecutor,
1300) -> Result<PathBuf> {
1301    if !mj_core::path_input::needs_home(path)? {
1302        return Ok(path.to_path_buf());
1303    }
1304    // An EC2 instance does not exist until a session starts, so the only home
1305    // this screen can resolve is this machine's.
1306    let host = cache_host::CacheHost::for_path_machine(machine)?;
1307    mj_core::path_input::expand_home(path, Some(&host.home(executor)?))
1308}
1309
1310fn execute_checked(executor: &impl CommandExecutor, command: CommandSpec) -> Result<CommandOutput> {
1311    let output = executor.execute(&command)?;
1312    if output.status != 0 {
1313        let detail = command_error_detail(&output.stderr);
1314        if detail.is_empty() {
1315            bail!("{} failed with status {}", command.purpose, output.status);
1316        }
1317        bail!("{detail}");
1318    }
1319    Ok(output)
1320}
1321
1322fn command_error_detail(stderr: &[u8]) -> String {
1323    let reported = String::from_utf8_lossy(stderr);
1324    let reported = reported.trim();
1325    let detail = reported
1326        .rsplit_once("\nCaused by:\n")
1327        .map_or(reported, |(_, causes)| causes);
1328    let detail = detail.strip_prefix("Error: ").unwrap_or(detail);
1329    detail
1330        .lines()
1331        .map(|line| line.strip_prefix("    ").unwrap_or(line))
1332        .collect::<Vec<_>>()
1333        .join("\n")
1334        .trim()
1335        .to_owned()
1336}
1337
1338fn now() -> String {
1339    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
1340}
1341
1342fn restore_session_after_persistence_failure(
1343    state: &mut State,
1344    session_id: &str,
1345    previous: &SessionRecord,
1346    primary: anyhow::Error,
1347    persist: impl FnOnce(&SessionRecord) -> Result<()>,
1348) -> anyhow::Error {
1349    state
1350        .sessions
1351        .insert(session_id.to_owned(), previous.clone());
1352    let restored = state
1353        .sessions
1354        .get(session_id)
1355        .expect("restored session record disappeared");
1356    match persist(restored) {
1357        Ok(()) => primary,
1358        Err(error) => primary.context(format!(
1359            "restored prior session state in memory, but failed to persist the rollback: {error:#}"
1360        )),
1361    }
1362}
1363
1364fn persist_session_record_transition_or_restore(
1365    state: &mut State,
1366    session_id: &str,
1367    previous: &SessionRecord,
1368    context: &'static str,
1369    persist: &impl Fn(&SessionRecord) -> Result<()>,
1370) -> Result<()> {
1371    let result = persist(
1372        state
1373            .sessions
1374            .get(session_id)
1375            .expect("checkpoint session disappeared before persistence"),
1376    );
1377    match result {
1378        Ok(()) => Ok(()),
1379        Err(error) => Err(restore_session_after_persistence_failure(
1380            state,
1381            session_id,
1382            previous,
1383            error.context(context),
1384            persist,
1385        )),
1386    }
1387}
1388
1389pub fn config_only_controller(config: Config) -> Controller {
1390    Controller {
1391        config,
1392        state: State::default(),
1393    }
1394}
1395
1396#[cfg(test)]
1397mod tests;