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 hel::hel_config::{HelConfig, TargetTemplate, is_bare_project_target};
5use hel::hel_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 const DEFAULT_IMAGE: &str = "ghcr.io/brokkai/mjolnir/agent-dev:latest";
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            // Keep this in lockstep with the controller's SSH backend. These
24            // options are part of the target identity because the managed
25            // worktree compares it when deciding whether a resume stays put.
26            let mut ssh_args = vec![
27                "-o".to_owned(),
28                "BatchMode=yes".to_owned(),
29                "-o".to_owned(),
30                "StrictHostKeyChecking=accept-new".to_owned(),
31                "-o".to_owned(),
32                "ConnectTimeout=15".to_owned(),
33            ];
34            ssh_args.extend(ssh.extra_args.iter().cloned());
35            if let Some(identity) = &ssh.identity_file {
36                ssh_args.push("-i".to_owned());
37                ssh_args.push(identity.to_string_lossy().into_owned());
38            }
39            Ok(ManagedWorktreeTarget::Ssh {
40                destination,
41                ssh_args,
42            })
43        }
44        _ => bail!("managed raw worktrees require a bare target"),
45    }
46}
47
48/// What a resume has to do to the session record before it provisions.
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum ResumePlan {
51    /// Keep the session in the representation it already has.
52    InPlace,
53    /// Move a raw checkout session into a workspace target as a bundle session.
54    RawToWorkspace,
55    /// Move a bundle session out of its workspace into a raw local worktree.
56    WorkspaceToRaw,
57}
58
59/// Whether `session` may resume on `target_id`, and what the resume must do to
60/// the session record. The error is shown to the person choosing the target, so
61/// it says where the session is tied down and what to pick instead.
62///
63/// This decides representation only. It performs no I/O, so it can run on every
64/// row of a target picker.
65pub fn resume_compatibility(
66    session: &SessionRecord,
67    config: &HelConfig,
68    target_id: &str,
69) -> Result<ResumePlan, String> {
70    let Some(target) = config.targets.get(target_id) else {
71        return Err(format!("target {target_id} is no longer configured"));
72    };
73    let Some(project_directory) = &session.project_directory else {
74        if matches!(target, TargetTemplate::LocalBare) {
75            return workspace_to_raw_compatibility(session, config);
76        }
77        return Ok(ResumePlan::InPlace);
78    };
79    let directory = project_directory.display();
80    let Some(worktree) = &session.managed_worktree else {
81        let Some(previous) = config.targets.get(&session.target_template_id) else {
82            return Err(
83                "the bare target this session last used is no longer configured".to_owned(),
84            );
85        };
86        if is_bare_project_target(target) {
87            if matches!(previous, TargetTemplate::LocalBare)
88                == matches!(target, TargetTemplate::LocalBare)
89            {
90                return Ok(ResumePlan::InPlace);
91            }
92            return Err(format!(
93                "this session opens {directory} directly on its host; resume it on the same kind of bare target"
94            ));
95        }
96        if matches!(previous, TargetTemplate::LocalBare) {
97            return Err("raw sessions do not have isolated network repository provenance; resume on a bare target or start a new isolated session".to_owned());
98        }
99        return Err(format!(
100            "this session opens {directory} on an SSH host; resume it on a bare target there"
101        ));
102    };
103    match managed_worktree_target(target) {
104        Ok(resume_target) if resume_target == worktree.target => Ok(ResumePlan::InPlace),
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        // Reject this in the target picker and live-move preparation, before
114        // any source is stopped: raw checkpoints cannot seed isolated clones.
115        Err(_) if Some(&worktree.worktree_root) == session.project_directory.as_ref() => {
116            Err("raw sessions do not have isolated network repository provenance; resume on a bare target or start a new isolated session".to_owned())
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: &HelConfig,
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}