Skip to main content

mj_controller/
controller.rs

1//! Controller-side lifecycle transitions and canonical-to-backend conversion.
2
3mod backend;
4mod checkpoint;
5mod git_cache;
6mod lifecycle;
7pub mod move_session;
8mod network_git;
9pub mod profile_config;
10mod provisioning;
11mod readiness;
12mod recovery_scan;
13mod resume;
14mod reviewer;
15mod subagents;
16#[cfg(test)]
17mod test_support;
18pub mod update;
19mod worker_binary;
20mod worker_restart;
21mod worktree;
22
23use std::collections::{BTreeMap, BTreeSet};
24use std::fs::{self, File, OpenOptions};
25use std::path::{Path, PathBuf};
26
27use anyhow::{Context, Result, bail, ensure};
28use chrono::Utc;
29
30use mj_core::config::{
31    Config, ProjectBundle, ProjectRepository, SshConnection, TargetTemplate, atomic_write,
32    container_size_host, data_dir, is_bare_project_target, mount_history_host,
33};
34
35use crate::import::{
36    RepositoryIdentity, bundle_matches, configured_bundle_for_local, configured_bundle_for_origin,
37    setup_style_id,
38};
39use crate::setup::github_repository_from_origin;
40
41const CONFIG_RENAME_JOURNAL: &str = "config-rename.json";
42
43#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
44#[serde(rename_all = "snake_case")]
45enum ConfigRenameKind {
46    Profile,
47    Target,
48}
49
50#[derive(Debug, serde::Serialize, serde::Deserialize)]
51#[serde(deny_unknown_fields)]
52struct ConfigRenameJournal {
53    kind: ConfigRenameKind,
54    old_id: String,
55    new_id: String,
56}
57use mj_core::state::{
58    HostContainerSize, SessionRecord, SessionResourceAllocation, SessionState, State,
59    new_session_id, normalize_session_title,
60};
61
62use crate::targets::{
63    self, AdditionalMount, CommandExecutor, CommandOutput, CommandSpec, SshTarget,
64};
65
66pub(crate) use backend::controller_github_token;
67pub use backend::image_refresh_plan;
68use backend::validate_resource_allocation;
69use provisioning::apply_failed_new_session_rollback;
70pub(crate) use worker_binary::refresh_remote_worker_binary_if_stale;
71pub(crate) use worktree::path_exists_on_managed_target;
72
73pub use checkpoint::{
74    CheckpointArtifact, CheckpointDeferred, IdleWorkspaceLease, SessionExportLayout,
75    checkpoint_was_deferred, reconcile_managed_checkpoint_archives,
76};
77pub use recovery_scan::{RecoveryCandidate, RecoveryScan};
78pub use resume::{
79    ResumeRepositorySourceMismatch, ResumeRepositorySourcePreflight, ResumeRepositorySourceReceipt,
80};
81pub use reviewer::reviewer_stager;
82pub use subagents::RegisterSubagentRequest;
83pub use worker_binary::{
84    WorkerBinaryAvailability, pin_worker_binary_sources, worker_binary_prerequisite_for_arch,
85};
86pub use worker_restart::WorkerUpgradeOutcome;
87pub use worktree::{ResumePlan, local_project_repository, resume_compatibility};
88
89pub struct Controller {
90    pub config: Config,
91    pub state: State,
92}
93
94/// Machine-wide advisory lock for one controller data store. This prevents a
95/// dashboard, server, or CLI lifecycle command from concurrently acting as a
96/// second controller against the same SQLite state and relay sessions.
97#[derive(Debug)]
98pub struct ControllerStoreGuard {
99    file: File,
100}
101
102impl ControllerStoreGuard {
103    pub fn acquire() -> Result<Self> {
104        let directory = data_dir();
105        Self::acquire_at(&directory)
106    }
107
108    fn acquire_at(directory: &Path) -> Result<Self> {
109        Self::try_acquire_at(directory)?.with_context(|| {
110            format!(
111                "another Mjolnir controller is already using {}; stop it before starting this command",
112                directory.display()
113            )
114        })
115    }
116
117    /// Probe exclusivity without treating an owner that is still exiting as an error.
118    pub fn try_acquire() -> Result<Option<Self>> {
119        Self::try_acquire_at(&data_dir())
120    }
121
122    fn try_acquire_at(directory: &Path) -> Result<Option<Self>> {
123        std::fs::create_dir_all(directory)
124            .with_context(|| format!("create controller data directory {}", directory.display()))?;
125        let path = directory.join("controller.lock");
126        let mut options = OpenOptions::new();
127        options.create(true).read(true).write(true);
128        #[cfg(unix)]
129        {
130            use std::os::unix::fs::OpenOptionsExt;
131            options.mode(0o600);
132        }
133        let file = options
134            .open(&path)
135            .with_context(|| format!("open controller lock {}", path.display()))?;
136        match file.try_lock() {
137            Ok(()) => {}
138            Err(std::fs::TryLockError::WouldBlock) => return Ok(None),
139            Err(std::fs::TryLockError::Error(error)) => {
140                return Err(error)
141                    .with_context(|| format!("lock controller store {}", directory.display()));
142            }
143        }
144        Ok(Some(Self { file }))
145    }
146
147    /// Start the sole production SQLite writer after controller exclusivity
148    /// has been established by this guard.
149    pub fn start_database_writer(&self) -> Result<crate::database::DatabaseWriterOwner> {
150        crate::database::start_database_writer()
151    }
152}
153
154impl Drop for ControllerStoreGuard {
155    fn drop(&mut self) {
156        // Make release explicit. `File` also unlocks on close, but an explicit
157        // unlock keeps same-process handoff deterministic across platforms.
158        let _ = self.file.unlock();
159    }
160}
161
162/// The durable result of creating a quick bundle. The returned config is the
163/// same fresh config that was written, allowing a serving projection to publish
164/// the new bundle before acknowledging the request that created it.
165#[derive(Debug)]
166pub struct QuickBundleCreation {
167    pub config: Config,
168    pub bundle_id: String,
169}
170
171/// Failure stages exposed to a viewer request without exposing the underlying
172/// filesystem/configuration error. The detailed error remains available to
173/// the caller for logs and terminal notices.
174#[derive(Debug)]
175pub enum QuickBundleFailure {
176    InvalidSource(anyhow::Error),
177    Persistence(anyhow::Error),
178}
179
180impl std::fmt::Display for QuickBundleFailure {
181    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182        match self {
183            Self::InvalidSource(error) => write!(formatter, "invalid repository source: {error}"),
184            Self::Persistence(error) => write!(formatter, "persist quick bundle: {error}"),
185        }
186    }
187}
188
189impl std::error::Error for QuickBundleFailure {
190    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
191        match self {
192            Self::InvalidSource(error) | Self::Persistence(error) => Some(error.root_cause()),
193        }
194    }
195}
196
197/// Create a quick bundle from a local repository or GitHub source and persist
198/// it as one serialized fresh-config transaction. Identical sources reuse the
199/// existing configured bundle, matching the terminal's behavior. The returned
200/// config is the same fresh config that was written, allowing a serving
201/// projection to publish the new bundle before acknowledging the request.
202pub fn create_quick_bundle(
203    source: &str,
204) -> std::result::Result<QuickBundleCreation, QuickBundleFailure> {
205    let (config, bundle_id) = Config::update(|config| {
206        create_quick_bundle_in_config(config, source)
207            .map_err(|error| anyhow::Error::new(QuickBundleFailure::InvalidSource(error)))
208    })
209    .map_err(|error| {
210        error
211            .downcast::<QuickBundleFailure>()
212            .unwrap_or_else(QuickBundleFailure::Persistence)
213    })?;
214    Ok(QuickBundleCreation { config, bundle_id })
215}
216
217/// Add a quick bundle to an already-loaded config. The helper still performs
218/// the local repository canonicalization/GitHub-source parsing, but callers
219/// that persist a config should use [`create_quick_bundle`] so concurrent saves
220/// cannot clobber one another.
221pub fn create_quick_bundle_in_config(config: &mut Config, source: &str) -> Result<String> {
222    let source = interpret_repository_source(source)?;
223    let existing = match &source.kind {
224        RepositorySourceKind::Local(root) => configured_bundle_for_local(config, root),
225        RepositorySourceKind::Github(repository) => {
226            configured_bundle_for_origin(config, repository)
227        }
228    };
229    if let Some(existing) = existing {
230        return Ok(existing);
231    }
232    let repository_id = setup_style_id(&source.name);
233    let mut bundle_id = repository_id.clone();
234    for suffix in 2_u32.. {
235        if !config.bundles.contains_key(&bundle_id) {
236            break;
237        }
238        bundle_id = format!("{repository_id}-{suffix}");
239    }
240    config.bundles.insert(
241        bundle_id.clone(),
242        ProjectBundle {
243            primary_repo: repository_id.clone(),
244            repositories: vec![source.into_project_repository(repository_id.clone())],
245        },
246    );
247    config.validate()?;
248    Ok(bundle_id)
249}
250
251/// Create one bundle from one or more local repositories or GitHub sources.
252///
253/// All sources are interpreted and checked before the config transaction can
254/// write anything. An existing bundle is reused only when its repository set
255/// and primary repository exactly match the request; this keeps selecting one
256/// repository from a larger bundle from silently changing the wizard's choice.
257pub fn create_bundle_from_sources(
258    sources: &[String],
259) -> std::result::Result<QuickBundleCreation, QuickBundleFailure> {
260    let (config, bundle_id) = Config::update(|config| {
261        create_bundle_from_sources_in_config(config, sources)
262            .map_err(|error| anyhow::Error::new(QuickBundleFailure::InvalidSource(error)))
263    })
264    .map_err(|error| {
265        error
266            .downcast::<QuickBundleFailure>()
267            .unwrap_or_else(QuickBundleFailure::Persistence)
268    })?;
269    Ok(QuickBundleCreation { config, bundle_id })
270}
271
272/// Add a bundle for all `sources` to an already-loaded config. The source
273/// interpretation is shared with the persisted [`create_bundle_from_sources`]
274/// entry point and the legacy quick-bundle helper.
275pub fn create_bundle_from_sources_in_config(
276    config: &mut Config,
277    sources: &[String],
278) -> Result<String> {
279    let sources = sources
280        .iter()
281        .map(|source| interpret_repository_source(source))
282        .collect::<Result<Vec<_>>>()?;
283    if sources.is_empty() {
284        bail!("at least one repository source is required");
285    }
286
287    let mut identities = BTreeSet::new();
288    for source in &sources {
289        if !identities.insert(source.identity()) {
290            bail!("duplicate repository source {:?}", source.display_name);
291        }
292    }
293
294    if let Some(existing) = exact_configured_bundle(config, &sources) {
295        return Ok(existing);
296    }
297
298    // Build and validate a candidate before replacing the caller's config, so
299    // a later validation error cannot leave an in-memory partial mutation.
300    let mut updated = config.clone();
301    let mut used_repository_ids = BTreeSet::new();
302    let mut repositories = Vec::with_capacity(sources.len());
303    for source in sources {
304        let base = setup_style_id(&source.name);
305        let repository_id = unique_id(&base, |candidate| used_repository_ids.contains(candidate));
306        used_repository_ids.insert(repository_id.clone());
307        repositories.push(source.into_project_repository(repository_id));
308    }
309    let primary_repo = repositories
310        .first()
311        .map(|repository| repository.id.clone())
312        .context("at least one repository source is required")?;
313    let bundle_id = unique_id(&primary_repo, |candidate| {
314        updated.bundles.contains_key(candidate)
315    });
316    updated.bundles.insert(
317        bundle_id.clone(),
318        ProjectBundle {
319            primary_repo,
320            repositories,
321        },
322    );
323    updated.validate()?;
324    *config = updated;
325    Ok(bundle_id)
326}
327
328#[derive(Debug, Clone)]
329enum RepositorySourceKind {
330    Github(crate::setup::GithubRepository),
331    Local(PathBuf),
332}
333
334#[derive(Debug, Clone)]
335struct InterpretedRepositorySource {
336    display_name: String,
337    name: String,
338    kind: RepositorySourceKind,
339}
340
341impl InterpretedRepositorySource {
342    fn identity(&self) -> RepositoryIdentity {
343        match &self.kind {
344            RepositorySourceKind::Github(repository) => RepositoryIdentity::Github(
345                repository.owner.to_ascii_lowercase(),
346                repository.repository.to_ascii_lowercase(),
347            ),
348            RepositorySourceKind::Local(root) => RepositoryIdentity::Local(root.clone()),
349        }
350    }
351
352    fn into_project_repository(self, id: String) -> ProjectRepository {
353        let (github, local) = match self.kind {
354            RepositorySourceKind::Github(repository) => (
355                Some(format!("{}/{}", repository.owner, repository.repository)),
356                None,
357            ),
358            RepositorySourceKind::Local(root) => (None, Some(root)),
359        };
360        ProjectRepository {
361            id: id.clone(),
362            github,
363            local,
364            destination: PathBuf::from(id),
365            git_ref: None,
366        }
367    }
368}
369
370/// Interpret a source once, including local Git canonicalization and GitHub
371/// parsing, so all creation paths use exactly the same source semantics.
372fn interpret_repository_source(source: &str) -> Result<InterpretedRepositorySource> {
373    let source = source.trim();
374    if source.is_empty() {
375        bail!("repository source cannot be empty");
376    }
377    let expanded = mj_core::path_input::expand_local(Path::new(source))?;
378    let candidate = expanded.as_path();
379    if candidate.exists() {
380        let root = mj_core::local_git::canonical_repository(candidate)?;
381        let name = root
382            .file_name()
383            .and_then(|name| name.to_str())
384            .context("local repository has no usable directory name")?
385            .to_owned();
386        return Ok(InterpretedRepositorySource {
387            display_name: source.to_owned(),
388            name,
389            kind: RepositorySourceKind::Local(root),
390        });
391    }
392    if candidate.is_absolute() || source.starts_with('.') || source.starts_with('~') {
393        bail!("local repository path {source:?} does not exist");
394    }
395    let repository = github_repository_from_origin(source).context(format!(
396        "{source:?} is not a GitHub owner/repository or URL"
397    ))?;
398    Ok(InterpretedRepositorySource {
399        display_name: source.to_owned(),
400        name: repository.repository.clone(),
401        kind: RepositorySourceKind::Github(repository),
402    })
403}
404
405fn exact_configured_bundle(
406    config: &Config,
407    requested: &[InterpretedRepositorySource],
408) -> Option<String> {
409    let requested_identities = requested
410        .iter()
411        .map(InterpretedRepositorySource::identity)
412        .collect::<BTreeSet<_>>();
413    let primary = requested.first()?.identity();
414    config.bundles.iter().find_map(|(id, bundle)| {
415        if bundle.repositories.len() != requested.len()
416            || bundle
417                .repositories
418                .iter()
419                .any(|repository| repository.git_ref.is_some())
420        {
421            return None;
422        }
423        bundle_matches(bundle, &requested_identities, &primary).then(|| id.clone())
424    })
425}
426
427fn unique_id(base: &str, mut is_used: impl FnMut(&str) -> bool) -> String {
428    if !is_used(base) {
429        return base.to_owned();
430    }
431    for suffix in 2_u32.. {
432        let suffix = format!("-{suffix}");
433        let prefix_len = 64usize.saturating_sub(suffix.len());
434        let prefix = base.chars().take(prefix_len).collect::<String>();
435        let candidate = format!("{prefix}{suffix}");
436        if !is_used(&candidate) {
437            return candidate;
438        }
439    }
440    unreachable!("u32 repository/bundle id suffixes exhausted")
441}
442
443pub struct SessionLaunchOptions {
444    pub create_managed_worktree: Option<bool>,
445    pub initial_prompt: Option<String>,
446    pub workspace_id: String,
447    pub additional_mounts: Vec<AdditionalMount>,
448    pub allow_dirty_local: bool,
449    pub resource_allocation: Option<SessionResourceAllocation>,
450    pub project_directory: Option<PathBuf>,
451    pub session_title_override: Option<String>,
452}
453
454pub struct SessionResumeOptions {
455    pub additional_mounts: Option<Vec<AdditionalMount>>,
456    pub resource_allocation: Option<SessionResourceAllocation>,
457    pub discard_queue: bool,
458}
459
460fn selected_host_container_size(
461    template: &TargetTemplate,
462    allocation: Option<&SessionResourceAllocation>,
463) -> Option<(String, HostContainerSize)> {
464    let host = container_size_host(template)?;
465    let SessionResourceAllocation::Container { cpus, memory_bytes } = allocation? else {
466        return None;
467    };
468    Some((
469        host.to_owned(),
470        HostContainerSize {
471            cpus: *cpus,
472            memory_bytes: *memory_bytes,
473        },
474    ))
475}
476
477impl Controller {
478    pub fn load() -> Result<Self> {
479        let config = Config::load()?;
480        let state = crate::database::load_state_migrating()?;
481        // Missing session dependencies must not lock users out of the tools
482        // needed to repair them. Operations validate the session they act on.
483        state.validate()?;
484        for session in state.sessions.values() {
485            if let Some(issue) = session.configuration_issue(&config) {
486                tracing::warn!(session_id = %session.id, "{issue}");
487            }
488        }
489        Ok(Self { config, state })
490    }
491
492    pub fn reload(&mut self) -> Result<()> {
493        *self = Self::load()?;
494        Ok(())
495    }
496
497    fn persist_session_state(&self, session_id: &str) -> Result<()> {
498        match self.state.sessions.get(session_id) {
499            Some(session) => crate::database::save_lifecycle_session(session),
500            None => crate::database::delete_session(session_id),
501        }
502    }
503
504    fn persist_session_transition_or_restore(
505        &mut self,
506        session_id: &str,
507        previous: &SessionRecord,
508        context: &'static str,
509    ) -> Result<()> {
510        persist_session_record_transition_or_restore(
511            &mut self.state,
512            session_id,
513            previous,
514            context,
515            &crate::database::save_lifecycle_session,
516        )
517    }
518
519    fn restore_prior_session_after_persistence_failure(
520        &mut self,
521        session_id: &str,
522        previous: &SessionRecord,
523        primary: anyhow::Error,
524    ) -> anyhow::Error {
525        restore_session_after_persistence_failure(
526            &mut self.state,
527            session_id,
528            previous,
529            primary,
530            crate::database::save_lifecycle_session,
531        )
532    }
533
534    /// Resolve an entered path on its owning host. Call only from background work.
535    pub fn resolve_input_path(
536        &self,
537        target_id: &str,
538        path: &Path,
539        executor: &impl CommandExecutor,
540    ) -> Result<PathBuf> {
541        let target = self
542            .config
543            .targets
544            .get(target_id)
545            .context("Unknown path target")?;
546        resolve_target_input_path(target, path, executor)
547    }
548
549    /// Complete a mount source on the container engine host, preserving ~/ while editing.
550    pub fn complete_mount_source(
551        &self,
552        target_id: &str,
553        prefix: &str,
554        executor: &impl CommandExecutor,
555    ) -> Result<Vec<String>> {
556        let target = self
557            .config
558            .targets
559            .get(target_id)
560            .with_context(|| format!("unknown target template {target_id:?}"))?;
561        let home = if mj_core::path_input::needs_home(Path::new(prefix))? {
562            Some(resolve_target_input_path(target, Path::new("~"), executor)?)
563        } else {
564            None
565        };
566        let expanded = mj_core::path_input::expand_home(Path::new(prefix), home.as_deref())?;
567        let mut lookup = expanded.to_string_lossy().into_owned();
568        // Completion is a text protocol: a trailing separator requests children.
569        if prefix.ends_with('/') && !lookup.ends_with('/') {
570            lookup.push('/');
571        }
572        let candidates = match target {
573            TargetTemplate::LocalPodman { .. }
574            | TargetTemplate::LocalDocker { .. }
575            | TargetTemplate::AppleContainer { .. }
576            | TargetTemplate::AwsEc2 { .. } => targets::local_directory_completions(&lookup),
577            TargetTemplate::SshPodman { ssh, .. } | TargetTemplate::SshDocker { ssh, .. } => {
578                targets::ssh_directory_completions(&backend_ssh(ssh), &lookup, executor)?
579            }
580            TargetTemplate::LocalBare | TargetTemplate::SshBare { .. } => {
581                bail!("resource path completion is unsupported for bare targets")
582            }
583        };
584        candidates
585            .into_iter()
586            .map(|candidate| {
587                let Some(home) = &home else {
588                    return Ok(candidate);
589                };
590                let suffix = Path::new(&candidate)
591                    .strip_prefix(home)
592                    .context("Completed path is outside the requested home")?;
593                let mut value = Path::new("~").join(suffix).to_string_lossy().into_owned();
594                if candidate.ends_with('/') && !value.ends_with('/') {
595                    value.push('/');
596                }
597                Ok(value)
598            })
599            .collect()
600    }
601
602    /// Verify a mount source on the host where Mjolnir will consume it, and report
603    /// the filesystem reason it must be attached read-only, if there is one.
604    ///
605    /// The probe runs in the same round trip as the existence check so the
606    /// editor learns both answers without a second wait. A probe that cannot
607    /// answer reports no reason: provisioning decides that authoritatively.
608    pub fn validate_mount_source(
609        &self,
610        target_id: &str,
611        source: &Path,
612        executor: &impl CommandExecutor,
613    ) -> Result<Option<String>> {
614        let target = self
615            .config
616            .targets
617            .get(target_id)
618            .with_context(|| format!("unknown target template {target_id:?}"))?;
619        let exists = match target {
620            TargetTemplate::LocalPodman { .. }
621            | TargetTemplate::LocalDocker { .. }
622            | TargetTemplate::AppleContainer { .. }
623            | TargetTemplate::AwsEc2 { .. } => std::fs::metadata(source)
624                .map(|metadata| metadata.is_dir())
625                .or_else(|error| {
626                    if error.kind() == std::io::ErrorKind::NotFound {
627                        Ok(false)
628                    } else {
629                        Err(error)
630                    }
631                })
632                .with_context(|| format!("inspect resource source {}", source.display()))?,
633            TargetTemplate::SshPodman { ssh, .. } | TargetTemplate::SshDocker { ssh, .. } => {
634                targets::ssh_directory_exists(&backend_ssh(ssh), source, executor)?
635            }
636            TargetTemplate::LocalBare | TargetTemplate::SshBare { .. } => {
637                bail!("resource attachments are unsupported for bare targets")
638            }
639        };
640        ensure!(
641            exists,
642            "source path {} does not exist or is not a directory",
643            source.display()
644        );
645        Ok(self.forced_read_only_reason(target, source, executor))
646    }
647
648    /// The `filesystem (reason)` label for a source the runtime cannot overlay.
649    fn forced_read_only_reason(
650        &self,
651        target: &TargetTemplate,
652        source: &Path,
653        executor: &impl CommandExecutor,
654    ) -> Option<String> {
655        let ssh = match target {
656            TargetTemplate::LocalPodman { .. } | TargetTemplate::LocalDocker { .. } => None,
657            TargetTemplate::SshPodman { ssh, .. } | TargetTemplate::SshDocker { ssh, .. } => {
658                Some(backend_ssh(ssh))
659            }
660            // Apple Container already mounts read-only, and EC2 copies instead
661            // of mounting, so neither has an overlay to lose.
662            _ => return None,
663        };
664        let filesystem = targets::probe_filesystem_types(
665            ssh.as_ref(),
666            std::slice::from_ref(&source.to_path_buf()),
667            executor,
668        )
669        .map_err(|error| {
670            tracing::debug!(
671                source = %source.display(),
672                error = format!("{error:#}"),
673                "could not probe the filesystem under a mount source"
674            );
675        })
676        .ok()?
677        .pop()?;
678        let reason = targets::overlay_unsupported_filesystem(&filesystem)?;
679        Some(format!("{filesystem} ({reason})"))
680    }
681
682    fn fail_new_session_with_cleanup(
683        &mut self,
684        session_id: &str,
685        error: anyhow::Error,
686        executor: &impl CommandExecutor,
687    ) -> Result<anyhow::Error> {
688        let original = format!("{error:#}");
689        let cleanup_error = self
690            .cleanup_new_session_worktree_after_failure(session_id, executor)
691            .err()
692            .map(|cleanup_error| format!("{cleanup_error:#}"));
693        if let Some(cleanup_error) = &cleanup_error {
694            tracing::warn!(
695                session_id,
696                error = %cleanup_error,
697                "new-session worktree rollback reported a cleanup failure"
698            );
699        }
700        let failure = apply_failed_new_session_rollback(
701            &mut self.state,
702            session_id,
703            &original,
704            cleanup_error,
705        );
706        self.persist_session_state(session_id)?;
707        Ok(failure)
708    }
709
710    pub fn register_session_with_resources(
711        &mut self,
712        profile_id: &str,
713        bundle_id: &str,
714        target_id: &str,
715        title: impl Into<String>,
716        options: SessionLaunchOptions,
717    ) -> Result<String> {
718        let SessionLaunchOptions {
719            create_managed_worktree,
720            initial_prompt,
721            workspace_id,
722            additional_mounts,
723            allow_dirty_local: _,
724            resource_allocation,
725            project_directory,
726            session_title_override,
727        } = options;
728        let session_title_override = match session_title_override {
729            Some(title) => {
730                Some(normalize_session_title(&title).context("session name cannot be empty")?)
731            }
732            None => None,
733        };
734        let profile = self
735            .config
736            .profiles
737            .get(profile_id)
738            .with_context(|| format!("unknown profile {profile_id:?}"))?;
739        ensure!(profile.enabled, "profile {profile_id:?} is disabled");
740        let template = self
741            .config
742            .targets
743            .get(target_id)
744            .with_context(|| format!("unknown target template {target_id:?}"))?;
745        if create_managed_worktree == Some(true) && !is_bare_project_target(template) {
746            bail!("managed worktree creation requires a bare Git project");
747        }
748        if project_directory.is_some() != is_bare_project_target(template) {
749            bail!("raw project directories require a bare target, and bare targets require one");
750        }
751        if let Some(path) = &project_directory
752            && (!path.is_absolute()
753                || path
754                    .components()
755                    .any(|part| part == std::path::Component::ParentDir))
756        {
757            bail!("bare project directory must be an absolute safe path");
758        }
759        let bundle = project_directory
760            .is_none()
761            .then(|| self.config.bundles.get(bundle_id))
762            .flatten();
763        if project_directory.is_none() && bundle.is_none() {
764            bail!("unknown bundle {bundle_id:?}");
765        }
766        if matches!(
767            profile.kind,
768            mj_core::config::HarnessKind::Deepseek | mj_core::config::HarnessKind::Muse
769        ) && (!additional_mounts.is_empty()
770            || bundle.is_some_and(|bundle| bundle.repositories.len() > 1))
771        {
772            bail!(
773                "{} ACP supports one workspace root; use a single-repository bundle without attached directories",
774                profile.kind.display_name()
775            );
776        }
777        if let Some(bundle) = bundle {
778            for repository in &bundle.repositories {
779                mj_core::remote_git::resolve_repository(
780                    repository,
781                    &targets::CancellableProcessExecutor::with_timeout(
782                        std::time::Duration::from_secs(15),
783                    ),
784                )
785                .with_context(|| format!("repository {:?}", repository.id))?;
786            }
787        }
788        validate_resource_allocation(template, resource_allocation.as_ref())?;
789        let selected_container_size =
790            selected_host_container_size(template, resource_allocation.as_ref());
791        if !additional_mounts.is_empty() && mount_history_host(template).is_none() {
792            bail!("attached resources are unsupported for this target");
793        }
794        targets::validate_additional_mounts(&additional_mounts)?;
795        let id = new_session_id()?;
796        let now = now();
797        let record = SessionRecord {
798            create_managed_worktree,
799            archived: false,
800            container_cpus: None,
801            container_memory: None,
802            id: id.clone(),
803            workspace_id,
804            title: title.into(),
805            harness_kind: profile.kind,
806            last_profile: profile_id.to_string(),
807            bundle_id: bundle_id.to_string(),
808            project_directory,
809            managed_worktree: None,
810            target_template_id: target_id.to_string(),
811            resource_allocation,
812            additional_mounts: additional_mounts.clone(),
813            state: SessionState::Provisioning,
814            target: None,
815            native_session_id: None,
816            acp_session_title: None,
817            session_title_override,
818            created_at: now.clone(),
819            updated_at: now,
820            viewed_through_event_ordinal: 0,
821            draft_input: initial_prompt.unwrap_or_default(),
822            last_error: None,
823            last_checkpoint_error: None,
824            checkpoint: None,
825        };
826        // Creation authors the whole record, so it writes the whole row. The
827        // record reaches memory only once it is durable: a session this process
828        // alone knows about is one the database can never resume or clean up.
829        if let Some((host, size)) = selected_container_size.as_ref() {
830            crate::database::save_session_with_container_size(&record, host, *size)?;
831        } else {
832            crate::database::save_session(&record)?;
833        }
834        self.state.sessions.insert(id.clone(), record);
835        if let Some((host, size)) = selected_container_size {
836            self.state.remember_container_size(&host, size);
837        }
838        if let Some(host) = mount_history_host(template) {
839            // Mount history only seeds the attach dialog's suggestions. The
840            // session row is already committed, so a failed suggestion write is
841            // reported rather than turned into a failed registration.
842            match crate::database::remember_mount_sources(host, &additional_mounts) {
843                Ok(()) => self.state.remember_mount_sources(host, &additional_mounts),
844                Err(error) => tracing::warn!(
845                    session_id = id,
846                    error = format!("{error:#}"),
847                    "could not remember the attached resource directories for later suggestions"
848                ),
849            }
850        }
851        Ok(id)
852    }
853
854    pub fn rename_session(&mut self, session_id: &str, title: &str) -> Result<String> {
855        let title = normalize_session_title(title).context("session name cannot be empty")?;
856        ensure!(
857            self.state.sessions.contains_key(session_id),
858            "unknown session {session_id}"
859        );
860        let updated_at = now();
861        crate::database::set_session_title_override(session_id, &title, &updated_at)?;
862        let record = self
863            .state
864            .sessions
865            .get_mut(session_id)
866            .expect("session was checked before updating its title");
867        record.session_title_override = Some(title.clone());
868        record.updated_at = updated_at;
869        Ok(title)
870    }
871
872    pub fn rename_profile_id(&mut self, old_id: &str, new_id: &str) -> Result<()> {
873        mj_core::config::validate_id("profile", new_id)?;
874        if old_id == new_id {
875            ensure!(
876                self.config.profiles.contains_key(old_id),
877                "unknown profile {old_id:?}"
878            );
879            return Ok(());
880        }
881        let journal = ConfigRenameJournal {
882            kind: ConfigRenameKind::Profile,
883            old_id: old_id.to_owned(),
884            new_id: new_id.to_owned(),
885        };
886        write_config_rename_journal(&journal)?;
887        let (config, ()) = match Config::update(|config| {
888            ensure!(
889                config.profiles.contains_key(old_id),
890                "unknown profile {old_id:?}"
891            );
892            ensure!(
893                !config.profiles.contains_key(new_id),
894                "profile {new_id:?} already exists"
895            );
896            let profile = config
897                .profiles
898                .remove(old_id)
899                .expect("profile was checked in the transaction");
900            config.profiles.insert(new_id.to_owned(), profile);
901            Ok(())
902        }) {
903            Ok(result) => result,
904            Err(error) => {
905                remove_config_rename_journal()
906                    .context("remove profile rename journal after config save failed")?;
907                return Err(error).context("save renamed profile configuration");
908            }
909        };
910        self.config = config;
911        mj_core::test_hooks::reach_test_hook("config_replacement_before_reference_migration")?;
912        if let Err(error) = crate::database::rename_profile_references(old_id, new_id) {
913            let restore = Config::update(|config| {
914                let profile = config
915                    .profiles
916                    .remove(new_id)
917                    .with_context(|| format!("renamed profile {new_id:?} is missing"))?;
918                ensure!(
919                    !config.profiles.contains_key(old_id),
920                    "cannot restore profile rename: both {old_id:?} and {new_id:?} exist"
921                );
922                config.profiles.insert(old_id.to_owned(), profile);
923                Ok(())
924            });
925            let restored = match restore {
926                Ok((config, ())) => config,
927                Err(restore_error) => {
928                    return Err(error).context(format!(
929                        "rename profile references; additionally failed to restore config: {restore_error:#}"
930                    ));
931                }
932            };
933            self.config = restored;
934            if let Err(restore_error) = remove_config_rename_journal() {
935                return Err(error).context(format!(
936                    "rename profile references; additionally failed to remove rename journal: {restore_error:#}"
937                ));
938            }
939            return Err(error).context("rename profile references");
940        }
941        for session in self.state.sessions.values_mut() {
942            if session.last_profile == old_id {
943                session.last_profile = new_id.to_owned();
944            }
945        }
946        remove_config_rename_journal()?;
947        Ok(())
948    }
949
950    pub fn rename_target_id(&mut self, old_id: &str, new_id: &str) -> Result<()> {
951        mj_core::config::validate_id("target template", new_id)?;
952        if old_id == new_id {
953            ensure!(
954                self.config.targets.contains_key(old_id),
955                "unknown target {old_id:?}"
956            );
957            return Ok(());
958        }
959        let journal = ConfigRenameJournal {
960            kind: ConfigRenameKind::Target,
961            old_id: old_id.to_owned(),
962            new_id: new_id.to_owned(),
963        };
964        write_config_rename_journal(&journal)?;
965        let (config, ()) = match Config::update(|config| {
966            ensure!(
967                config.targets.contains_key(old_id),
968                "unknown target {old_id:?}"
969            );
970            ensure!(
971                !config.targets.contains_key(new_id),
972                "target {new_id:?} already exists"
973            );
974            let target = config
975                .targets
976                .remove(old_id)
977                .expect("target was checked in the transaction");
978            config.targets.insert(new_id.to_owned(), target);
979            Ok(())
980        }) {
981            Ok(result) => result,
982            Err(error) => {
983                remove_config_rename_journal()
984                    .context("remove target rename journal after config save failed")?;
985                return Err(error).context("save renamed target configuration");
986            }
987        };
988        self.config = config;
989        mj_core::test_hooks::reach_test_hook("config_replacement_before_reference_migration")?;
990        if let Err(error) = crate::database::rename_target_references(old_id, new_id) {
991            let restore = Config::update(|config| {
992                let target = config
993                    .targets
994                    .remove(new_id)
995                    .with_context(|| format!("renamed target {new_id:?} is missing"))?;
996                ensure!(
997                    !config.targets.contains_key(old_id),
998                    "cannot restore target rename: both {old_id:?} and {new_id:?} exist"
999                );
1000                config.targets.insert(old_id.to_owned(), target);
1001                Ok(())
1002            });
1003            let restored = match restore {
1004                Ok((config, ())) => config,
1005                Err(restore_error) => {
1006                    return Err(error).context(format!(
1007                        "rename target references; additionally failed to restore config: {restore_error:#}"
1008                    ));
1009                }
1010            };
1011            self.config = restored;
1012            if let Err(restore_error) = remove_config_rename_journal() {
1013                return Err(error).context(format!(
1014                    "rename target references; additionally failed to remove rename journal: {restore_error:#}"
1015                ));
1016            }
1017            return Err(error).context("rename target references");
1018        }
1019        for session in self.state.sessions.values_mut() {
1020            if session.target_template_id == old_id {
1021                session.target_template_id = new_id.to_owned();
1022            }
1023        }
1024        remove_config_rename_journal()?;
1025        Ok(())
1026    }
1027
1028    /// Finish a profile/target id rename interrupted between the atomic config
1029    /// replacement and SQLite transaction. Each step is idempotent, so a
1030    /// second crash leaves the same intent available for the next startup.
1031    pub fn recover_config_id_rename() -> Result<bool> {
1032        let path = config_rename_journal_path();
1033        let body = match fs::read(&path) {
1034            Ok(body) => body,
1035            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(false),
1036            Err(error) => return Err(error).context(format!("read {}", path.display())),
1037        };
1038        let journal: ConfigRenameJournal =
1039            serde_json::from_slice(&body).with_context(|| format!("parse {}", path.display()))?;
1040        match journal.kind {
1041            ConfigRenameKind::Profile => {
1042                Config::update(|config| {
1043                    finish_config_map_rename(
1044                        &mut config.profiles,
1045                        &journal.old_id,
1046                        &journal.new_id,
1047                        "profile",
1048                    )?;
1049                    Ok(())
1050                })?;
1051                crate::database::rename_profile_references(&journal.old_id, &journal.new_id)?;
1052            }
1053            ConfigRenameKind::Target => {
1054                Config::update(|config| {
1055                    finish_config_map_rename(
1056                        &mut config.targets,
1057                        &journal.old_id,
1058                        &journal.new_id,
1059                        "target",
1060                    )?;
1061                    Ok(())
1062                })?;
1063                crate::database::rename_target_references(&journal.old_id, &journal.new_id)?;
1064            }
1065        }
1066        remove_config_rename_journal()?;
1067        Ok(true)
1068    }
1069
1070    /// Record the per-session container size overrides and attached
1071    /// directories. Nothing is applied to a running container: the values are
1072    /// read the next time the session's container is created.
1073    pub fn update_session_container_settings(
1074        &mut self,
1075        session_id: &str,
1076        cpus: Option<String>,
1077        memory: Option<String>,
1078        additional_mounts: Vec<targets::AdditionalMount>,
1079        mount_history: Vec<std::path::PathBuf>,
1080    ) -> Result<()> {
1081        ensure!(
1082            self.state.sessions.contains_key(session_id),
1083            "unknown session {session_id}"
1084        );
1085        let cpus = cpus.filter(|value| !value.trim().is_empty());
1086        let memory = memory.filter(|value| !value.trim().is_empty());
1087        let updated_at = now();
1088        crate::database::set_session_container_settings(
1089            session_id,
1090            cpus.as_deref(),
1091            memory.as_deref(),
1092            &additional_mounts,
1093            &updated_at,
1094        )?;
1095        if let Some(host) = self
1096            .config
1097            .targets
1098            .get(
1099                &self.state.sessions[session_id]
1100                    .target_template_id
1101                    .to_owned(),
1102            )
1103            .and_then(mj_core::config::mount_history_host)
1104        {
1105            let host = host.to_owned();
1106            // The dialog owns the suggestion list, so forgetting a directory
1107            // there has to survive the mounts being remembered right after.
1108            crate::database::replace_mount_history(&host, &mount_history)?;
1109            crate::database::remember_mount_sources(&host, &additional_mounts)?;
1110            self.state.mount_history.insert(host.clone(), mount_history);
1111            self.state.remember_mount_sources(&host, &additional_mounts);
1112        }
1113        let record = self
1114            .state
1115            .sessions
1116            .get_mut(session_id)
1117            .expect("session was checked before updating its container settings");
1118        record.container_cpus = cpus;
1119        record.container_memory = memory;
1120        record.additional_mounts = additional_mounts;
1121        record.updated_at = updated_at;
1122        Ok(())
1123    }
1124}
1125
1126fn config_rename_journal_path() -> PathBuf {
1127    data_dir().join(CONFIG_RENAME_JOURNAL)
1128}
1129
1130fn write_config_rename_journal(journal: &ConfigRenameJournal) -> Result<()> {
1131    let path = config_rename_journal_path();
1132    let body = serde_json::to_vec(journal).context("serialize config rename journal")?;
1133    atomic_write(&path, &body).with_context(|| format!("write {}", path.display()))
1134}
1135
1136fn remove_config_rename_journal() -> Result<()> {
1137    let path = config_rename_journal_path();
1138    match fs::remove_file(&path) {
1139        Ok(()) => Ok(()),
1140        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
1141        Err(error) => Err(error).with_context(|| format!("remove {}", path.display())),
1142    }
1143}
1144
1145fn finish_config_map_rename<T>(
1146    entries: &mut BTreeMap<String, T>,
1147    old_id: &str,
1148    new_id: &str,
1149    kind: &str,
1150) -> Result<()> {
1151    if let Some(entry) = entries.remove(old_id) {
1152        ensure!(
1153            !entries.contains_key(new_id),
1154            "cannot recover {kind} rename: both {old_id:?} and {new_id:?} exist"
1155        );
1156        entries.insert(new_id.to_owned(), entry);
1157    } else {
1158        ensure!(
1159            entries.contains_key(new_id),
1160            "cannot recover {kind} rename: neither {old_id:?} nor {new_id:?} exists"
1161        );
1162    }
1163    Ok(())
1164}
1165
1166fn target_kind(locator: &targets::TargetLocator) -> &'static str {
1167    match locator {
1168        targets::TargetLocator::LocalBare { .. } => "local-bare",
1169        targets::TargetLocator::LocalPodman { .. } => "local-podman",
1170        targets::TargetLocator::LocalDocker { .. } => "local-docker",
1171        targets::TargetLocator::AppleContainer { .. } => "apple-container",
1172        targets::TargetLocator::AwsEc2 { .. } => "aws-ec2",
1173        targets::TargetLocator::SshBare { .. } => "ssh-bare",
1174        targets::TargetLocator::SshPodman { .. } => "ssh-podman",
1175        targets::TargetLocator::SshDocker { .. } => "ssh-docker",
1176    }
1177}
1178
1179fn target_profile_home(
1180    locator: &targets::TargetLocator,
1181    session_id: &str,
1182    profile: &mj_core::config::HarnessProfile,
1183) -> String {
1184    let home = match locator {
1185        targets::TargetLocator::LocalBare { worker_root }
1186            if profile.kind == mj_core::config::HarnessKind::Claude =>
1187        {
1188            Path::new(worker_root)
1189                .join("profile")
1190                .to_string_lossy()
1191                .into_owned()
1192        }
1193        targets::TargetLocator::LocalBare { .. } => profile.home.to_string_lossy().into_owned(),
1194        targets::TargetLocator::LocalPodman { .. }
1195        | targets::TargetLocator::LocalDocker { .. }
1196        | targets::TargetLocator::AppleContainer { .. }
1197        | targets::TargetLocator::SshPodman { .. }
1198        | targets::TargetLocator::SshDocker { .. } => {
1199            format!("/var/lib/hel/profiles/{session_id}")
1200        }
1201        targets::TargetLocator::AwsEc2 { .. } | targets::TargetLocator::SshBare { .. } => {
1202            format!(".local/share/hel/profiles/{session_id}")
1203        }
1204    };
1205    if profile.kind == mj_core::config::HarnessKind::Muse {
1206        let root = if matches!(locator, targets::TargetLocator::LocalBare { .. }) {
1207            mj_core::config::data_dir()
1208                .join("profiles")
1209                .join(session_id)
1210        } else {
1211            PathBuf::from(home)
1212        };
1213        root.join("muse").to_string_lossy().into_owned()
1214    } else {
1215        home
1216    }
1217}
1218
1219/// Resolve the login home on the machine that owns an editable path.
1220pub fn resolve_target_input_path(
1221    target: &TargetTemplate,
1222    path: &Path,
1223    executor: &impl CommandExecutor,
1224) -> Result<PathBuf> {
1225    if !mj_core::path_input::needs_home(path)? {
1226        return Ok(path.to_path_buf());
1227    }
1228    match target {
1229        TargetTemplate::SshBare { ssh, .. }
1230        | TargetTemplate::SshPodman { ssh, .. }
1231        | TargetTemplate::SshDocker { ssh, .. } => {
1232            let mut ssh = ssh.clone();
1233            ssh.identity_file = ssh
1234                .identity_file
1235                .as_deref()
1236                .map(mj_core::path_input::expand_local)
1237                .transpose()?;
1238            let command =
1239                ssh_command_spec(&backend_ssh(&ssh), ["sh", "-c", "printf '%s' \"$HOME\""])
1240                    .purpose("resolve remote home directory");
1241            let output = executor.execute(&command)?;
1242            anyhow::ensure!(
1243                output.status == 0,
1244                "Could not resolve remote home: {}",
1245                String::from_utf8_lossy(&output.stderr).trim()
1246            );
1247            let home =
1248                String::from_utf8(output.stdout).context("Remote home is not valid UTF-8")?;
1249            mj_core::path_input::expand_home(path, Some(Path::new(&home)))
1250        }
1251        _ => mj_core::path_input::expand_local(path),
1252    }
1253}
1254
1255pub(crate) fn backend_ssh(ssh: &SshConnection) -> SshTarget {
1256    let destination = match &ssh.user {
1257        Some(user) => format!("{user}@{}", ssh.host),
1258        None => ssh.host.clone(),
1259    };
1260    SshTarget {
1261        destination,
1262        ssh_args: ssh_args_with_identity(&ssh.extra_args, ssh.identity_file.as_deref()),
1263    }
1264}
1265
1266fn ssh_command_spec(
1267    ssh: &SshTarget,
1268    args: impl IntoIterator<Item = impl AsRef<str>>,
1269) -> CommandSpec {
1270    let remote = args
1271        .into_iter()
1272        .map(|arg| arg.as_ref().to_string())
1273        .collect::<Vec<_>>();
1274    let mut command_args = ssh.ssh_args.clone();
1275    command_args.push(ssh.destination.clone());
1276    command_args.push(targets::join_remote_command(&remote));
1277    CommandSpec::new("ssh", command_args)
1278}
1279
1280fn scp_command_spec(ssh: &SshTarget, source: &Path, remote: &str, recursive: bool) -> CommandSpec {
1281    let mut args = ssh.ssh_args.clone();
1282    if recursive {
1283        args.push("-r".into());
1284    }
1285    args.push(source.to_string_lossy().into_owned());
1286    args.push(format!("{}:{remote}", ssh.destination));
1287    CommandSpec::new("scp", args)
1288}
1289
1290fn ssh_args_with_identity(args: &[String], identity: Option<&Path>) -> Vec<String> {
1291    // Mjolnir drives ssh non-interactively from a TUI; a host-key or password
1292    // prompt would steal the terminal and wedge provisioning. BatchMode fails
1293    // fast instead of prompting, and accept-new trusts a first-seen host key
1294    // (fresh EC2 instances are always first-seen) while still rejecting
1295    // changed keys. User-supplied ssh_args come last so they can override.
1296    let mut result = vec![
1297        "-o".into(),
1298        "BatchMode=yes".into(),
1299        "-o".into(),
1300        "StrictHostKeyChecking=accept-new".into(),
1301        "-o".into(),
1302        "ConnectTimeout=15".into(),
1303    ];
1304    result.extend(args.iter().cloned());
1305    if let Some(identity) = identity {
1306        result.push("-i".into());
1307        result.push(identity.to_string_lossy().into_owned());
1308    }
1309    result
1310}
1311
1312fn execute_checked(executor: &impl CommandExecutor, command: CommandSpec) -> Result<CommandOutput> {
1313    let output = executor.execute(&command)?;
1314    if output.status != 0 {
1315        let detail = command_error_detail(&output.stderr);
1316        if detail.is_empty() {
1317            bail!("{} failed with status {}", command.purpose, output.status);
1318        }
1319        bail!("{detail}");
1320    }
1321    Ok(output)
1322}
1323
1324fn command_error_detail(stderr: &[u8]) -> String {
1325    let reported = String::from_utf8_lossy(stderr);
1326    let reported = reported.trim();
1327    let detail = reported
1328        .rsplit_once("\nCaused by:\n")
1329        .map_or(reported, |(_, causes)| causes);
1330    let detail = detail.strip_prefix("Error: ").unwrap_or(detail);
1331    detail
1332        .lines()
1333        .map(|line| line.strip_prefix("    ").unwrap_or(line))
1334        .collect::<Vec<_>>()
1335        .join("\n")
1336        .trim()
1337        .to_owned()
1338}
1339
1340fn now() -> String {
1341    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
1342}
1343
1344fn restore_session_after_persistence_failure(
1345    state: &mut State,
1346    session_id: &str,
1347    previous: &SessionRecord,
1348    primary: anyhow::Error,
1349    persist: impl FnOnce(&SessionRecord) -> Result<()>,
1350) -> anyhow::Error {
1351    state
1352        .sessions
1353        .insert(session_id.to_owned(), previous.clone());
1354    let restored = state
1355        .sessions
1356        .get(session_id)
1357        .expect("restored session record disappeared");
1358    match persist(restored) {
1359        Ok(()) => primary,
1360        Err(error) => primary.context(format!(
1361            "restored prior session state in memory, but failed to persist the rollback: {error:#}"
1362        )),
1363    }
1364}
1365
1366fn persist_session_record_transition_or_restore(
1367    state: &mut State,
1368    session_id: &str,
1369    previous: &SessionRecord,
1370    context: &'static str,
1371    persist: &impl Fn(&SessionRecord) -> Result<()>,
1372) -> Result<()> {
1373    let result = persist(
1374        state
1375            .sessions
1376            .get(session_id)
1377            .expect("checkpoint session disappeared before persistence"),
1378    );
1379    match result {
1380        Ok(()) => Ok(()),
1381        Err(error) => Err(restore_session_after_persistence_failure(
1382            state,
1383            session_id,
1384            previous,
1385            error.context(context),
1386            persist,
1387        )),
1388    }
1389}
1390
1391pub fn config_only_controller(config: Config) -> Controller {
1392    Controller {
1393        config,
1394        state: State::default(),
1395    }
1396}
1397
1398#[cfg(test)]
1399mod tests {
1400    use std::collections::BTreeMap;
1401    use std::path::Path;
1402
1403    use crate::targets::ProcessExecutor;
1404    use mj_core::config::{
1405        Config, ContainerTemplate as ConfigContainer, HarnessKind, HarnessProfile, ProjectBundle,
1406        ProjectRepository, TargetTemplate,
1407    };
1408    use mj_core::state::State;
1409
1410    use super::*;
1411
1412    /// One profile, one bundle with nothing checked out locally, and one
1413    /// container target, which is all `register_session_with_resources` reads.
1414    fn registration_config() -> Config {
1415        let mut config = Config::default();
1416        config.profiles.insert(
1417            "codex".into(),
1418            HarnessProfile {
1419                enabled: true,
1420                kind: HarnessKind::Codex,
1421                home: PathBuf::from("/home/dev/.codex"),
1422                environment: BTreeMap::new(),
1423                context_window_bytes: None,
1424            },
1425        );
1426        config.bundles.insert(
1427            "project".into(),
1428            ProjectBundle {
1429                primary_repo: "project".into(),
1430                repositories: vec![ProjectRepository {
1431                    id: "project".into(),
1432                    github: Some("owner/project".into()),
1433                    local: None,
1434                    destination: PathBuf::from("project"),
1435                    git_ref: None,
1436                }],
1437            },
1438        );
1439        config.targets.insert(
1440            "podman".into(),
1441            TargetTemplate::LocalPodman {
1442                container: ConfigContainer {
1443                    image: "example.invalid/hel-test:latest".into(),
1444                    pull_policy: Default::default(),
1445                    platform: None,
1446                    cpus: None,
1447                    memory: None,
1448                    environment: BTreeMap::new(),
1449                    workspace_storage: Default::default(),
1450                },
1451            },
1452        );
1453        config
1454    }
1455
1456    #[test]
1457    fn remote_completion_preserves_home_shorthand_and_trailing_separator() {
1458        struct CompletionExecutor;
1459        impl CommandExecutor for CompletionExecutor {
1460            fn execute(&self, command: &CommandSpec) -> Result<targets::CommandOutput> {
1461                let script = command.args.last().unwrap();
1462                let stdout = if script.contains("$HOME") {
1463                    b"/remote".to_vec()
1464                } else {
1465                    assert!(script.contains("'/remote/cache/'"), "{script}");
1466                    b"/remote/cache/alpha/\n/remote/cache/alpine/\n".to_vec()
1467                };
1468                Ok(targets::CommandOutput {
1469                    status: 0,
1470                    stdout,
1471                    stderr: Vec::new(),
1472                })
1473            }
1474        }
1475        let target: TargetTemplate =
1476            serde_json::from_str(r#"{"kind":"ssh-podman","host":"builder","image":"test"}"#)
1477                .unwrap();
1478        let mut config = Config::default();
1479        config.targets.insert("remote".into(), target);
1480        let controller = Controller {
1481            config,
1482            state: State::default(),
1483        };
1484        let candidates = controller
1485            .complete_mount_source("remote", "~/cache/", &CompletionExecutor)
1486            .unwrap();
1487        assert_eq!(candidates, ["~/cache/alpha/", "~/cache/alpine/"]);
1488        assert_eq!(
1489            targets::path_completion("~/cache/", &candidates).as_deref(),
1490            Some("~/cache/alp")
1491        );
1492    }
1493
1494    #[test]
1495    fn remote_path_resolution_uses_login_home_without_evaluating_suffix() {
1496        struct HomeExecutor {
1497            status: i32,
1498            home: &'static str,
1499        }
1500        impl CommandExecutor for HomeExecutor {
1501            fn execute(&self, command: &CommandSpec) -> Result<targets::CommandOutput> {
1502                assert_eq!(command.program, "ssh");
1503                let script = command.args.last().unwrap();
1504                assert!(!script.contains("touch"));
1505                assert!(script.contains("$HOME"));
1506                Ok(targets::CommandOutput {
1507                    status: self.status,
1508                    stdout: self.home.as_bytes().to_vec(),
1509                    stderr: b"home lookup failed".to_vec(),
1510                })
1511            }
1512        }
1513        let target: TargetTemplate = serde_json::from_str(
1514            r#"{"kind":"ssh-bare","host":"builder","permissions":"guardian"}"#,
1515        )
1516        .unwrap();
1517        let path = Path::new("~/資料/$(touch nope)");
1518        assert_eq!(
1519            resolve_target_input_path(
1520                &target,
1521                path,
1522                &HomeExecutor {
1523                    status: 0,
1524                    home: "/remote user"
1525                }
1526            )
1527            .unwrap(),
1528            Path::new("/remote user/資料/$(touch nope)")
1529        );
1530        assert!(
1531            resolve_target_input_path(
1532                &target,
1533                path,
1534                &HomeExecutor {
1535                    status: 1,
1536                    home: "/remote"
1537                }
1538            )
1539            .unwrap_err()
1540            .to_string()
1541            .contains("home lookup failed")
1542        );
1543        assert!(
1544            resolve_target_input_path(
1545                &target,
1546                path,
1547                &HomeExecutor {
1548                    status: 0,
1549                    home: ""
1550                }
1551            )
1552            .is_err()
1553        );
1554        assert!(
1555            resolve_target_input_path(
1556                &target,
1557                path,
1558                &HomeExecutor {
1559                    status: 0,
1560                    home: "relative"
1561                }
1562            )
1563            .is_err()
1564        );
1565    }
1566
1567    #[test]
1568    fn bundle_creation_combines_sources_with_first_primary_and_stable_collisions() {
1569        let mut config = Config::default();
1570        let sources = vec!["example/app".into(), "other/app".into()];
1571
1572        let bundle_id = create_bundle_from_sources_in_config(&mut config, &sources).unwrap();
1573        let bundle = &config.bundles[&bundle_id];
1574        assert_eq!(bundle_id, "app");
1575        assert_eq!(bundle.primary_repo, "app");
1576        assert_eq!(
1577            bundle
1578                .repositories
1579                .iter()
1580                .map(|repository| repository.id.as_str())
1581                .collect::<Vec<_>>(),
1582            ["app", "app-2"]
1583        );
1584        assert_eq!(
1585            bundle
1586                .repositories
1587                .iter()
1588                .map(|repository| repository.destination.to_string_lossy().into_owned())
1589                .collect::<Vec<_>>(),
1590            ["app".to_owned(), "app-2".to_owned()]
1591        );
1592        assert_eq!(
1593            bundle.repositories[0].github.as_deref(),
1594            Some("example/app")
1595        );
1596        assert_eq!(bundle.repositories[1].github.as_deref(), Some("other/app"));
1597    }
1598
1599    #[test]
1600    fn bundle_creation_combines_local_and_github_sources_and_rejects_local_aliases() {
1601        let directory = tempfile::tempdir().unwrap();
1602        let root = directory.path().join("app");
1603        let output = mj_core::subprocess::run_capturing_stdout(
1604            std::process::Command::new("git").arg("init").arg(&root),
1605        )
1606        .unwrap();
1607        assert!(output.status.success(), "{output:?}");
1608        let nested = root.join("nested");
1609        fs::create_dir(&nested).unwrap();
1610        let mut config = Config::default();
1611        let sources = vec![root.to_str().unwrap().into(), "example/shared".into()];
1612        let id = create_bundle_from_sources_in_config(&mut config, &sources).unwrap();
1613        let bundle = &config.bundles[&id];
1614        assert_eq!(
1615            bundle.primary().unwrap().local,
1616            Some(root.canonicalize().unwrap())
1617        );
1618        assert_eq!(
1619            bundle.repositories[1].github.as_deref(),
1620            Some("example/shared")
1621        );
1622        let before = config.clone();
1623        let aliases = vec![
1624            root.to_str().unwrap().into(),
1625            nested.to_str().unwrap().into(),
1626        ];
1627        let error = create_bundle_from_sources_in_config(&mut config, &aliases).unwrap_err();
1628        assert!(
1629            error.to_string().contains("duplicate repository source"),
1630            "{error:#}"
1631        );
1632        assert_eq!(config, before);
1633    }
1634
1635    #[test]
1636    fn bundle_creation_rejects_duplicate_normalized_sources_atomically() {
1637        let mut config = Config::default();
1638        let before = config.clone();
1639        let sources = vec![
1640            "example/app".into(),
1641            "https://github.com/EXAMPLE/APP.git".into(),
1642        ];
1643
1644        let error = create_bundle_from_sources_in_config(&mut config, &sources).unwrap_err();
1645        assert!(error.to_string().contains("duplicate repository source"));
1646        assert_eq!(config, before);
1647    }
1648
1649    #[test]
1650    fn bundle_creation_validates_every_source_before_mutating_config() {
1651        let mut config = Config::default();
1652        let before = config.clone();
1653        let invalid_directory = tempfile::tempdir().unwrap();
1654        let sources = vec![
1655            "example/app".into(),
1656            invalid_directory.path().to_string_lossy().into_owned(),
1657        ];
1658
1659        let error = create_bundle_from_sources_in_config(&mut config, &sources).unwrap_err();
1660        assert!(error.to_string().contains("not a Git repository"));
1661        assert_eq!(config, before);
1662    }
1663
1664    #[test]
1665    fn bundle_creation_reuses_an_exact_source_set_and_rejects_obsolete_pins() {
1666        let mut config = Config::default();
1667        config.bundles.insert(
1668            "all".into(),
1669            ProjectBundle {
1670                primary_repo: "app".into(),
1671                repositories: vec![
1672                    ProjectRepository {
1673                        id: "app".into(),
1674                        github: Some("example/app".into()),
1675                        local: None,
1676                        destination: "app".into(),
1677                        git_ref: None,
1678                    },
1679                    ProjectRepository {
1680                        id: "shared".into(),
1681                        github: Some("example/shared".into()),
1682                        local: None,
1683                        destination: "shared".into(),
1684                        git_ref: None,
1685                    },
1686                ],
1687            },
1688        );
1689
1690        let one_source = vec!["example/app".into()];
1691        let created = create_bundle_from_sources_in_config(&mut config, &one_source).unwrap();
1692        assert_eq!(created, "app");
1693        assert_eq!(config.bundles[&created].repositories.len(), 1);
1694        assert_eq!(
1695            create_bundle_from_sources_in_config(&mut config, &one_source).unwrap(),
1696            "app"
1697        );
1698
1699        let exact_sources = vec!["example/app".into(), "example/shared".into()];
1700        assert_eq!(
1701            create_bundle_from_sources_in_config(&mut config, &exact_sources).unwrap(),
1702            "all"
1703        );
1704        assert_eq!(config.bundles.len(), 2);
1705        config.bundles.get_mut("all").unwrap().repositories[0].git_ref = Some("release".into());
1706        let before = config.clone();
1707        let error = create_bundle_from_sources_in_config(&mut config, &exact_sources).unwrap_err();
1708        assert!(format!("{error:#}").contains("git_ref is no longer supported"));
1709        assert_eq!(config, before);
1710    }
1711
1712    fn launch_options(additional_mounts: Vec<AdditionalMount>) -> SessionLaunchOptions {
1713        SessionLaunchOptions {
1714            create_managed_worktree: None,
1715            initial_prompt: None,
1716            workspace_id: mj_core::workspace::DEFAULT_WORKSPACE_ID.to_owned(),
1717            additional_mounts,
1718            allow_dirty_local: false,
1719            resource_allocation: None,
1720            project_directory: None,
1721            session_title_override: None,
1722        }
1723    }
1724
1725    #[test]
1726    fn registration_rejects_a_disabled_profile_before_persisting() {
1727        let mut config = registration_config();
1728        config.profiles.get_mut("codex").unwrap().enabled = false;
1729        let mut controller = Controller {
1730            config,
1731            state: State::default(),
1732        };
1733
1734        let error = controller
1735            .register_session_with_resources(
1736                "codex",
1737                "project",
1738                "podman",
1739                "disabled",
1740                launch_options(Vec::new()),
1741            )
1742            .unwrap_err();
1743
1744        assert!(error.to_string().contains("disabled"));
1745        assert!(controller.state.sessions.is_empty());
1746    }
1747
1748    #[test]
1749    fn deepseek_registration_rejects_more_than_one_workspace_root_before_persisting() {
1750        let mut config = registration_config();
1751        config.profiles.get_mut("codex").unwrap().kind = HarnessKind::Deepseek;
1752        let second = config.bundles["project"].repositories[0].clone();
1753        config
1754            .bundles
1755            .get_mut("project")
1756            .unwrap()
1757            .repositories
1758            .push(mj_core::config::ProjectRepository {
1759                id: "second".into(),
1760                destination: "second".into(),
1761                ..second
1762            });
1763        let mut controller = Controller {
1764            config,
1765            state: State::default(),
1766        };
1767
1768        let error = controller
1769            .register_session_with_resources(
1770                "codex",
1771                "project",
1772                "podman",
1773                "unsupported",
1774                launch_options(Vec::new()),
1775            )
1776            .unwrap_err();
1777
1778        assert!(error.to_string().contains("one workspace root"));
1779        assert!(controller.state.sessions.is_empty());
1780    }
1781
1782    /// MJ_DATA_DIR is process-global, so every test that reaches the
1783    /// controller database runs in an exact child with its own data directory.
1784    fn run_registration_child(marker: &str, test: &str, data_directory: &Path) {
1785        let output = std::process::Command::new(std::env::current_exe().unwrap())
1786            .args([
1787                "--exact",
1788                &format!("controller::tests::{test}"),
1789                "--nocapture",
1790            ])
1791            .env(marker, "1")
1792            .env("MJ_DATA_DIR", data_directory)
1793            .env("MJ_CONFIG_DIR", data_directory)
1794            .output()
1795            .unwrap();
1796        assert!(
1797            output.status.success(),
1798            "isolated {test} failed\nstdout:\n{}\nstderr:\n{}",
1799            String::from_utf8_lossy(&output.stdout),
1800            String::from_utf8_lossy(&output.stderr)
1801        );
1802    }
1803
1804    #[test]
1805    fn registration_saves_the_initial_task_before_provisioning() {
1806        const MARKER: &str = "MJ_TEST_INITIAL_TASK_CHILD";
1807        if std::env::var_os(MARKER).is_none() {
1808            let directory = tempfile::tempdir().unwrap();
1809            run_registration_child(
1810                MARKER,
1811                "registration_saves_the_initial_task_before_provisioning",
1812                directory.path(),
1813            );
1814            return;
1815        }
1816        let _writer = crate::database::install_isolated_test_writer();
1817        let mut controller = Controller {
1818            config: registration_config(),
1819            state: State::default(),
1820        };
1821        let prompt = format!(
1822            "Initial task\n{}\n\tPreserve indentation and λ",
1823            "x".repeat(70_000)
1824        );
1825        let mut options = launch_options(Vec::new());
1826        options.initial_prompt = Some(prompt.clone());
1827        let id = controller
1828            .register_session_with_resources("codex", "project", "podman", "fresh task", options)
1829            .unwrap();
1830        let saved = crate::database::load_state().unwrap();
1831        assert_eq!(saved.sessions[&id].draft_input, prompt);
1832        assert_eq!(saved.sessions[&id].state, SessionState::Provisioning);
1833        crate::database::set_session_draft_input(&id, "a newer draft").unwrap();
1834        crate::database::clear_session_draft_input_if_matches(&id, &prompt).unwrap();
1835        assert_eq!(
1836            crate::database::load_state().unwrap().sessions[&id].draft_input,
1837            "a newer draft"
1838        );
1839        crate::database::clear_session_draft_input_if_matches(&id, "a newer draft").unwrap();
1840        assert!(
1841            crate::database::load_state().unwrap().sessions[&id]
1842                .draft_input
1843                .is_empty()
1844        );
1845    }
1846
1847    const UNPERSISTABLE_SESSION_CHILD: &str = "MJ_TEST_UNPERSISTABLE_SESSION_CHILD";
1848
1849    #[test]
1850    fn missing_bundle_does_not_block_controller_or_other_sessions() {
1851        const CHILD: &str = "MJ_TEST_MISSING_BUNDLE_CHILD";
1852        if std::env::var_os(CHILD).is_none() {
1853            let directory = tempfile::tempdir().unwrap();
1854            run_registration_child(
1855                CHILD,
1856                "missing_bundle_does_not_block_controller_or_other_sessions",
1857                directory.path(),
1858            );
1859            return;
1860        }
1861        let _writer = crate::database::install_isolated_test_writer();
1862        let mut controller = Controller {
1863            config: registration_config(),
1864            state: State::default(),
1865        };
1866        let bundle = controller.config.bundles["project"].clone();
1867        controller
1868            .config
1869            .bundles
1870            .insert("other".into(), bundle.clone());
1871        controller.config.save().unwrap();
1872        let affected = controller
1873            .register_session_with_resources(
1874                "codex",
1875                "project",
1876                "podman",
1877                "affected",
1878                launch_options(Vec::new()),
1879            )
1880            .unwrap();
1881        let healthy = controller
1882            .register_session_with_resources(
1883                "codex",
1884                "other",
1885                "podman",
1886                "healthy",
1887                launch_options(Vec::new()),
1888            )
1889            .unwrap();
1890        controller.config.bundles.remove("project");
1891        controller.config.save().unwrap();
1892        let loaded = Controller::load().unwrap();
1893        assert_eq!(loaded.state.sessions.len(), 2);
1894        assert!(
1895            loaded.state.sessions[&healthy]
1896                .configuration_issue(&loaded.config)
1897                .is_none()
1898        );
1899        let issue = loaded.reconnect_command(&affected).unwrap_err().to_string();
1900        assert!(issue.contains("missing bundle"), "{issue}");
1901        assert!(issue.contains("config.toml"), "{issue}");
1902        // Loading must not turn a configuration problem into a persisted lifecycle failure.
1903        assert_eq!(
1904            loaded.state.sessions[&affected],
1905            controller.state.sessions[&affected]
1906        );
1907        Config::update(|config| {
1908            config.bundles.insert("project".into(), bundle);
1909            Ok(())
1910        })
1911        .unwrap();
1912        let repaired = Controller::load().unwrap();
1913        assert!(
1914            repaired.state.sessions[&affected]
1915                .configuration_issue(&repaired.config)
1916                .is_none()
1917        );
1918    }
1919
1920    const CONFIG_ID_RENAME_CHILD: &str = "MJ_TEST_CONFIG_ID_RENAME_CHILD";
1921
1922    #[test]
1923    fn configuration_id_rename_rewrites_durable_session_references() {
1924        if std::env::var_os(CONFIG_ID_RENAME_CHILD).is_none() {
1925            let directory = tempfile::tempdir().unwrap();
1926            run_registration_child(
1927                CONFIG_ID_RENAME_CHILD,
1928                "configuration_id_rename_rewrites_durable_session_references",
1929                directory.path(),
1930            );
1931            return;
1932        }
1933        // Alone in this child process, so it installs the one writer.
1934        let _writer = crate::database::install_isolated_test_writer();
1935
1936        let mut controller = Controller {
1937            config: registration_config(),
1938            state: State::default(),
1939        };
1940        controller.config.save().unwrap();
1941        let session_id = controller
1942            .register_session_with_resources(
1943                "codex",
1944                "project",
1945                "podman",
1946                "rename references",
1947                launch_options(Vec::new()),
1948            )
1949            .unwrap();
1950
1951        controller
1952            .rename_profile_id("codex", "codex-renamed")
1953            .unwrap();
1954        controller
1955            .rename_target_id("podman", "podman-renamed")
1956            .unwrap();
1957
1958        let loaded = Controller::load().unwrap();
1959        let session = &loaded.state.sessions[&session_id];
1960        assert_eq!(session.last_profile, "codex-renamed");
1961        assert_eq!(session.target_template_id, "podman-renamed");
1962        assert!(loaded.config.profiles.contains_key("codex-renamed"));
1963        assert!(loaded.config.targets.contains_key("podman-renamed"));
1964        assert!(!config_rename_journal_path().exists());
1965    }
1966
1967    #[test]
1968    fn a_session_the_database_rejects_is_never_left_in_memory() {
1969        if std::env::var_os(UNPERSISTABLE_SESSION_CHILD).is_none() {
1970            let directory = tempfile::tempdir().unwrap();
1971            run_registration_child(
1972                UNPERSISTABLE_SESSION_CHILD,
1973                "a_session_the_database_rejects_is_never_left_in_memory",
1974                directory.path(),
1975            );
1976            return;
1977        }
1978        // Alone in this child process, so it installs the one writer.
1979        let _writer = crate::database::install_isolated_test_writer();
1980
1981        let mut controller = Controller {
1982            config: registration_config(),
1983            state: State::default(),
1984        };
1985        // The store has to be healthy enough to open before it can reject a
1986        // write: this test is about a write the database refuses, not about a
1987        // store that cannot be opened at all, which now fails earlier and
1988        // louder when the writer is installed. The first registration builds
1989        // the schema the second one then loses.
1990        controller
1991            .register_session_with_resources(
1992                "codex",
1993                "project",
1994                "podman",
1995                "first",
1996                launch_options(Vec::new()),
1997            )
1998            .expect("a healthy store registers a session");
1999        rusqlite::Connection::open(crate::database::database_path())
2000            .unwrap()
2001            .execute_batch("DROP TABLE sessions")
2002            .unwrap();
2003
2004        let error = controller
2005            .register_session_with_resources(
2006                "codex",
2007                "project",
2008                "podman",
2009                "unpersistable",
2010                launch_options(Vec::new()),
2011            )
2012            .expect_err("a store that rejects the write cannot register a session");
2013        assert!(
2014            format!("{error:#}").contains("sessions"),
2015            "unexpected error: {error:#}"
2016        );
2017        assert_eq!(
2018            controller.state.sessions.len(),
2019            1,
2020            "a session the database never accepted stayed in controller memory"
2021        );
2022        assert!(
2023            controller
2024                .state
2025                .sessions
2026                .values()
2027                .all(|session| session.title != "unpersistable"),
2028            "the rejected session is the one that stayed"
2029        );
2030    }
2031
2032    const MOUNT_HISTORY_FAILURE_CHILD: &str = "MJ_TEST_MOUNT_HISTORY_FAILURE_CHILD";
2033
2034    const CONTAINER_SIZE_HISTORY_CHILD: &str = "MJ_TEST_CONTAINER_SIZE_HISTORY_CHILD";
2035
2036    #[test]
2037    fn registration_remembers_launch_size_but_session_overrides_do_not_replace_it() {
2038        if std::env::var_os(CONTAINER_SIZE_HISTORY_CHILD).is_none() {
2039            let directory = tempfile::tempdir().unwrap();
2040            run_registration_child(
2041                CONTAINER_SIZE_HISTORY_CHILD,
2042                "registration_remembers_launch_size_but_session_overrides_do_not_replace_it",
2043                directory.path(),
2044            );
2045            return;
2046        }
2047        // Alone in this child process, so it installs the one writer.
2048        let _writer = crate::database::install_isolated_test_writer();
2049
2050        let mut controller = Controller {
2051            config: registration_config(),
2052            state: State::default(),
2053        };
2054        let mut options = launch_options(Vec::new());
2055        options.resource_allocation = Some(SessionResourceAllocation::Container {
2056            cpus: 12,
2057            memory_bytes: 48 * 1024 * 1024 * 1024,
2058        });
2059        let id = controller
2060            .register_session_with_resources("codex", "project", "podman", "sized", options)
2061            .unwrap();
2062        let expected = HostContainerSize {
2063            cpus: 12,
2064            memory_bytes: 48 * 1024 * 1024 * 1024,
2065        };
2066        assert_eq!(controller.state.container_sizes["local"], expected);
2067        assert_eq!(
2068            crate::database::load_state_migrating()
2069                .unwrap()
2070                .container_sizes["local"],
2071            expected
2072        );
2073
2074        controller
2075            .update_session_container_settings(
2076                &id,
2077                Some("2".into()),
2078                Some("4g".into()),
2079                Vec::new(),
2080                Vec::new(),
2081            )
2082            .unwrap();
2083        assert_eq!(
2084            crate::database::load_state_migrating()
2085                .unwrap()
2086                .container_sizes["local"],
2087            expected
2088        );
2089    }
2090
2091    #[test]
2092    fn a_failed_mount_history_write_does_not_fail_the_registered_session() {
2093        if std::env::var_os(MOUNT_HISTORY_FAILURE_CHILD).is_none() {
2094            let directory = tempfile::tempdir().unwrap();
2095            run_registration_child(
2096                MOUNT_HISTORY_FAILURE_CHILD,
2097                "a_failed_mount_history_write_does_not_fail_the_registered_session",
2098                directory.path(),
2099            );
2100            return;
2101        }
2102        // Alone in this child process, so it installs the one writer.
2103        let _writer = crate::database::install_isolated_test_writer();
2104
2105        let mut controller = Controller {
2106            config: registration_config(),
2107            state: State::default(),
2108        };
2109        // The first registration builds the schema this test then breaks.
2110        controller
2111            .register_session_with_resources(
2112                "codex",
2113                "project",
2114                "podman",
2115                "first",
2116                launch_options(Vec::new()),
2117            )
2118            .expect("a healthy store registers a session");
2119        let database = crate::database::database_path();
2120        rusqlite::Connection::open(&database)
2121            .unwrap()
2122            .execute_batch("DROP TABLE mount_history")
2123            .unwrap();
2124
2125        let id = controller
2126            .register_session_with_resources(
2127                "codex",
2128                "project",
2129                "podman",
2130                "attached",
2131                launch_options(vec![AdditionalMount {
2132                    source: PathBuf::from("/host/models"),
2133                    destination: PathBuf::from("/mnt/models"),
2134                    read_only: false,
2135                }]),
2136            )
2137            .expect("a suggestion list that cannot be written must not fail a registration");
2138
2139        let stored: i64 = rusqlite::Connection::open(&database)
2140            .unwrap()
2141            .query_row(
2142                "SELECT count(*) FROM sessions WHERE session_id = ?1",
2143                [&id],
2144                |row| row.get(0),
2145            )
2146            .unwrap();
2147        assert_eq!(stored, 1, "the registered session was not committed");
2148        assert!(
2149            controller.state.mount_history.is_empty(),
2150            "controller memory remembered mount sources the database never stored"
2151        );
2152    }
2153
2154    #[test]
2155    fn command_errors_report_the_root_cause_without_worker_wrappers() {
2156        let stderr = b"Error: restore target checkpoint failed with status 1: Error: restore repository \"bifrost\"\n\nCaused by:\n    checkpoint base b41dc78 is absent from configured source\n    repository may have moved\n";
2157
2158        assert_eq!(
2159            command_error_detail(stderr),
2160            "checkpoint base b41dc78 is absent from configured source\nrepository may have moved"
2161        );
2162    }
2163
2164    #[test]
2165    fn controller_store_lock_excludes_a_second_process_owner() {
2166        let directory = tempfile::tempdir().unwrap();
2167        let first = ControllerStoreGuard::acquire_at(directory.path()).unwrap();
2168        run_controller_lock_probe(directory.path(), true);
2169        drop(first);
2170        run_controller_lock_probe(directory.path(), false);
2171    }
2172    fn run_controller_lock_probe(directory: &Path, expect_locked: bool) {
2173        let output = std::process::Command::new(std::env::current_exe().unwrap())
2174            .args([
2175                "--exact",
2176                "controller::tests::controller_store_lock_subprocess_probe",
2177                "--nocapture",
2178            ])
2179            .env("MJ_CONTROLLER_LOCK_PROBE", directory)
2180            .env(
2181                "MJ_CONTROLLER_LOCK_EXPECTED",
2182                if expect_locked { "locked" } else { "available" },
2183            )
2184            .output()
2185            .unwrap();
2186        assert!(
2187            output.status.success(),
2188            "controller lock subprocess failed:\nstdout:\n{}\nstderr:\n{}",
2189            String::from_utf8_lossy(&output.stdout),
2190            String::from_utf8_lossy(&output.stderr)
2191        );
2192    }
2193    #[test]
2194    fn controller_store_lock_subprocess_probe() {
2195        let Some(directory) = std::env::var_os("MJ_CONTROLLER_LOCK_PROBE") else {
2196            return;
2197        };
2198        let expected = std::env::var("MJ_CONTROLLER_LOCK_EXPECTED").unwrap();
2199        let acquired = ControllerStoreGuard::acquire_at(Path::new(&directory));
2200        match expected.as_str() {
2201            "locked" => {
2202                let error = acquired.expect_err("a second process acquired the controller store");
2203                assert!(error.to_string().contains("another Mjolnir controller"));
2204            }
2205            "available" => {
2206                acquired.expect("released controller store stayed locked");
2207            }
2208            value => panic!("unexpected lock probe expectation {value:?}"),
2209        }
2210    }
2211    #[test]
2212    fn local_mount_source_must_be_an_existing_directory() {
2213        let directory = tempfile::tempdir().unwrap();
2214        let file = directory.path().join("file");
2215        std::fs::write(&file, "not a directory").unwrap();
2216        let mut config = Config::default();
2217        config.targets.insert(
2218            "local".into(),
2219            TargetTemplate::LocalPodman {
2220                container: ConfigContainer {
2221                    image: "ubuntu:24.04".into(),
2222                    pull_policy: Default::default(),
2223                    platform: None,
2224                    cpus: None,
2225                    memory: None,
2226                    environment: BTreeMap::new(),
2227                    workspace_storage: Default::default(),
2228                },
2229            },
2230        );
2231        let controller = Controller {
2232            config,
2233            state: State::default(),
2234        };
2235
2236        assert!(
2237            controller
2238                .validate_mount_source("local", directory.path(), &ProcessExecutor)
2239                .is_ok()
2240        );
2241        for invalid in [file, directory.path().join("missing")] {
2242            let error = controller
2243                .validate_mount_source("local", &invalid, &ProcessExecutor)
2244                .unwrap_err();
2245            assert!(
2246                error
2247                    .to_string()
2248                    .contains("does not exist or is not a directory")
2249            );
2250        }
2251    }
2252}