Skip to main content

mj_controller/hel_controller/
move_session.rs

1//! One recoverable stop/restore operation, independent of its initiating viewer.
2
3#[cfg(test)]
4mod tests;
5
6use anyhow::{Context, Result, bail, ensure};
7use sha2::{Digest, Sha256};
8
9use super::{Controller, SessionResumeOptions, now};
10
11fn mutation_holds() -> &'static std::sync::Mutex<std::collections::BTreeSet<String>> {
12    static HOLDS: std::sync::OnceLock<std::sync::Mutex<std::collections::BTreeSet<String>>> =
13        std::sync::OnceLock::new();
14    HOLDS.get_or_init(Default::default)
15}
16
17pub fn move_owns_session(session_id: &str) -> bool {
18    move_has_pending_queue(session_id)
19        || mutation_holds()
20            .lock()
21            .unwrap_or_else(std::sync::PoisonError::into_inner)
22            .contains(session_id)
23}
24
25fn queue_holds() -> &'static std::sync::Mutex<std::collections::BTreeSet<String>> {
26    static HOLDS: std::sync::OnceLock<std::sync::Mutex<std::collections::BTreeSet<String>>> =
27        std::sync::OnceLock::new();
28    HOLDS.get_or_init(Default::default)
29}
30
31pub fn move_has_pending_queue(session_id: &str) -> bool {
32    queue_holds()
33        .lock()
34        .unwrap_or_else(std::sync::PoisonError::into_inner)
35        .contains(session_id)
36}
37
38pub fn release_move_queue_hold(session_id: &str) {
39    queue_holds()
40        .lock()
41        .unwrap_or_else(std::sync::PoisonError::into_inner)
42        .remove(session_id);
43}
44
45pub fn restore_move_queue_hold(operation: &MoveOperation) {
46    let mut holds = queue_holds()
47        .lock()
48        .unwrap_or_else(std::sync::PoisonError::into_inner);
49    if operation.queue_admission_started && !operation.queue_admission_finished {
50        holds.insert(operation.selection.session_id.clone());
51    } else {
52        holds.remove(&operation.selection.session_id);
53    }
54}
55
56pub struct MoveMutationGuard(String);
57
58impl MoveMutationGuard {
59    pub fn reserve(session_id: &str) -> Result<Self> {
60        ensure!(
61            mutation_holds()
62                .lock()
63                .unwrap_or_else(std::sync::PoisonError::into_inner)
64                .insert(session_id.to_owned()),
65            "session already has a move owner"
66        );
67        Ok(Self(session_id.to_owned()))
68    }
69}
70
71impl Drop for MoveMutationGuard {
72    fn drop(&mut self) {
73        mutation_holds()
74            .lock()
75            .unwrap_or_else(std::sync::PoisonError::into_inner)
76            .remove(&self.0);
77    }
78}
79
80pub(crate) fn move_refuses_command(session_id: &str, command: &RelayCommand) -> bool {
81    move_owns_session(session_id)
82        && matches!(
83            command,
84            RelayCommand::Prompt { .. }
85                | RelayCommand::SetConfig { .. }
86                | RelayCommand::SetSessionMode { .. }
87                | RelayCommand::RunUserShell { .. }
88                | RelayCommand::CancelUserShell { .. }
89                | RelayCommand::Cancel
90                | RelayCommand::RemoveQueuedPrompt { .. }
91                | RelayCommand::ClearQueuedPrompts
92        )
93}
94use crate::hel_session_manager::{SessionManagerControl, StandaloneSession, new_command_id};
95use hel::hel_archive::{CanonicalQueuedCommandKind, verify_archive_streaming};
96use hel::hel_state::{MoveOperation, MovePhase, ResumeQueueDisposition, SessionState};
97pub use hel::hel_state::{MoveOutcome, MovePreparation, MoveSelection, MoveSessionRequest};
98use hel::hel_targets::{CommandExecutor, ProvisionStage, ProvisionStageGuard};
99use hel::hel_worker::RelayCommand;
100
101fn digest(value: &impl serde::Serialize) -> Result<String> {
102    Ok(format!("{:x}", Sha256::digest(serde_json::to_vec(value)?)))
103}
104
105struct MovePhaseTimer<'a> {
106    session_id: &'a str,
107    phase: &'static str,
108    started: std::time::Instant,
109}
110
111impl<'a> MovePhaseTimer<'a> {
112    fn new(session_id: &'a str, phase: &'static str) -> Self {
113        Self {
114            session_id,
115            phase,
116            started: std::time::Instant::now(),
117        }
118    }
119}
120
121impl Drop for MovePhaseTimer<'_> {
122    fn drop(&mut self) {
123        tracing::info!(
124            session_id = self.session_id,
125            phase = self.phase,
126            elapsed_ms = self.started.elapsed().as_millis() as u64,
127            "move phase finished"
128        );
129    }
130}
131
132impl Controller {
133    fn validate_move_destination_paths(
134        &self,
135        source: &hel::hel_state::SessionRecord,
136        target_id: &str,
137        executor: &(impl CommandExecutor + Sync),
138    ) -> Result<()> {
139        use super::worktree::ResumePlan;
140        match super::worktree::resume_compatibility(source, &self.config, target_id)
141            .map_err(anyhow::Error::msg)?
142        {
143            ResumePlan::RawToWorkspace => {
144                super::worktree::plan_raw_to_workspace(source, &self.config, executor)?;
145            }
146            ResumePlan::WorkspaceToRaw => {
147                self.plan_workspace_to_raw(source, target_id, executor)?;
148            }
149            ResumePlan::InPlace if source.managed_worktree.is_none() => {
150                if let Some(path) = &source.project_directory {
151                    self.validate_project_directory(target_id, path, executor)?;
152                }
153            }
154            ResumePlan::InPlace => {}
155        }
156        Ok(())
157    }
158    fn move_confirmation(
159        &self,
160        selection: &MoveSelection,
161    ) -> Result<(bool, Vec<hel::hel_state::MaterializedQueuedPrompt>, String)> {
162        let source = self
163            .state
164            .sessions
165            .get(&selection.session_id)
166            .context("unknown move session")?;
167        let (mut active, mut queued) = hel::hel_database::move_pending_work(&source.id)?;
168        if let Some(operation) = hel::hel_database::load_move_operation(&source.id)?
169            && operation.queue_admission_started
170            && !operation.queue_admission_finished
171        {
172            ensure!(
173                operation.selection == *selection,
174                "queue admission is incomplete on the live destination; retry that move before selecting another destination"
175            );
176            let checkpoint = operation
177                .checkpoint
178                .as_ref()
179                .context("retained queue checkpoint is missing")?;
180            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
181            ensure!(
182                verified.archive_sha256 == checkpoint.sha256
183                    && verified.manifest.session.id == source.id,
184                "retained move checkpoint verification failed"
185            );
186            queued = verified
187                .canonical_session
188                .queued_prompts
189                .into_iter()
190                .map(|entry| hel::hel_state::MaterializedQueuedPrompt {
191                    command_id: entry.command_id,
192                    kind: match entry.kind {
193                        CanonicalQueuedCommandKind::Prompt => {
194                            hel::hel_state::QueuedCommandKind::Prompt
195                        }
196                        CanonicalQueuedCommandKind::SetConfig { key, value } => {
197                            hel::hel_state::QueuedCommandKind::SetConfig { key, value }
198                        }
199                    },
200                    content: entry.content,
201                    queued_at_ms: entry.queued_at_ms,
202                })
203                .collect();
204            active = false;
205        }
206        let fingerprint = digest(&(
207            &source.last_profile,
208            &source.target_template_id,
209            &source.target,
210            &source.native_session_id,
211            &source.resource_allocation,
212            &source.additional_mounts,
213            &source.container_cpus,
214            &source.container_memory,
215            selection,
216            self.move_configuration_fingerprint(selection)?,
217            &queued,
218        ))?;
219        Ok((active, queued, fingerprint))
220    }
221    fn move_configuration_fingerprint(&self, selection: &MoveSelection) -> Result<String> {
222        let profile = self
223            .config
224            .profiles
225            .get(
226                selection
227                    .profile_id
228                    .as_deref()
229                    .context("move profile is unresolved")?,
230            )
231            .context("move profile no longer exists")?;
232        let target = self
233            .config
234            .targets
235            .get(
236                selection
237                    .target_template_id
238                    .as_deref()
239                    .context("move target is unresolved")?,
240            )
241            .context("move target no longer exists")?;
242        // Only a digest crosses IPC or enters the move record. Configuration
243        // may contain credential-bearing values and must never be copied there.
244        let source = self
245            .state
246            .sessions
247            .get(&selection.session_id)
248            .context("unknown move session")?;
249        digest(&(
250            profile,
251            target,
252            &self.config.bundles,
253            self.config.targets.get(&source.target_template_id),
254            self.config.profiles.get(&source.last_profile),
255        ))
256    }
257
258    pub async fn prepare_move_session_controlled(
259        &self,
260        mut selection: MoveSelection,
261        executor: &(impl CommandExecutor + Sync),
262    ) -> Result<MovePreparation> {
263        ensure!(
264            selection.profile_id.is_some() || selection.target_template_id.is_some(),
265            "move requires a target or profile selection"
266        );
267        let source = self
268            .state
269            .sessions
270            .get(&selection.session_id)
271            .context("unknown session")?;
272        let previous = hel::hel_database::load_move_operation(&source.id)?;
273        let retry = previous.as_ref().is_some_and(|op| {
274            !matches!(op.phase, MovePhase::Completed) && source.checkpoint.is_some()
275        });
276        ensure!(
277            matches!(
278                source.state,
279                SessionState::Running | SessionState::Disconnected
280            ) || retry,
281            "only active sessions can move; use Resume for a stopped or lost session"
282        );
283        selection
284            .profile_id
285            .get_or_insert_with(|| source.last_profile.clone());
286        selection
287            .target_template_id
288            .get_or_insert_with(|| source.target_template_id.clone());
289        selection
290            .additional_mounts
291            .get_or_insert_with(|| source.additional_mounts.clone());
292        ensure!(
293            !selection.clear_resource_allocation || selection.resource_allocation.is_none(),
294            "select resource allocation or explicitly clear it, not both"
295        );
296        if !selection.clear_resource_allocation {
297            selection.resource_allocation = selection
298                .resource_allocation
299                .or_else(|| source.resource_allocation.clone());
300        }
301        let profile_id = selection.profile_id.as_deref().unwrap();
302        let target_id = selection.target_template_id.as_deref().unwrap();
303        let profile = self
304            .config
305            .profiles
306            .get(profile_id)
307            .context("unknown destination profile")?;
308        let target = self
309            .config
310            .targets
311            .get(target_id)
312            .context("unknown destination target")?;
313        self.validate_muse_resume_destination(source, profile.kind, target_id)?;
314        super::worktree::resume_compatibility(source, &self.config, target_id)
315            .map_err(anyhow::Error::msg)?;
316        super::backend::validate_resource_allocation(
317            target,
318            selection.resource_allocation.as_ref(),
319        )?;
320        let mounts = selection.additional_mounts.as_deref().unwrap_or_default();
321        ensure!(
322            profile.kind != hel::hel_config::HarnessKind::Muse || mounts.is_empty(),
323            "Muse Code ACP supports one workspace root; attached directories are unsupported"
324        );
325        ensure!(
326            mounts.is_empty() || hel::hel_config::mount_history_host(target).is_some(),
327            "attached resources are unsupported for this target; select compatible resources explicitly"
328        );
329        hel::hel_targets::validate_additional_mounts(mounts)?;
330        for mount in mounts {
331            self.validate_mount_source(target_id, &mount.source, executor)?;
332        }
333        self.validate_move_destination_paths(source, target_id, executor)?;
334        ensure!(
335            profile.home.is_dir(),
336            "destination profile home is unavailable; configure the profile before moving"
337        );
338        super::worker_binary::preflight_worker_binary(target)?;
339        super::backend::preflight_target(target, executor)?;
340        let source_harness = previous
341            .as_ref()
342            .filter(|operation| {
343                !operation.queue_admission_started && operation.phase != MovePhase::Completed
344            })
345            .and_then(|operation| operation.recovery_session.as_ref())
346            .map_or(source.harness_kind, |record| record.harness_kind);
347        let cross_harness = profile.kind != source_harness;
348        if cross_harness {
349            let cancel = tokio_util::sync::CancellationToken::new();
350            let resolve =
351                crate::hel_utility_llm::UtilityLlmRuntime::shared().resolve(&self.config, &cancel);
352            tokio::pin!(resolve);
353            loop {
354                tokio::select! {
355                    result = &mut resolve => { result.context("cross-harness move needs an available utility model")?; break; }
356                    _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {
357                        if executor.cancellation_requested() { cancel.cancel(); bail!("move preparation cancelled"); }
358                    }
359                }
360            }
361        }
362        let (active, mut queued_commands, fingerprint) = self.move_confirmation(&selection)?;
363        // Confirmation is an inspector, not transport for attachment bytes.
364        // Replay always reads the verified archive after destination readiness.
365        for entry in &mut queued_commands {
366            for content in &mut entry.content {
367                if content.get("type").and_then(serde_json::Value::as_str) == Some("image") {
368                    let mime = content
369                        .get("mimeType")
370                        .and_then(serde_json::Value::as_str)
371                        .unwrap_or("image");
372                    *content = serde_json::json!({"type":"text", "text":format!("[Image attachment: {mime}]")});
373                }
374            }
375        }
376        let operation_id = previous
377            .as_ref()
378            .filter(|operation| {
379                operation.selection == selection
380                    && operation.phase != MovePhase::Completed
381                    && operation.checkpoint.is_some()
382            })
383            .map(|operation| operation.operation_id.clone())
384            .unwrap_or(new_command_id("move")?);
385        Ok(MovePreparation {
386            selection,
387            source_profile_id: source.last_profile.clone(),
388            source_target_template_id: source.target_template_id.clone(),
389            cross_harness,
390            active,
391            queued_commands,
392            fingerprint,
393            operation_id,
394        })
395    }
396
397    /// Called with one daemon lifecycle and recovery reservation already held.
398    pub async fn move_session_managed_controlled(
399        &mut self,
400        request: MoveSessionRequest,
401        executor: &(impl CommandExecutor + Sync),
402        manager: &SessionManagerControl,
403    ) -> Result<MoveOutcome> {
404        let prepared = &request.preparation;
405        let id = prepared.selection.session_id.clone();
406        let started = std::time::Instant::now();
407        executor.notify_notice("Checking destination");
408        let checked = {
409            let _checking_destination =
410                ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
411            let mut checked = self
412                .prepare_move_session_controlled(prepared.selection.clone(), executor)
413                .await?;
414            // Destination checks can outlast a turn. Refresh confirmation from the
415            // relay immediately before interruption, while new submissions are held.
416            if matches!(
417                self.state.sessions[&id].state,
418                SessionState::Running | SessionState::Disconnected
419            ) {
420                let handle = manager
421                    .wait_for_session(&id, std::time::Duration::from_secs(5))
422                    .await?;
423                handle.sync_now().await?;
424                let (active, queue, fingerprint) = self.move_confirmation(&checked.selection)?;
425                checked.active = active
426                    || handle.view().snapshot.as_ref().is_some_and(|snapshot| {
427                        let mut operational = snapshot.operational.clone();
428                        operational.queued_prompts.clear();
429                        operational.checkpoint_barrier = None;
430                        !operational.is_quiet()
431                    });
432                checked.queued_commands = queue;
433                checked.fingerprint = fingerprint;
434            }
435            checked
436        };
437        ensure!(
438            checked.fingerprint == prepared.fingerprint,
439            "session, pending work, or destination configuration changed; prepare and confirm Move again"
440        );
441        let queue = request.queue.unwrap_or(ResumeQueueDisposition::Discard);
442        let source = self.state.sessions[&id].clone();
443        let old_operation = hel::hel_database::load_move_operation(&id)?;
444        let retry = old_operation.filter(|op| {
445            op.selection == prepared.selection
446                && op.phase != MovePhase::Completed
447                && op.checkpoint.is_some()
448        });
449        if retry.is_none()
450            && source.state == SessionState::Running
451            && source.last_profile == checked.selection.profile_id.as_deref().unwrap()
452            && source.target_template_id == checked.selection.target_template_id.as_deref().unwrap()
453            && Some(&source.additional_mounts) == checked.selection.additional_mounts.as_ref()
454            && source.resource_allocation == checked.selection.resource_allocation
455            && (!checked.selection.clear_resource_allocation
456                || (source.container_cpus.is_none() && source.container_memory.is_none()))
457        {
458            return Ok(outcome(
459                &prepared.operation_id,
460                &prepared.selection,
461                "unchanged",
462                None,
463                None,
464            ));
465        }
466        ensure!(
467            !checked.active || request.acknowledge_interruption,
468            "active work will be interrupted; confirm Move again with interruption acknowledgement"
469        );
470        ensure!(
471            checked.queued_commands.is_empty() || request.queue.is_some(),
472            "pending work requires an explicit queue choice: discard or start"
473        );
474        let timestamp = now();
475        let mut operation = match retry {
476            Some(mut op) => {
477                ensure!(
478                    !op.queue_admission_started || op.queue == queue,
479                    "queued work may already have run; retry with the original queue choice on the same destination"
480                );
481                hel::hel_database::clear_move_cancellation_for_retry(&id)?;
482                op.configuration_fingerprint =
483                    self.move_configuration_fingerprint(&checked.selection)?;
484                op.queue = queue;
485                op.cancellation_requested = false;
486                op.error = None;
487                op
488            }
489            None => MoveOperation {
490                operation_id: prepared.operation_id.clone(),
491                selection: checked.selection.clone(),
492                source_profile_id: source.last_profile.clone(),
493                source_target_template_id: source.target_template_id.clone(),
494                source_target: source.target.clone(),
495                source_native_session_id: source.native_session_id.clone(),
496                source_additional_mounts: source.additional_mounts.clone(),
497                source_resource_allocation: source.resource_allocation.clone(),
498                destination_target: None,
499                destination_native_session_id: None,
500                destination_store_id: None,
501                configuration_fingerprint: self
502                    .move_configuration_fingerprint(&checked.selection)?,
503                checkpoint: None,
504                recovery_session: None,
505                queue,
506                phase: MovePhase::Preparing,
507                queue_admission_started: false,
508                queue_admission_finished: false,
509                cancellation_requested: false,
510                created_at: timestamp.clone(),
511                updated_at: timestamp,
512                error: None,
513            },
514        };
515        hel::hel_database::save_move_operation(&operation)?;
516        tracing::info!(
517            session_id = id,
518            phase = "preflight",
519            elapsed_ms = started.elapsed().as_millis() as u64,
520            "move phase completed"
521        );
522        let result = self
523            .execute_move(&mut operation, Some(&checked), executor, manager)
524            .await;
525        self.finish_move_result(&mut operation, result, executor)
526    }
527
528    fn finish_move_result(
529        &self,
530        operation: &mut MoveOperation,
531        result: Result<()>,
532        executor: &impl CommandExecutor,
533    ) -> Result<MoveOutcome> {
534        let (status, error, recovery) = match result {
535            Ok(()) => {
536                operation.phase = MovePhase::Completed;
537                ("completed", None, None)
538            }
539            Err(error) => {
540                let cancelled =
541                    executor.cancellation_requested() || operation.cancellation_requested;
542                operation.phase = if cancelled {
543                    MovePhase::Cancelled
544                } else {
545                    MovePhase::Failed
546                };
547                operation.cancellation_requested = cancelled;
548                let recovery = if operation.queue_admission_started {
549                    "Destination is live; retry queue admission on this same destination. Already accepted work may have effects."
550                } else if self
551                    .state
552                    .sessions
553                    .get(&operation.selection.session_id)
554                    .is_some_and(|s| s.state == SessionState::Stopped)
555                {
556                    "Session is stopped with a verified checkpoint. Retry move or Resume with previous settings."
557                } else {
558                    "Source or partial destination is retained. Retry move after resolving the reported error."
559                };
560                let error = format!("{error:#}");
561                operation.error = Some(error.clone());
562                (
563                    if cancelled { "cancelled" } else { "failed" },
564                    Some(error),
565                    Some(recovery.to_owned()),
566                )
567            }
568        };
569        operation.updated_at = now();
570        hel::hel_database::save_move_operation(operation)?;
571        Ok(outcome(
572            &operation.operation_id,
573            &operation.selection,
574            status,
575            error,
576            recovery,
577        ))
578    }
579
580    pub async fn recover_move_managed_controlled(
581        &mut self,
582        mut operation: MoveOperation,
583        executor: &(impl CommandExecutor + Sync),
584        manager: &SessionManagerControl,
585    ) -> Result<MoveOutcome> {
586        let id = operation.selection.session_id.clone();
587        let result = async {
588            let session = self.state.sessions.get(&id).context("move session is missing")?.clone();
589            if operation.queue_admission_started {
590                ensure!(!operation.cancellation_requested, "Move was cancelled; destination retained without further queue admission");
591                return self.admit_move_queue(&mut operation, executor).await;
592            }
593            if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
594                let cleanup = hel::hel_targets::CancellableProcessExecutor::with_timeout(std::time::Duration::from_secs(15));
595                self.recover_move_source_stop(&mut operation, &cleanup, manager).await?;
596                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
597                if self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
598                    self.cleanup_stopped_target(&id, &cleanup)?;
599                }
600                bail!("Move source stop recovered; no destination work was started. Retry Move or Resume with previous settings");
601            }
602            match operation.phase {
603                MovePhase::Preparing => bail!("Move preparation was interrupted; source retained. Prepare Move again."),
604                MovePhase::ResumingDestination if session.state == SessionState::Running => {
605                    // Running is installed only after native readiness and the
606                    // handoff. A crash before the next intent write is safe to
607                    // advance, since restore started with an empty queue.
608                    ensure!(Some(&session.last_profile) == operation.selection.profile_id.as_ref()
609                        && Some(&session.target_template_id) == operation.selection.target_template_id.as_ref(),
610                        "ready destination does not match the move intent");
611                    operation.destination_target = session.target.clone();
612                    operation.destination_native_session_id = session.native_session_id.clone();
613                    operation.queue_admission_started = true;
614                    operation.phase = MovePhase::StartingQueue;
615                    hel::hel_database::save_move_operation(&operation)?;
616                    restore_move_queue_hold(&operation);
617                    ensure!(!operation.cancellation_requested, "Move was cancelled; ready destination retained");
618                    self.admit_move_queue(&mut operation, executor).await
619                }
620                MovePhase::ResumingDestination => {
621                    let previous = operation.recovery_session.as_ref().context("move lacks its stopped recovery identity; retain resources for inspection")?;
622                    let error = self.rollback_failed_resume(&id, previous, false,
623                        anyhow::anyhow!("destination restoration was interrupted; checkpoint retained for an explicit retry"), executor)?;
624                    Err(error)
625                }
626                MovePhase::ClosingSource => {
627                    if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
628                        self.recover_move_source_stop(&mut operation, executor, manager).await?;
629                    }
630                    operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
631                    if self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
632                        self.cleanup_stopped_target(&id, executor)?;
633                    }
634                    bail!("source stop was recovered; verified checkpoint retained. Retry move or Resume with previous settings")
635                }
636                _ => bail!("Move requires an explicit retry after the daemon restarted"),
637            }
638        }.await;
639        self.finish_move_result(&mut operation, result, executor)
640    }
641
642    async fn recover_move_source_stop(
643        &mut self,
644        operation: &mut MoveOperation,
645        executor: &(impl CommandExecutor + Sync),
646        manager: &SessionManagerControl,
647    ) -> Result<()> {
648        let id = operation.selection.session_id.clone();
649        if self.state.sessions[&id].state == SessionState::Closing {
650            let handle = manager
651                .wait_for_session(&id, std::time::Duration::from_secs(5))
652                .await?;
653            let mut lease = handle.lease_connection().await?;
654            let execution = lease.connection_mut().sync().await?.operational.execution;
655            lease.release();
656            if matches!(
657                execution,
658                hel::hel_worker::RelayExecutionState::Idle
659                    | hel::hel_worker::RelayExecutionState::Running
660            ) {
661                if operation.cancellation_requested {
662                    let record = self.state.sessions.get_mut(&id).unwrap();
663                    record.state = SessionState::Running;
664                    record.updated_at = now();
665                    record.last_error =
666                        Some("Move was cancelled before the source was sealed".into());
667                    hel::hel_database::save_lifecycle_session(record)?;
668                } else {
669                    self.close_session_for_move(&id, executor, manager, operation, None)
670                        .await?;
671                }
672                return Ok(());
673            }
674        }
675        self.recover_interrupted_close_managed(&id, executor, manager)
676            .await?;
677        Ok(())
678    }
679
680    async fn execute_move(
681        &mut self,
682        operation: &mut MoveOperation,
683        preparation: Option<&MovePreparation>,
684        executor: &(impl CommandExecutor + Sync),
685        manager: &SessionManagerControl,
686    ) -> Result<()> {
687        let id = operation.selection.session_id.clone();
688        ensure!(
689            !executor.cancellation_requested(),
690            "move cancelled before source interruption"
691        );
692        if !operation.queue_admission_started {
693            if self.state.sessions[&id].state == SessionState::Error
694                && let Some(previous) = operation.recovery_session.as_ref()
695            {
696                // A prior failed teardown retains its exact partial checkout.
697                // Restore source identity only after that owner is stopped.
698                let failure = self.rollback_failed_resume(
699                    &id,
700                    previous,
701                    false,
702                    anyhow::anyhow!("clean up the partial Move destination before retry"),
703                    executor,
704                )?;
705                ensure!(
706                    self.state.sessions[&id].state == SessionState::Stopped,
707                    "{failure:#}"
708                );
709            }
710            let state = self.state.sessions[&id].state;
711            if matches!(state, SessionState::Closing | SessionState::Destroying) {
712                self.recover_move_source_stop(operation, executor, manager)
713                    .await?;
714                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
715            } else if matches!(state, SessionState::Running | SessionState::Disconnected)
716                && operation.destination_target.is_none()
717            {
718                executor.notify_notice("Stopping source");
719                let _timing = MovePhaseTimer::new(&id, "checkpoint and source stop");
720                operation.phase = MovePhase::ClosingSource;
721                operation.updated_at = now();
722                hel::hel_database::save_move_operation(operation)?;
723                self.close_session_for_move(&id, executor, manager, operation, preparation)
724                    .await?;
725            }
726            if self.state.sessions[&id].state == SessionState::Stopped
727                && self.state.sessions[&id].target.is_some()
728            {
729                executor.notify_notice("Cleaning up source");
730                let _timing = MovePhaseTimer::new(&id, "source storage cleanup");
731                self.cleanup_stopped_target(&id, executor)?;
732            }
733            operation.checkpoint = operation
734                .checkpoint
735                .clone()
736                .or_else(|| self.state.sessions[&id].checkpoint.clone());
737            ensure!(
738                operation.checkpoint.is_some(),
739                "move has no verified checkpoint"
740            );
741            ensure!(
742                !executor.cancellation_requested(),
743                "move cancelled after source teardown; session is stopped"
744            );
745            operation.phase = MovePhase::ResumingDestination;
746            operation.recovery_session = Some(self.state.sessions[&id].clone());
747            operation.updated_at = now();
748            hel::hel_database::save_move_operation(operation)?;
749            executor.notify_notice("Preparing destination");
750            if operation.selection.clear_resource_allocation {
751                let session = self.state.sessions.get_mut(&id).unwrap();
752                session.resource_allocation = None;
753                session.container_cpus = None;
754                session.container_memory = None;
755                hel::hel_database::save_session(session)?;
756            }
757            self.resume_session_controlled(
758                &id,
759                operation.selection.profile_id.as_deref().unwrap(),
760                operation.selection.target_template_id.as_deref().unwrap(),
761                SessionResumeOptions {
762                    additional_mounts: operation.selection.additional_mounts.clone(),
763                    resource_allocation: operation.selection.resource_allocation.clone(),
764                    discard_queue: true,
765                },
766                executor,
767            )
768            .await?;
769            let destination = &self.state.sessions[&id];
770            operation.destination_target = destination.target.clone();
771            operation.destination_native_session_id = destination.native_session_id.clone();
772            // Persist readiness before submitting even the first queued command.
773            operation.phase = MovePhase::StartingQueue;
774            operation.queue_admission_started = true;
775            operation.updated_at = now();
776            hel::hel_database::save_move_operation(operation)?;
777        }
778        restore_move_queue_hold(operation);
779        self.admit_move_queue(operation, executor).await
780    }
781
782    async fn admit_move_queue(
783        &self,
784        operation: &mut MoveOperation,
785        executor: &(impl CommandExecutor + Sync),
786    ) -> Result<()> {
787        let timing_id = operation.selection.session_id.clone();
788        let _timing = MovePhaseTimer::new(&timing_id, "queue admission");
789        let id = &operation.selection.session_id;
790        let mut relay = {
791            let _checking_destination =
792                ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
793            let destination = &self.state.sessions[id];
794            ensure!(
795                destination.state == SessionState::Running
796                    && destination.target == operation.destination_target
797                    && destination.native_session_id == operation.destination_native_session_id,
798                "cannot prove the same ready destination; refusing to replay potentially executed work"
799            );
800            let spec = self.reconnect_command(id)?;
801            let relay = StandaloneSession::connect_command(&spec, id).await?;
802            let store_id = relay.snapshot().operational.store_id.context("destination worker does not expose its durable store identity; upgrade the worker before admitting queued work")?;
803            if let Some(expected) = &operation.destination_store_id {
804                ensure!(
805                    *expected == store_id,
806                    "destination relay storage was replaced; refusing to replay potentially executed work"
807                );
808            } else {
809                // No command can be admitted until this identity is durable.
810                operation.destination_store_id = Some(store_id);
811                hel::hel_database::save_move_operation(operation)?;
812            }
813            ensure!(
814                relay.snapshot().operational.native_session_id
815                    == operation.destination_native_session_id,
816                "destination relay native identity changed; refusing queue replay"
817            );
818            relay
819        };
820        if operation.queue == ResumeQueueDisposition::Start && !operation.queue_admission_finished {
821            let _starting_queue = ProvisionStageGuard::new(executor, ProvisionStage::Starting);
822            executor.notify_notice("Starting queued work");
823            let checkpoint = operation
824                .checkpoint
825                .as_ref()
826                .context("move queue archive is missing")?;
827            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
828            ensure!(
829                verified.archive_sha256 == checkpoint.sha256 && verified.manifest.session.id == *id,
830                "move queue checkpoint verification failed"
831            );
832            for queued in verified.canonical_session.queued_prompts {
833                ensure!(
834                    !executor.cancellation_requested(),
835                    "move cancelled during queue admission; destination retained"
836                );
837                let command = match queued.kind {
838                    CanonicalQueuedCommandKind::Prompt => RelayCommand::Prompt {
839                        prompt: queued
840                            .content
841                            .into_iter()
842                            .map(serde_json::from_value)
843                            .collect::<serde_json::Result<_>>()?,
844                    },
845                    CanonicalQueuedCommandKind::SetConfig { key, value } => {
846                        RelayCommand::SetConfig { key, value }
847                    }
848                };
849                relay.submit(queued.command_id, command).await?;
850            }
851        }
852        operation.queue_admission_finished = true;
853        hel::hel_database::save_move_operation(operation)?;
854        restore_move_queue_hold(operation);
855        relay.submit(format!("{}-notice", operation.operation_id), RelayCommand::RecordNotice {
856            text: format!("Moved from {} / {} to {} / {} in a fresh environment. {} The interrupted prompt was not replayed.",
857                operation.source_profile_id, operation.source_target_template_id,
858                operation.selection.profile_id.as_deref().unwrap(), operation.selection.target_template_id.as_deref().unwrap(),
859                if operation.queue == ResumeQueueDisposition::Discard { "Queued work was discarded; ready and idle." } else { "Queued work was accepted." }),
860        }).await?;
861        Ok(())
862    }
863
864    pub(super) fn validate_move_checkpoint(
865        &self,
866        operation: &MoveOperation,
867        preparation: Option<&MovePreparation>,
868        executor: &(impl CommandExecutor + Sync),
869    ) -> Result<()> {
870        let _verifying = ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
871        let current = Controller {
872            config: hel::hel_config::HelConfig::load()?,
873            state: self.state.clone(),
874        };
875        ensure!(
876            current.move_configuration_fingerprint(&operation.selection)?
877                == operation.configuration_fingerprint,
878            "destination configuration changed during move"
879        );
880        let id = &operation.selection.session_id;
881        current.validate_move_destination_paths(
882            &self.state.sessions[id],
883            operation.selection.target_template_id.as_deref().unwrap(),
884            executor,
885        )?;
886        if let super::ResumeRepositorySourcePreflight::RepositoryMoved(mismatch) = self
887            .preflight_resume_repository_sources(
888                id,
889                operation.selection.target_template_id.as_deref().unwrap(),
890                executor,
891            )?
892        {
893            bail!(
894                "destination repository source is missing checkpoint commit {}; source retained",
895                mismatch.missing_commit
896            );
897        }
898        if let Some(prepared) = preparation {
899            let checkpoint = self.state.sessions[id]
900                .checkpoint
901                .as_ref()
902                .context("no move checkpoint")?;
903            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
904            let actual: Vec<_> = verified
905                .canonical_session
906                .queued_prompts
907                .iter()
908                .map(|p| p.command_id.as_str())
909                .collect();
910            let expected: Vec<_> = prepared
911                .queued_commands
912                .iter()
913                .map(|p| p.command_id.as_str())
914                .collect();
915            ensure!(
916                actual == expected,
917                "pending queue changed before checkpoint capture; source retained, confirm Move again"
918            );
919        }
920        Ok(())
921    }
922}
923
924fn outcome(
925    operation_id: &str,
926    selection: &MoveSelection,
927    status: &str,
928    error: Option<String>,
929    recovery: Option<String>,
930) -> MoveOutcome {
931    MoveOutcome {
932        operation_id: operation_id.into(),
933        session_id: selection.session_id.clone(),
934        profile_id: selection.profile_id.clone().unwrap_or_default(),
935        target_template_id: selection.target_template_id.clone().unwrap_or_default(),
936        outcome: status.into(),
937        error,
938        recovery,
939    }
940}