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