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