Skip to main content

mj_client/
target.rs

1//! Pure target and resume compatibility contracts shared by control surfaces.
2
3use anyhow::{Result, bail};
4use mj_core::config::{Config, TargetTemplate, is_bare_project_target};
5use mj_core::state::{ManagedWorktreeTarget, SessionRecord};
6
7// Published from containers/Containerfile.agent-dev by
8// .github/workflows/publish-agent-dev-image.yml. It already carries Node, Rust,
9// Git, gh, and the pinned ACP bridges, so a first session does not have to
10// install them.
11pub use mj_core::config::DEFAULT_CONTAINER_IMAGE as DEFAULT_IMAGE;
12
13/// Convert a configured bare target to the durable target identity stored on
14/// managed worktrees.
15pub fn managed_worktree_target(template: &TargetTemplate) -> Result<ManagedWorktreeTarget> {
16    match template {
17        TargetTemplate::LocalBare => Ok(ManagedWorktreeTarget::Local),
18        TargetTemplate::SshBare { ssh, .. } => {
19            let destination = match &ssh.user {
20                Some(user) => format!("{user}@{}", ssh.host),
21                None => ssh.host.clone(),
22            };
23            // The same arguments the controller's SSH backend uses. Only the
24            // location they name (see `ManagedWorktreeTarget::same_location`)
25            // decides whether a resume stays put.
26            let ssh_args = mj_core::targets::ssh_args_with_identity(
27                &ssh.extra_args,
28                ssh.identity_file.as_deref(),
29            );
30            Ok(ManagedWorktreeTarget::Ssh {
31                destination,
32                ssh_args,
33            })
34        }
35        _ => bail!("managed raw worktrees require a bare target"),
36    }
37}
38
39/// What a resume has to do to the session record before it provisions.
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41pub enum ResumePlan {
42    /// Keep the session in the representation it already has.
43    InPlace,
44    /// Move a raw checkout session into a workspace target as a bundle
45    /// session. Only a whole checkout on this machine reaches this plan; the
46    /// conversion still requires that checkout to have a network Git remote,
47    /// which only Git can answer.
48    RawToWorkspace,
49    /// Move a bundle session out of its workspace into a raw local worktree.
50    WorkspaceToRaw,
51}
52
53/// Whether `session` may resume on `target_id`, and what the resume must do to
54/// the session record. The error is shown to the person choosing the target, so
55/// it says where the session is tied down and what to pick instead.
56///
57/// This decides representation only. It performs no I/O, so it can run on every
58/// row of a target picker.
59pub fn resume_compatibility(
60    session: &SessionRecord,
61    config: &Config,
62    target_id: &str,
63) -> Result<ResumePlan, String> {
64    let Some(target) = config.targets.get(target_id) else {
65        return Err(format!("target {target_id} is no longer configured"));
66    };
67    let Some(project_directory) = &session.project_directory else {
68        if matches!(target, TargetTemplate::LocalBare) {
69            return workspace_to_raw_compatibility(session, config);
70        }
71        return Ok(ResumePlan::InPlace);
72    };
73    let directory = project_directory.display();
74    let Some(worktree) = &session.managed_worktree else {
75        let Some(previous) = config.targets.get(&session.target_template_id) else {
76            return Err(
77                "the bare target this session last used is no longer configured".to_owned(),
78            );
79        };
80        if is_bare_project_target(target) {
81            if matches!(previous, TargetTemplate::LocalBare)
82                == matches!(target, TargetTemplate::LocalBare)
83            {
84                return Ok(ResumePlan::InPlace);
85            }
86            return Err(format!(
87                "this session opens {directory} directly on its host; resume it on the same kind of bare target"
88            ));
89        }
90        // A checkout on this machine can become an isolated workspace: the
91        // resume re-snapshots it against its own network remote. Whether the
92        // recorded directory really is a whole checkout with such a remote
93        // needs Git, so the conversion plan decides that, not the picker.
94        if matches!(previous, TargetTemplate::LocalBare) {
95            return Ok(ResumePlan::RawToWorkspace);
96        }
97        return Err(format!(
98            "this session opens {directory} on an SSH host; resume it on a bare target there"
99        ));
100    };
101    match managed_worktree_target(target) {
102        Ok(resume_target) if resume_target.same_location(&worktree.target) => {
103            Ok(ResumePlan::InPlace)
104        }
105        Ok(_) => Err(format!(
106            "this session's working tree lives on {}; resume it there",
107            managed_worktree_location(&worktree.target)
108        )),
109        Err(_) if worktree.target != ManagedWorktreeTarget::Local => Err(format!(
110            "this session works directly in {directory} on {}; resume it on a bare target there",
111            managed_worktree_location(&worktree.target)
112        )),
113        // A whole managed worktree on this machine converts: the resume
114        // re-snapshots it against the owning checkout's network remote.
115        Err(_) if Some(&worktree.worktree_root) == session.project_directory.as_ref() => {
116            Ok(ResumePlan::RawToWorkspace)
117        }
118        Err(_) => Err(format!(
119            "this session opens {directory}, a subdirectory of its checkout; resume it on a bare target"
120        )),
121    }
122}
123
124/// Why a bundle session cannot resume on a local bare target. A bare target has
125/// no managed workspace to restore the bundle into.
126const BUNDLE_ON_LOCAL_BARE: &str = "this session was created from a project bundle; a local bare target only hosts raw project sessions — resume it on a container, SSH, or EC2 target";
127
128/// Whether a bundle session can leave its workspace for a checkout on this
129/// machine. Only a single repository already on this machine can become one.
130fn workspace_to_raw_compatibility(
131    session: &SessionRecord,
132    config: &Config,
133) -> Result<ResumePlan, String> {
134    let Some(bundle) = config.bundles.get(&session.bundle_id) else {
135        return Err(BUNDLE_ON_LOCAL_BARE.to_owned());
136    };
137    let [repository] = bundle.repositories.as_slice() else {
138        return Err(format!(
139            "this session's project has {} repositories; a local bare target holds one checkout — resume it on a container, SSH, or EC2 target",
140            bundle.repositories.len()
141        ));
142    };
143    if repository.local.is_none() {
144        return Err(
145            "this session's project came from GitHub; resume it on a container, SSH, or EC2 target"
146                .to_owned(),
147        );
148    }
149    Ok(ResumePlan::WorkspaceToRaw)
150}
151
152/// Where a managed worktree's checkout physically lives, in words a user
153/// reads.
154fn managed_worktree_location(target: &ManagedWorktreeTarget) -> String {
155    match target {
156        ManagedWorktreeTarget::Local => "this machine".to_owned(),
157        ManagedWorktreeTarget::Ssh { destination, .. } => destination.clone(),
158    }
159}