Skip to main content

mj_controller/import/
native_import.rs

1use super::*;
2
3pub struct NativeImportRequest<'a> {
4    pub harness: HarnessKind,
5    pub harness_home: &'a Path,
6    pub native_session_id: &'a str,
7    pub source_path: &'a Path,
8    pub transcript: &'a ClaudeTranscript,
9    pub bundle_id: &'a str,
10    pub profile_id: Option<&'a str>,
11    pub title: Option<&'a str>,
12    pub archive_directory: &'a Path,
13}
14
15/// Build, verify, and install a local archive for one already-located,
16/// already-parsed native session, for any harness, then update the in-memory
17/// state. The caller saves `state` only after this returns successfully.
18pub fn import_native_session(
19    config: &Config,
20    state: &mut State,
21    request: NativeImportRequest<'_>,
22    control: Option<&ImportControl<'_>>,
23) -> Result<ImportedClaudeSession> {
24    let NativeImportRequest {
25        harness,
26        harness_home,
27        native_session_id,
28        source_path,
29        transcript,
30        bundle_id,
31        profile_id,
32        title,
33        archive_directory,
34    } = request;
35    let bundle = config
36        .bundles
37        .get(bundle_id)
38        .with_context(|| format!("unknown bundle {bundle_id:?}"))?;
39    let session_title_override = title.map(str::to_owned);
40    let title = match session_title_override.as_deref() {
41        Some(title) if !title.trim().is_empty() => title.to_owned(),
42        Some(_) => bail!("import title must not be empty"),
43        None => harness_session_title(&transcript.events).unwrap_or_else(|| {
44            format!(
45                "Imported {} session {native_session_id}",
46                harness.display_name()
47            )
48        }),
49    };
50    let targets = session_edit_targets(transcript, harness_home)?;
51    let raw_project = raw_project_import(config, &targets);
52    let repositories =
53        collect_local_repositories(bundle, &targets.git_roots, raw_project.is_none(), control)?;
54    let native_artifacts =
55        collect_import_native_artifacts(harness, harness_home, native_session_id, source_path)?;
56    if harness == HarnessKind::Muse {
57        // The preview may precede a user's confirmation by minutes. Never
58        // pair its old transcript with a newer native conversation.
59        if let Some(control) = control {
60            control.check_cancelled()?;
61        }
62        let current = read_native_transcript(harness, source_path)?;
63        ensure!(
64            current.cwd == transcript.cwd
65                && current.edited_paths == transcript.edited_paths
66                && serde_json::to_value(&current.events)?
67                    == serde_json::to_value(&transcript.events)?,
68            "native session changed after it was selected; select it again"
69        );
70        ensure!(
71            native_artifacts
72                == collect_import_native_artifacts(
73                    harness,
74                    harness_home,
75                    native_session_id,
76                    source_path
77                )?,
78            "native session changed while being imported; stop its harness and retry"
79        );
80    }
81    let session_id = new_session_id()?;
82    let canonical_session =
83        canonical_import_session(session_id.as_str(), &transcript.events, source_path)?;
84    let timestamp = timestamp();
85    let profile_id = import_profile_id(config, profile_id, harness, harness_home)?;
86    let target_id = default_import_target_id(config);
87    let archive_path = archive_directory.join(format!("{session_id}.hel.zip"));
88    if let Some(control) = control {
89        control.report(ImportArchiveProgress::WritingArchive)?;
90    }
91    let verified = write_archive_atomic(
92        &archive_path,
93        &ArchiveInput {
94            session: mj_checkpoint::archive::SessionManifest {
95                id: session_id.clone(),
96                title: title.clone(),
97                harness_kind: harness,
98                profile_id: profile_id.clone(),
99                native_session_id: native_session_id.to_owned(),
100                created_at: timestamp.clone(),
101                checkpointed_at: timestamp.clone(),
102                hel_version: env!("CARGO_PKG_VERSION").into(),
103                relay_version: env!("CARGO_PKG_VERSION").into(),
104                adapter_version: "acp-v1".into(),
105            },
106            target: TargetManifest {
107                template_id: target_id.clone(),
108                target_kind: "import".into(),
109                details: BTreeMap::from([("source".into(), format!("{}-import", harness.id()))]),
110            },
111            bundle: BundleManifest {
112                id: bundle_id.to_owned(),
113                primary_repository: bundle.primary_repo.clone(),
114            },
115            canonical_session,
116            native_artifacts,
117            repositories,
118        },
119    )?;
120    if let Some(control) = control
121        && let Err(error) = control.check_cancelled()
122    {
123        let _ = fs::remove_file(&archive_path);
124        return Err(error);
125    }
126    let checkpoint = CheckpointMetadata {
127        archive_path: archive_path.clone(),
128        sha256: verified.archive_sha256,
129        created_at: timestamp.clone(),
130        event_frontier: transcript.events.last().map_or(0, |event| event.seq),
131    };
132    state.sessions.insert(
133        session_id.clone(),
134        SessionRecord {
135            build_cache: None,
136            mjolnir_subagents: None,
137            // An imported history is a new session: when it is resumed into a
138            // container it gets its own workspace, like any session created
139            // now.
140            container_workspace: Some(mj_core::targets::new_container_workspace(&session_id)?),
141            create_managed_worktree: None,
142            workspace_id: mj_core::workspace::DEFAULT_WORKSPACE_ID.to_owned(),
143            archived: false,
144            container_cpus: None,
145            container_memory: None,
146            id: session_id.clone(),
147            title,
148            harness_kind: harness,
149            last_profile: profile_id,
150            bundle_id: bundle_id.to_owned(),
151            project_directory: raw_project.as_ref().map(|(directory, _)| directory.clone()),
152            managed_worktree: None,
153            target_template_id: raw_project.map_or(target_id, |(_, raw_target_id)| raw_target_id),
154            resource_allocation: None,
155            additional_mounts: Vec::new(),
156            state: SessionState::Stopped,
157            target: None,
158            native_session_id: Some(native_session_id.to_owned()),
159            acp_session_title: None,
160            session_title_override,
161            created_at: timestamp.clone(),
162            updated_at: timestamp,
163            viewed_through_event_ordinal: 0,
164            draft_input: String::new(),
165            last_error: None,
166            last_checkpoint_error: None,
167            checkpoint: Some(checkpoint),
168        },
169    );
170    Ok(ImportedClaudeSession {
171        session_id,
172        native_session_id: native_session_id.to_owned(),
173        source_jsonl: source_path.to_path_buf(),
174        source_cwd: transcript.cwd.clone(),
175        bundle_id: bundle_id.to_owned(),
176        archive_path,
177    })
178}
179
180pub(super) fn default_import_target_id(config: &Config) -> String {
181    config
182        .targets
183        .get_key_value("podman")
184        .map(|(id, _)| id)
185        .or_else(|| {
186            config.targets.iter().find_map(|(id, target)| {
187                matches!(
188                    target,
189                    TargetTemplate::LocalPodman { .. }
190                        | TargetTemplate::LocalDocker { .. }
191                        | TargetTemplate::SshPodman { .. }
192                        | TargetTemplate::SshDocker { .. }
193                )
194                .then_some(id)
195            })
196        })
197        .or_else(|| config.targets.keys().next())
198        .cloned()
199        .unwrap_or_else(|| "import".into())
200}
201
202/// Target that hosts raw project sessions on this machine.
203pub(super) fn raw_import_target_id(config: &Config) -> Option<String> {
204    let local_bare = |template: &TargetTemplate| matches!(template, TargetTemplate::LocalBare);
205    config
206        .targets
207        .get_key_value("localhost")
208        .filter(|(_, template)| local_bare(template))
209        .map(|(id, _)| id.clone())
210        .or_else(|| {
211            config
212                .targets
213                .iter()
214                .find_map(|(id, template)| local_bare(template).then(|| id.clone()))
215        })
216}
217
218/// A session that only wrote to its own repository can keep working in that
219/// directory, so import it as a raw project session instead of a bundle
220/// session. `session_edit_targets` always records the cwd root, so a single
221/// durable root is that root.
222pub fn raw_project_import(
223    config: &Config,
224    targets: &SessionEditTargets,
225) -> Option<(PathBuf, String)> {
226    let [cwd_root] = targets.git_roots.as_slice() else {
227        return None;
228    };
229    Some((cwd_root.clone(), raw_import_target_id(config)?))
230}
231
232pub(super) fn collect_local_repositories(
233    bundle: &ProjectBundle,
234    detected_roots: &[PathBuf],
235    isolated: bool,
236    control: Option<&ImportControl<'_>>,
237) -> Result<Vec<mj_checkpoint::archive::RepositorySnapshot>> {
238    let detected = detected_roots
239        .iter()
240        .map(|root| Ok((root_identity(root)?, root.clone())))
241        .collect::<Result<BTreeMap<_, _>>>()?;
242    let repository_paths = bundle
243        .repositories
244        .iter()
245        .map(|repository| {
246            // A local source remains identified by its configured path even
247            // after its checkout gains a network origin. GitHub-origin
248            // detection is still used for configured network sources.
249            let path = if let Some(configured_path) = repository.local.as_ref() {
250                let configured_path =
251                    fs::canonicalize(configured_path).unwrap_or_else(|_| configured_path.clone());
252                detected_roots
253                    .iter()
254                    .find(|root| {
255                        fs::canonicalize(root).unwrap_or_else(|_| (*root).clone())
256                            == configured_path
257                    })
258                    .cloned()
259            } else {
260                let identity = configured_repository_identity(repository).with_context(|| {
261                    format!("repository {:?} has no usable source", repository.id)
262                })?;
263                detected.get(&identity).cloned()
264            };
265            let path = path.with_context(|| {
266                format!(
267                    "repository {:?} was not detected in the native session",
268                    repository.id
269                )
270            })?;
271            Ok((repository.id.clone(), path))
272        })
273        .collect::<Result<BTreeMap<_, _>>>()?;
274    let git = SystemGit;
275    let repository_count = bundle.repositories.len();
276    bundle
277        .repositories
278        // Indexed parallel iteration keeps repository and manifest order
279        // identical to the configured bundle.
280        .par_iter()
281        .enumerate()
282        .map(|(index, repository)| {
283            if let Some(control) = control {
284                control.report(ImportArchiveProgress::Repository {
285                    current: index + 1,
286                    total: repository_count,
287                    id: repository.id.clone(),
288                })?;
289            }
290            let path = repository_paths
291                .get(&repository.id)
292                .expect("repository paths cover the validated bundle")
293                .clone();
294            ensure!(
295                path.is_dir(),
296                "local repository {:?} is missing at {}",
297                repository.id,
298                path.display()
299            );
300            let source = isolated
301                .then(|| {
302                    resolve_repository(repository, &ProcessExecutor)
303                        .with_context(|| format!("resolve network source for {:?}", repository.id))
304                })
305                .transpose()?;
306            // Isolated imports restore the native session's committed work on
307            // top of the source's available network baseline. Raw imports
308            // continue to use the live local checkout, including repositories
309            // without any remote.
310            let history = if isolated {
311                GitHistoryMode::DeltaFrom(import_delta_base(
312                    &path,
313                    &source.as_ref().expect("isolated source resolved").fetch_url,
314                )?)
315            } else {
316                GitHistoryMode::NoBundle
317            };
318            let origin_override = if let Some(source) = &source {
319                Some(source.fetch_url.clone())
320            } else {
321                Some(path.to_string_lossy().into_owned())
322            };
323            let mut snapshot = collect_git_snapshot_with_progress(
324                &git,
325                &path,
326                &GitCollectionSpec {
327                    id: repository.id.clone(),
328                    relative_destination: repository.destination.clone(),
329                    history,
330                    origin_override,
331                },
332                control.is_none_or(|control| control.include_untracked),
333                &|progress| {
334                    let Some(control) = control else {
335                        return Ok(());
336                    };
337                    match progress {
338                        GitSnapshotProgress::UntrackedFile {
339                            current,
340                            total,
341                            path,
342                        } => control.report(ImportArchiveProgress::UntrackedFile {
343                            repository_id: repository.id.clone(),
344                            current,
345                            total,
346                            path,
347                        }),
348                    }
349                },
350            )
351            .with_context(|| format!("collect local repository {:?}", repository.id))?;
352            if let Some(source) = source {
353                snapshot.metadata.push_urls = source
354                    .push_urls
355                    .iter()
356                    .map(|url| mj_checkpoint::archive::redact_origin_credentials(url))
357                    .collect::<Result<Vec<_>>>()?;
358                snapshot.metadata.remote_workspace = true;
359            } else {
360                snapshot.metadata.push_urls.clear();
361            }
362            Ok(snapshot)
363        })
364        .collect()
365}
366
367pub(super) fn canonical_import_session(
368    session_id: &str,
369    events: &[SequencedEvent],
370    source_path: &Path,
371) -> Result<mj_checkpoint::archive::CanonicalSessionSnapshot> {
372    let mut events = events.to_vec();
373    finalize_import_event_times(&mut events, source_path)?;
374    let mut materialized =
375        mj_transcript::projection::imported_materialized_session(session_id, &events);
376    materialized.session_title = harness_session_title(&events);
377    if let Some(last_activity_at_ms) = events.iter().filter_map(|event| event.recorded_at_ms).max()
378    {
379        materialized.last_activity_at_ms = Some(
380            materialized
381                .last_activity_at_ms
382                .map_or(last_activity_at_ms, |current| {
383                    current.max(last_activity_at_ms)
384                }),
385        );
386    }
387    canonical_session_from_materialized(&materialized)
388}
389
390pub(super) fn default_profile(config: &Config, harness: HarnessKind, home: &Path) -> String {
391    let source = fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf());
392    config
393        .enabled_profiles()
394        .find(|(_, profile)| {
395            profile.kind == harness
396                && fs::canonicalize(&profile.home).unwrap_or_else(|_| profile.home.clone())
397                    == source
398        })
399        .or_else(|| {
400            config
401                .enabled_profiles()
402                .find(|(_, profile)| profile.kind == harness)
403        })
404        .map(|(id, _)| id.to_owned())
405        .unwrap_or_else(|| format!("{}-import", harness.id()))
406}
407
408pub(super) fn import_profile_id(
409    config: &Config,
410    requested: Option<&str>,
411    harness: HarnessKind,
412    home: &Path,
413) -> Result<String> {
414    let Some(requested) = requested else {
415        return Ok(default_profile(config, harness, home));
416    };
417    let profile = config
418        .profiles
419        .get(requested)
420        .with_context(|| format!("unknown import profile {requested:?}"))?;
421    ensure!(profile.enabled, "import profile {requested:?} is disabled");
422    ensure!(
423        profile.kind == harness,
424        "import profile {requested:?} does not use {harness:?}"
425    );
426    Ok(requested.to_owned())
427}
428
429/// The upstream revision an imported repository deltas from. A repository
430/// without remote-tracking refs cannot tell us which ancestry a newly
431/// provisioned clone has, and Hel never bundles full history, so it fails here.
432pub(super) fn import_delta_base(path: &Path, fetch_url: &str) -> Result<String> {
433    let remotes = git_optional_text(path, ["remote"])?.unwrap_or_default();
434    let upstream_ref = git_optional_text(
435        path,
436        [
437            "rev-parse",
438            "--symbolic-full-name",
439            "--verify",
440            "--quiet",
441            "@{upstream}",
442        ],
443    )?;
444    for remote in remotes.lines() {
445        let Some(url) = git_optional_text(path, ["remote", "get-url", remote])? else {
446            continue;
447        };
448        let same_source = url == fetch_url
449            || mj_core::state::ProjectSourceIdentity::git_remote(&url).is_some_and(|identity| {
450                Some(identity) == mj_core::state::ProjectSourceIdentity::git_remote(fetch_url)
451            });
452        if !same_source {
453            continue;
454        }
455        let prefix = format!("refs/remotes/{remote}/");
456        let revision = upstream_ref
457            .as_deref()
458            .filter(|reference| reference.starts_with(&prefix))
459            .map(str::to_owned)
460            .unwrap_or_else(|| format!("{prefix}HEAD"));
461        if let Some(base) =
462            git_optional_text(path, ["rev-parse", "--verify", "--quiet", &revision])?
463        {
464            return Ok(base);
465        }
466    }
467    bail!(
468        "repository {} has no remote-tracking refs to import against for its selected network source; fetch its remote first",
469        path.display()
470    )
471}
472
473pub(super) fn git_optional_text<const N: usize>(
474    cwd: &Path,
475    arguments: [&str; N],
476) -> Result<Option<String>> {
477    let output = Command::new("git")
478        .args(arguments)
479        .current_dir(cwd)
480        .output()
481        .with_context(|| format!("start git in {}", cwd.display()))?;
482    if !output.status.success() {
483        return Ok(None);
484    }
485    let text = String::from_utf8(output.stdout).context("decode Git output")?;
486    Ok((!text.trim().is_empty()).then(|| text.trim().to_owned()))
487}
488
489pub(super) fn timestamp() -> String {
490    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
491}
492
493pub fn persist_imported_session_locally(session: &SessionRecord) -> Result<()> {
494    crate::database::save_session(session)?;
495    let checkpoint = session
496        .checkpoint
497        .as_ref()
498        .context("imported session has no checkpoint")?;
499    let canonical = mj_checkpoint::archive::verify_archive_streaming(&checkpoint.archive_path)?
500        .canonical_session;
501    let materialized = mj_transcript::projection::materialized_session_from_canonical(
502        session.id.clone(),
503        &canonical,
504    )?;
505    crate::database::save_materialized_session(&materialized)
506}