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