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;
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 mut checked = self
409            .prepare_move_session_controlled(prepared.selection.clone(), executor)
410            .await?;
411        // Destination checks can outlast a turn. Refresh confirmation from the
412        // relay immediately before interruption, while new submissions are held.
413        if matches!(
414            self.state.sessions[&id].state,
415            SessionState::Running | SessionState::Disconnected
416        ) {
417            let handle = manager
418                .wait_for_session(&id, std::time::Duration::from_secs(5))
419                .await?;
420            handle.sync_now().await?;
421            let (active, queue, fingerprint) = self.move_confirmation(&checked.selection)?;
422            checked.active = active
423                || handle.view().snapshot.as_ref().is_some_and(|snapshot| {
424                    let mut operational = snapshot.operational.clone();
425                    operational.queued_prompts.clear();
426                    operational.checkpoint_barrier = None;
427                    !operational.is_quiet()
428                });
429            checked.queued_commands = queue;
430            checked.fingerprint = fingerprint;
431        }
432        ensure!(
433            checked.fingerprint == prepared.fingerprint,
434            "session, pending work, or destination configuration changed; prepare and confirm Move again"
435        );
436        let queue = request.queue.unwrap_or(ResumeQueueDisposition::Discard);
437        let source = self.state.sessions[&id].clone();
438        let old_operation = hel::hel_database::load_move_operation(&id)?;
439        let retry = old_operation.filter(|op| {
440            op.selection == prepared.selection
441                && op.phase != MovePhase::Completed
442                && op.checkpoint.is_some()
443        });
444        if retry.is_none()
445            && source.state == SessionState::Running
446            && source.last_profile == checked.selection.profile_id.as_deref().unwrap()
447            && source.target_template_id == checked.selection.target_template_id.as_deref().unwrap()
448            && Some(&source.additional_mounts) == checked.selection.additional_mounts.as_ref()
449            && source.resource_allocation == checked.selection.resource_allocation
450            && (!checked.selection.clear_resource_allocation
451                || (source.container_cpus.is_none() && source.container_memory.is_none()))
452        {
453            return Ok(outcome(
454                &prepared.operation_id,
455                &prepared.selection,
456                "unchanged",
457                None,
458                None,
459            ));
460        }
461        ensure!(
462            !checked.active || request.acknowledge_interruption,
463            "active work will be interrupted; confirm Move again with interruption acknowledgement"
464        );
465        ensure!(
466            checked.queued_commands.is_empty() || request.queue.is_some(),
467            "pending work requires an explicit queue choice: discard or start"
468        );
469        let timestamp = now();
470        let mut operation = match retry {
471            Some(mut op) => {
472                ensure!(
473                    !op.queue_admission_started || op.queue == queue,
474                    "queued work may already have run; retry with the original queue choice on the same destination"
475                );
476                hel::hel_database::clear_move_cancellation_for_retry(&id)?;
477                op.configuration_fingerprint =
478                    self.move_configuration_fingerprint(&checked.selection)?;
479                op.queue = queue;
480                op.cancellation_requested = false;
481                op.error = None;
482                op
483            }
484            None => MoveOperation {
485                operation_id: prepared.operation_id.clone(),
486                selection: checked.selection.clone(),
487                source_profile_id: source.last_profile.clone(),
488                source_target_template_id: source.target_template_id.clone(),
489                source_target: source.target.clone(),
490                source_native_session_id: source.native_session_id.clone(),
491                source_additional_mounts: source.additional_mounts.clone(),
492                source_resource_allocation: source.resource_allocation.clone(),
493                destination_target: None,
494                destination_native_session_id: None,
495                destination_store_id: None,
496                configuration_fingerprint: self
497                    .move_configuration_fingerprint(&checked.selection)?,
498                checkpoint: None,
499                recovery_session: None,
500                queue,
501                phase: MovePhase::Preparing,
502                queue_admission_started: false,
503                queue_admission_finished: false,
504                cancellation_requested: false,
505                created_at: timestamp.clone(),
506                updated_at: timestamp,
507                error: None,
508            },
509        };
510        hel::hel_database::save_move_operation(&operation)?;
511        tracing::info!(
512            session_id = id,
513            phase = "preflight",
514            elapsed_ms = started.elapsed().as_millis() as u64,
515            "move phase completed"
516        );
517        let result = self
518            .execute_move(&mut operation, Some(&checked), executor, manager)
519            .await;
520        self.finish_move_result(&mut operation, result, executor)
521    }
522
523    fn finish_move_result(
524        &self,
525        operation: &mut MoveOperation,
526        result: Result<()>,
527        executor: &impl CommandExecutor,
528    ) -> Result<MoveOutcome> {
529        let (status, error, recovery) = match result {
530            Ok(()) => {
531                operation.phase = MovePhase::Completed;
532                ("completed", None, None)
533            }
534            Err(error) => {
535                let cancelled =
536                    executor.cancellation_requested() || operation.cancellation_requested;
537                operation.phase = if cancelled {
538                    MovePhase::Cancelled
539                } else {
540                    MovePhase::Failed
541                };
542                operation.cancellation_requested = cancelled;
543                let recovery = if operation.queue_admission_started {
544                    "Destination is live; retry queue admission on this same destination. Already accepted work may have effects."
545                } else if self
546                    .state
547                    .sessions
548                    .get(&operation.selection.session_id)
549                    .is_some_and(|s| s.state == SessionState::Stopped)
550                {
551                    "Session is stopped with a verified checkpoint. Retry move or Resume with previous settings."
552                } else {
553                    "Source or partial destination is retained. Retry move after resolving the reported error."
554                };
555                let error = format!("{error:#}");
556                operation.error = Some(error.clone());
557                (
558                    if cancelled { "cancelled" } else { "failed" },
559                    Some(error),
560                    Some(recovery.to_owned()),
561                )
562            }
563        };
564        operation.updated_at = now();
565        hel::hel_database::save_move_operation(operation)?;
566        Ok(outcome(
567            &operation.operation_id,
568            &operation.selection,
569            status,
570            error,
571            recovery,
572        ))
573    }
574
575    pub async fn recover_move_managed_controlled(
576        &mut self,
577        mut operation: MoveOperation,
578        executor: &(impl CommandExecutor + Sync),
579        manager: &SessionManagerControl,
580    ) -> Result<MoveOutcome> {
581        let id = operation.selection.session_id.clone();
582        let result = async {
583            let session = self.state.sessions.get(&id).context("move session is missing")?.clone();
584            if operation.queue_admission_started {
585                ensure!(!operation.cancellation_requested, "Move was cancelled; destination retained without further queue admission");
586                return self.admit_move_queue(&mut operation, executor).await;
587            }
588            if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
589                let cleanup = hel::hel_targets::CancellableProcessExecutor::with_timeout(std::time::Duration::from_secs(15));
590                self.recover_move_source_stop(&mut operation, &cleanup, manager).await?;
591                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
592                if self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
593                    self.cleanup_stopped_target(&id, &cleanup)?;
594                }
595                bail!("Move source stop recovered; no destination work was started. Retry Move or Resume with previous settings");
596            }
597            match operation.phase {
598                MovePhase::Preparing => bail!("Move preparation was interrupted; source retained. Prepare Move again."),
599                MovePhase::ResumingDestination if session.state == SessionState::Running => {
600                    // Running is installed only after native readiness and the
601                    // handoff. A crash before the next intent write is safe to
602                    // advance, since restore started with an empty queue.
603                    ensure!(Some(&session.last_profile) == operation.selection.profile_id.as_ref()
604                        && Some(&session.target_template_id) == operation.selection.target_template_id.as_ref(),
605                        "ready destination does not match the move intent");
606                    operation.destination_target = session.target.clone();
607                    operation.destination_native_session_id = session.native_session_id.clone();
608                    operation.queue_admission_started = true;
609                    operation.phase = MovePhase::StartingQueue;
610                    hel::hel_database::save_move_operation(&operation)?;
611                    restore_move_queue_hold(&operation);
612                    ensure!(!operation.cancellation_requested, "Move was cancelled; ready destination retained");
613                    self.admit_move_queue(&mut operation, executor).await
614                }
615                MovePhase::ResumingDestination => {
616                    let previous = operation.recovery_session.as_ref().context("move lacks its stopped recovery identity; retain resources for inspection")?;
617                    let error = self.rollback_failed_resume(&id, previous, false,
618                        anyhow::anyhow!("destination restoration was interrupted; checkpoint retained for an explicit retry"), executor)?;
619                    Err(error)
620                }
621                MovePhase::ClosingSource => {
622                    if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
623                        self.recover_move_source_stop(&mut operation, executor, manager).await?;
624                    }
625                    operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
626                    if self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
627                        self.cleanup_stopped_target(&id, executor)?;
628                    }
629                    bail!("source stop was recovered; verified checkpoint retained. Retry move or Resume with previous settings")
630                }
631                _ => bail!("Move requires an explicit retry after the daemon restarted"),
632            }
633        }.await;
634        self.finish_move_result(&mut operation, result, executor)
635    }
636
637    async fn recover_move_source_stop(
638        &mut self,
639        operation: &mut MoveOperation,
640        executor: &(impl CommandExecutor + Sync),
641        manager: &SessionManagerControl,
642    ) -> Result<()> {
643        let id = operation.selection.session_id.clone();
644        if self.state.sessions[&id].state == SessionState::Closing {
645            let handle = manager
646                .wait_for_session(&id, std::time::Duration::from_secs(5))
647                .await?;
648            let mut lease = handle.lease_connection().await?;
649            let execution = lease.connection_mut().sync().await?.operational.execution;
650            lease.release();
651            if matches!(
652                execution,
653                hel::hel_worker::RelayExecutionState::Idle
654                    | hel::hel_worker::RelayExecutionState::Running
655            ) {
656                if operation.cancellation_requested {
657                    let record = self.state.sessions.get_mut(&id).unwrap();
658                    record.state = SessionState::Running;
659                    record.updated_at = now();
660                    record.last_error =
661                        Some("Move was cancelled before the source was sealed".into());
662                    hel::hel_database::save_lifecycle_session(record)?;
663                } else {
664                    self.close_session_for_move(&id, executor, manager, operation, None)
665                        .await?;
666                }
667                return Ok(());
668            }
669        }
670        self.recover_interrupted_close_managed(&id, executor, manager)
671            .await?;
672        Ok(())
673    }
674
675    async fn execute_move(
676        &mut self,
677        operation: &mut MoveOperation,
678        preparation: Option<&MovePreparation>,
679        executor: &(impl CommandExecutor + Sync),
680        manager: &SessionManagerControl,
681    ) -> Result<()> {
682        let id = operation.selection.session_id.clone();
683        ensure!(
684            !executor.cancellation_requested(),
685            "move cancelled before source interruption"
686        );
687        if !operation.queue_admission_started {
688            if self.state.sessions[&id].state == SessionState::Error
689                && let Some(previous) = operation.recovery_session.as_ref()
690            {
691                // A prior failed teardown retains its exact partial checkout.
692                // Restore source identity only after that owner is stopped.
693                let failure = self.rollback_failed_resume(
694                    &id,
695                    previous,
696                    false,
697                    anyhow::anyhow!("clean up the partial Move destination before retry"),
698                    executor,
699                )?;
700                ensure!(
701                    self.state.sessions[&id].state == SessionState::Stopped,
702                    "{failure:#}"
703                );
704            }
705            let state = self.state.sessions[&id].state;
706            if matches!(state, SessionState::Closing | SessionState::Destroying) {
707                self.recover_move_source_stop(operation, executor, manager)
708                    .await?;
709                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
710            } else if matches!(state, SessionState::Running | SessionState::Disconnected)
711                && operation.destination_target.is_none()
712            {
713                executor.notify_notice("Stopping source");
714                let _timing = MovePhaseTimer::new(&id, "checkpoint and source stop");
715                operation.phase = MovePhase::ClosingSource;
716                operation.updated_at = now();
717                hel::hel_database::save_move_operation(operation)?;
718                self.close_session_for_move(&id, executor, manager, operation, preparation)
719                    .await?;
720            }
721            if self.state.sessions[&id].state == SessionState::Stopped
722                && self.state.sessions[&id].target.is_some()
723            {
724                executor.notify_notice("Cleaning up source");
725                let _timing = MovePhaseTimer::new(&id, "source storage cleanup");
726                self.cleanup_stopped_target(&id, executor)?;
727            }
728            operation.checkpoint = operation
729                .checkpoint
730                .clone()
731                .or_else(|| self.state.sessions[&id].checkpoint.clone());
732            ensure!(
733                operation.checkpoint.is_some(),
734                "move has no verified checkpoint"
735            );
736            ensure!(
737                !executor.cancellation_requested(),
738                "move cancelled after source teardown; session is stopped"
739            );
740            operation.phase = MovePhase::ResumingDestination;
741            operation.recovery_session = Some(self.state.sessions[&id].clone());
742            operation.updated_at = now();
743            hel::hel_database::save_move_operation(operation)?;
744            executor.notify_notice("Preparing destination");
745            if operation.selection.clear_resource_allocation {
746                let session = self.state.sessions.get_mut(&id).unwrap();
747                session.resource_allocation = None;
748                session.container_cpus = None;
749                session.container_memory = None;
750                hel::hel_database::save_session(session)?;
751            }
752            self.resume_session_controlled(
753                &id,
754                operation.selection.profile_id.as_deref().unwrap(),
755                operation.selection.target_template_id.as_deref().unwrap(),
756                SessionResumeOptions {
757                    additional_mounts: operation.selection.additional_mounts.clone(),
758                    resource_allocation: operation.selection.resource_allocation.clone(),
759                    discard_queue: true,
760                },
761                executor,
762            )
763            .await?;
764            let destination = &self.state.sessions[&id];
765            operation.destination_target = destination.target.clone();
766            operation.destination_native_session_id = destination.native_session_id.clone();
767            // Persist readiness before submitting even the first queued command.
768            operation.phase = MovePhase::StartingQueue;
769            operation.queue_admission_started = true;
770            operation.updated_at = now();
771            hel::hel_database::save_move_operation(operation)?;
772        }
773        restore_move_queue_hold(operation);
774        self.admit_move_queue(operation, executor).await
775    }
776
777    async fn admit_move_queue(
778        &self,
779        operation: &mut MoveOperation,
780        executor: &(impl CommandExecutor + Sync),
781    ) -> Result<()> {
782        let timing_id = operation.selection.session_id.clone();
783        let _timing = MovePhaseTimer::new(&timing_id, "queue admission");
784        let id = &operation.selection.session_id;
785        let destination = &self.state.sessions[id];
786        ensure!(
787            destination.state == SessionState::Running
788                && destination.target == operation.destination_target
789                && destination.native_session_id == operation.destination_native_session_id,
790            "cannot prove the same ready destination; refusing to replay potentially executed work"
791        );
792        let spec = self.reconnect_command(id)?;
793        let mut relay = StandaloneSession::connect_command(&spec, id).await?;
794        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")?;
795        if let Some(expected) = &operation.destination_store_id {
796            ensure!(
797                *expected == store_id,
798                "destination relay storage was replaced; refusing to replay potentially executed work"
799            );
800        } else {
801            // No command can be admitted until this identity is durable.
802            operation.destination_store_id = Some(store_id);
803            hel::hel_database::save_move_operation(operation)?;
804        }
805        ensure!(
806            relay.snapshot().operational.native_session_id
807                == operation.destination_native_session_id,
808            "destination relay native identity changed; refusing queue replay"
809        );
810        if operation.queue == ResumeQueueDisposition::Start && !operation.queue_admission_finished {
811            executor.notify_notice("Starting queued work");
812            let checkpoint = operation
813                .checkpoint
814                .as_ref()
815                .context("move queue archive is missing")?;
816            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
817            ensure!(
818                verified.archive_sha256 == checkpoint.sha256 && verified.manifest.session.id == *id,
819                "move queue checkpoint verification failed"
820            );
821            for queued in verified.canonical_session.queued_prompts {
822                ensure!(
823                    !executor.cancellation_requested(),
824                    "move cancelled during queue admission; destination retained"
825                );
826                let command = match queued.kind {
827                    CanonicalQueuedCommandKind::Prompt => RelayCommand::Prompt {
828                        prompt: queued
829                            .content
830                            .into_iter()
831                            .map(serde_json::from_value)
832                            .collect::<serde_json::Result<_>>()?,
833                    },
834                    CanonicalQueuedCommandKind::SetConfig { key, value } => {
835                        RelayCommand::SetConfig { key, value }
836                    }
837                };
838                relay.submit(queued.command_id, command).await?;
839            }
840        }
841        operation.queue_admission_finished = true;
842        hel::hel_database::save_move_operation(operation)?;
843        restore_move_queue_hold(operation);
844        relay.submit(format!("{}-notice", operation.operation_id), RelayCommand::RecordNotice {
845            text: format!("Moved from {} / {} to {} / {} in a fresh environment. {} The interrupted prompt was not replayed.",
846                operation.source_profile_id, operation.source_target_template_id,
847                operation.selection.profile_id.as_deref().unwrap(), operation.selection.target_template_id.as_deref().unwrap(),
848                if operation.queue == ResumeQueueDisposition::Discard { "Queued work was discarded; ready and idle." } else { "Queued work was accepted." }),
849        }).await?;
850        Ok(())
851    }
852
853    pub(super) fn validate_move_checkpoint(
854        &self,
855        operation: &MoveOperation,
856        preparation: Option<&MovePreparation>,
857        executor: &(impl CommandExecutor + Sync),
858    ) -> Result<()> {
859        let current = Controller {
860            config: hel::hel_config::HelConfig::load()?,
861            state: self.state.clone(),
862        };
863        ensure!(
864            current.move_configuration_fingerprint(&operation.selection)?
865                == operation.configuration_fingerprint,
866            "destination configuration changed during move"
867        );
868        let id = &operation.selection.session_id;
869        current.validate_move_destination_paths(
870            &self.state.sessions[id],
871            operation.selection.target_template_id.as_deref().unwrap(),
872            executor,
873        )?;
874        if let super::ResumeRepositorySourcePreflight::RepositoryMoved(mismatch) = self
875            .preflight_resume_repository_sources(
876                id,
877                operation.selection.target_template_id.as_deref().unwrap(),
878                executor,
879            )?
880        {
881            bail!(
882                "destination repository source is missing checkpoint commit {}; source retained",
883                mismatch.missing_commit
884            );
885        }
886        if let Some(prepared) = preparation {
887            let checkpoint = self.state.sessions[id]
888                .checkpoint
889                .as_ref()
890                .context("no move checkpoint")?;
891            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
892            let actual: Vec<_> = verified
893                .canonical_session
894                .queued_prompts
895                .iter()
896                .map(|p| p.command_id.as_str())
897                .collect();
898            let expected: Vec<_> = prepared
899                .queued_commands
900                .iter()
901                .map(|p| p.command_id.as_str())
902                .collect();
903            ensure!(
904                actual == expected,
905                "pending queue changed before checkpoint capture; source retained, confirm Move again"
906            );
907        }
908        Ok(())
909    }
910}
911
912fn outcome(
913    operation_id: &str,
914    selection: &MoveSelection,
915    status: &str,
916    error: Option<String>,
917    recovery: Option<String>,
918) -> MoveOutcome {
919    MoveOutcome {
920        operation_id: operation_id.into(),
921        session_id: selection.session_id.clone(),
922        profile_id: selection.profile_id.clone().unwrap_or_default(),
923        target_template_id: selection.target_template_id.clone().unwrap_or_default(),
924        outcome: status.into(),
925        error,
926        recovery,
927    }
928}