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            target_runtime: None,
136            launch_base: None,
137            launch_branch: None,
138            publication: None,
139            build_cache: None,
140            mjolnir_subagents: None,
141            // An imported history is a new session: when it is resumed into a
142            // container it gets its own workspace, like any session created
143            // now.
144            container_workspace: Some(mj_core::targets::new_container_workspace(&session_id)?),
145            create_managed_worktree: None,
146            workspace_id: mj_core::workspace::DEFAULT_WORKSPACE_ID.to_owned(),
147            archived: false,
148            container_cpus: None,
149            container_memory: None,
150            id: session_id.clone(),
151            title,
152            harness_kind: harness,
153            last_profile: profile_id,
154            bundle_id: bundle_id.to_owned(),
155            project_directory: raw_project.as_ref().map(|(directory, _)| directory.clone()),
156            managed_worktree: None,
157            target_template_id: raw_project.map_or(target_id, |(_, raw_target_id)| raw_target_id),
158            resource_allocation: None,
159            additional_mounts: Vec::new(),
160            state: SessionState::Stopped,
161            target: None,
162            native_session_id: Some(native_session_id.to_owned()),
163            acp_session_title: None,
164            session_title_override,
165            created_at: timestamp.clone(),
166            updated_at: timestamp,
167            viewed_through_event_ordinal: 0,
168            draft_input: String::new(),
169            last_error: None,
170            last_checkpoint_error: None,
171            checkpoint: Some(checkpoint),
172        },
173    );
174    Ok(ImportedClaudeSession {
175        session_id,
176        native_session_id: native_session_id.to_owned(),
177        source_jsonl: source_path.to_path_buf(),
178        source_cwd: transcript.cwd.clone(),
179        bundle_id: bundle_id.to_owned(),
180        archive_path,
181    })
182}
183
184pub(super) fn default_import_target_id(config: &Config) -> String {
185    config
186        .targets
187        .get_key_value("podman")
188        .map(|(id, _)| id)
189        .or_else(|| {
190            config.targets.iter().find_map(|(id, target)| {
191                matches!(
192                    target,
193                    TargetTemplate::LocalPodman { .. }
194                        | TargetTemplate::LocalDocker { .. }
195                        | TargetTemplate::SshPodman { .. }
196                        | TargetTemplate::SshDocker { .. }
197                )
198                .then_some(id)
199            })
200        })
201        .or_else(|| config.targets.keys().next())
202        .cloned()
203        .unwrap_or_else(|| "import".into())
204}
205
206/// Target that hosts raw project sessions on this machine.
207pub(super) fn raw_import_target_id(config: &Config) -> Option<String> {
208    let local_bare = |template: &TargetTemplate| matches!(template, TargetTemplate::LocalBare);
209    config
210        .targets
211        .get_key_value("localhost")
212        .filter(|(_, template)| local_bare(template))
213        .map(|(id, _)| id.clone())
214        .or_else(|| {
215            config
216                .targets
217                .iter()
218                .find_map(|(id, template)| local_bare(template).then(|| id.clone()))
219        })
220}
221
222/// A session that only wrote to its own repository can keep working in that
223/// directory, so import it as a raw project session instead of a bundle
224/// session. `session_edit_targets` always records the cwd root, so a single
225/// durable root is that root.
226pub fn raw_project_import(
227    config: &Config,
228    targets: &SessionEditTargets,
229) -> Option<(PathBuf, String)> {
230    let [cwd_root] = targets.git_roots.as_slice() else {
231        return None;
232    };
233    Some((cwd_root.clone(), raw_import_target_id(config)?))
234}
235
236pub(super) fn collect_local_repositories(
237    bundle: &ProjectBundle,
238    detected_roots: &[PathBuf],
239    isolated: bool,
240    control: Option<&ImportControl<'_>>,
241) -> Result<Vec<mj_checkpoint::archive::RepositorySnapshot>> {
242    let detected = detected_roots
243        .iter()
244        .map(|root| Ok((root_identity(root)?, root.clone())))
245        .collect::<Result<BTreeMap<_, _>>>()?;
246    let repository_paths = bundle
247        .repositories
248        .iter()
249        .map(|repository| {
250            // A local source remains identified by its configured path even
251            // after its checkout gains a network origin. GitHub-origin
252            // detection is still used for configured network sources.
253            let path = if let Some(configured_path) = repository.local.as_ref() {
254                let configured_path =
255                    fs::canonicalize(configured_path).unwrap_or_else(|_| configured_path.clone());
256                detected_roots
257                    .iter()
258                    .find(|root| {
259                        fs::canonicalize(root).unwrap_or_else(|_| (*root).clone())
260                            == configured_path
261                    })
262                    .cloned()
263            } else {
264                let identity = configured_repository_identity(repository).with_context(|| {
265                    format!("repository {:?} has no usable source", repository.id)
266                })?;
267                detected.get(&identity).cloned()
268            };
269            let path = path.with_context(|| {
270                format!(
271                    "repository {:?} was not detected in the native session",
272                    repository.id
273                )
274            })?;
275            Ok((repository.id.clone(), path))
276        })
277        .collect::<Result<BTreeMap<_, _>>>()?;
278    let git = SystemGit;
279    let repository_count = bundle.repositories.len();
280    bundle
281        .repositories
282        // Indexed parallel iteration keeps repository and manifest order
283        // identical to the configured bundle.
284        .par_iter()
285        .enumerate()
286        .map(|(index, repository)| {
287            if let Some(control) = control {
288                control.report(ImportArchiveProgress::Repository {
289                    current: index + 1,
290                    total: repository_count,
291                    id: repository.id.clone(),
292                })?;
293            }
294            let path = repository_paths
295                .get(&repository.id)
296                .expect("repository paths cover the validated bundle")
297                .clone();
298            ensure!(
299                path.is_dir(),
300                "local repository {:?} is missing at {}",
301                repository.id,
302                path.display()
303            );
304            let source = isolated
305                .then(|| {
306                    resolve_repository(repository, &ProcessExecutor)
307                        .with_context(|| format!("resolve network source for {:?}", repository.id))
308                })
309                .transpose()?;
310            // Isolated imports restore the native session's committed work on
311            // top of the source's available network baseline. Raw imports
312            // continue to use the live local checkout, including repositories
313            // without any remote.
314            let history = if isolated {
315                GitHistoryMode::DeltaFrom(import_delta_base(
316                    &path,
317                    &source.as_ref().expect("isolated source resolved").fetch_url,
318                )?)
319            } else {
320                GitHistoryMode::NoBundle
321            };
322            let origin_override = if let Some(source) = &source {
323                Some(source.fetch_url.clone())
324            } else {
325                Some(path.to_string_lossy().into_owned())
326            };
327            let mut snapshot = collect_git_snapshot_with_progress(
328                &git,
329                &path,
330                &GitCollectionSpec {
331                    id: repository.id.clone(),
332                    relative_destination: repository.destination.clone(),
333                    history,
334                    origin_override,
335                },
336                control.is_none_or(|control| control.include_untracked),
337                &|progress| {
338                    let Some(control) = control else {
339                        return Ok(());
340                    };
341                    match progress {
342                        GitSnapshotProgress::UntrackedFile {
343                            current,
344                            total,
345                            path,
346                        } => control.report(ImportArchiveProgress::UntrackedFile {
347                            repository_id: repository.id.clone(),
348                            current,
349                            total,
350                            path,
351                        }),
352                    }
353                },
354            )
355            .with_context(|| format!("collect local repository {:?}", repository.id))?;
356            if let Some(source) = source {
357                snapshot.metadata.push_urls = source
358                    .push_urls
359                    .iter()
360                    .map(|url| mj_checkpoint::archive::redact_origin_credentials(url))
361                    .collect::<Result<Vec<_>>>()?;
362                snapshot.metadata.remote_workspace = true;
363            } else {
364                snapshot.metadata.push_urls.clear();
365            }
366            Ok(snapshot)
367        })
368        .collect()
369}
370
371pub(super) fn canonical_import_session(
372    session_id: &str,
373    events: &[SequencedEvent],
374    source_path: &Path,
375) -> Result<mj_checkpoint::archive::CanonicalSessionSnapshot> {
376    let mut events = events.to_vec();
377    finalize_import_event_times(&mut events, source_path)?;
378    let mut materialized =
379        mj_transcript::projection::imported_materialized_session(session_id, &events);
380    materialized.session_title = harness_session_title(&events);
381    if let Some(last_activity_at_ms) = events.iter().filter_map(|event| event.recorded_at_ms).max()
382    {
383        materialized.last_activity_at_ms = Some(
384            materialized
385                .last_activity_at_ms
386                .map_or(last_activity_at_ms, |current| {
387                    current.max(last_activity_at_ms)
388                }),
389        );
390    }
391    canonical_session_from_materialized(&materialized)
392}
393
394pub(super) fn default_profile(config: &Config, harness: HarnessKind, home: &Path) -> String {
395    let source = fs::canonicalize(home).unwrap_or_else(|_| home.to_path_buf());
396    config
397        .enabled_profiles()
398        .find(|(_, profile)| {
399            profile.kind == harness
400                && fs::canonicalize(&profile.home).unwrap_or_else(|_| profile.home.clone())
401                    == source
402        })
403        .or_else(|| {
404            config
405                .enabled_profiles()
406                .find(|(_, profile)| profile.kind == harness)
407        })
408        .map(|(id, _)| id.to_owned())
409        .unwrap_or_else(|| format!("{}-import", harness.id()))
410}
411
412pub(super) fn import_profile_id(
413    config: &Config,
414    requested: Option<&str>,
415    harness: HarnessKind,
416    home: &Path,
417) -> Result<String> {
418    let Some(requested) = requested else {
419        return Ok(default_profile(config, harness, home));
420    };
421    let profile = config
422        .profiles
423        .get(requested)
424        .with_context(|| format!("unknown import profile {requested:?}"))?;
425    ensure!(profile.enabled, "import profile {requested:?} is disabled");
426    ensure!(
427        profile.kind == harness,
428        "import profile {requested:?} does not use {harness:?}"
429    );
430    Ok(requested.to_owned())
431}
432
433/// The upstream revision an imported repository deltas from. A repository
434/// without remote-tracking refs cannot tell us which ancestry a newly
435/// provisioned clone has, and Hel never bundles full history, so it fails here.
436pub(super) fn import_delta_base(path: &Path, fetch_url: &str) -> Result<String> {
437    let remotes = git_optional_text(path, ["remote"])?.unwrap_or_default();
438    let upstream_ref = git_optional_text(
439        path,
440        [
441            "rev-parse",
442            "--symbolic-full-name",
443            "--verify",
444            "--quiet",
445            "@{upstream}",
446        ],
447    )?;
448    for remote in remotes.lines() {
449        let Some(url) = git_optional_text(path, ["remote", "get-url", remote])? else {
450            continue;
451        };
452        let same_source = url == fetch_url
453            || mj_core::state::ProjectSourceIdentity::git_remote(&url).is_some_and(|identity| {
454                Some(identity) == mj_core::state::ProjectSourceIdentity::git_remote(fetch_url)
455            });
456        if !same_source {
457            continue;
458        }
459        let prefix = format!("refs/remotes/{remote}/");
460        let revision = upstream_ref
461            .as_deref()
462            .filter(|reference| reference.starts_with(&prefix))
463            .map(str::to_owned)
464            .unwrap_or_else(|| format!("{prefix}HEAD"));
465        if let Some(base) =
466            git_optional_text(path, ["rev-parse", "--verify", "--quiet", &revision])?
467        {
468            return Ok(base);
469        }
470    }
471    bail!(
472        "repository {} has no remote-tracking refs to import against for its selected network source; fetch its remote first",
473        path.display()
474    )
475}
476
477pub(super) fn git_optional_text<const N: usize>(
478    cwd: &Path,
479    arguments: [&str; N],
480) -> Result<Option<String>> {
481    let output = Command::new("git")
482        .args(arguments)
483        .current_dir(cwd)
484        .output()
485        .with_context(|| format!("start git in {}", cwd.display()))?;
486    if !output.status.success() {
487        return Ok(None);
488    }
489    let text = String::from_utf8(output.stdout).context("decode Git output")?;
490    Ok((!text.trim().is_empty()).then(|| text.trim().to_owned()))
491}
492
493pub(super) fn timestamp() -> String {
494    Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
495}
496
497pub fn persist_imported_session_locally(session: &SessionRecord) -> Result<()> {
498    crate::database::save_session(session)?;
499    let checkpoint = session
500        .checkpoint
501        .as_ref()
502        .context("imported session has no checkpoint")?;
503    let canonical = mj_checkpoint::archive::verify_archive_streaming(&checkpoint.archive_path)?
504        .canonical_session;
505    let materialized = mj_transcript::projection::materialized_session_from_canonical(
506        session.id.clone(),
507        &canonical,
508    )?;
509    crate::database::save_materialized_session(&materialized)
510}