brokk-mj-controller 2.24.0

Daemon-side controller, session manager, and web server for Mjolnir
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
//! One recoverable stop/restore operation, independent of its initiating viewer.

mod handoff;
#[cfg(test)]
mod tests;
mod transfer;

use anyhow::{Context, Result, bail, ensure};
use mj_core::hex::lower_hex;
use sha2::{Digest, Sha256};

use super::lifecycle::SourceTargetDisposition;
use super::{Controller, SessionResumeOptions, now};

/// Execution and retained queue admission are phases of one ownership record.
#[derive(Clone, Copy)]
enum MoveOwnership {
    Executing,
    ExecutingQueue,
    PendingQueue,
}

fn move_ownership() -> &'static std::sync::Mutex<std::collections::BTreeMap<String, MoveOwnership>>
{
    static OWNER: std::sync::OnceLock<
        std::sync::Mutex<std::collections::BTreeMap<String, MoveOwnership>>,
    > = std::sync::OnceLock::new();
    OWNER.get_or_init(Default::default)
}

pub fn move_owns_session(session_id: &str) -> bool {
    move_ownership()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner)
        .contains_key(session_id)
}

pub fn move_has_pending_queue(session_id: &str) -> bool {
    matches!(
        move_ownership()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
            .get(session_id),
        Some(MoveOwnership::ExecutingQueue | MoveOwnership::PendingQueue)
    )
}

pub fn release_move_queue_hold(session_id: &str) {
    set_move_queue_hold(session_id, false);
}

fn set_move_queue_hold(session_id: &str, pending: bool) {
    let mut owner = move_ownership()
        .lock()
        .unwrap_or_else(std::sync::PoisonError::into_inner);
    let next = match (owner.get(session_id), pending) {
        (Some(MoveOwnership::Executing | MoveOwnership::ExecutingQueue), true) => {
            Some(MoveOwnership::ExecutingQueue)
        }
        (Some(MoveOwnership::Executing | MoveOwnership::ExecutingQueue), false) => {
            Some(MoveOwnership::Executing)
        }
        (_, true) => Some(MoveOwnership::PendingQueue),
        (_, false) => None,
    };
    if let Some(next) = next {
        owner.insert(session_id.to_owned(), next);
    } else {
        owner.remove(session_id);
    }
}

pub fn restore_move_queue_hold(operation: &MoveOperation) {
    set_move_queue_hold(
        &operation.selection.session_id,
        operation.queue_admission_started && !operation.queue_admission_finished,
    );
}

/// What a recovered, interrupted source stop tells the person.
///
/// Recovery keeps the environment promised by an in-place move.
fn interrupted_source_stop_message(recovered: &str, in_place: bool) -> String {
    if in_place {
        format!("{recovered}; the in-place swap was interrupted; the environment was retained")
    } else {
        recovered.to_owned()
    }
}

/// Whether the persisted record shows a source that has finished stopping with
/// a verified checkpoint to restore.
///
/// Only `Stopped` proves the source stop finished. Resume also admits recovery
/// states, but those do not establish that the source is already stopped.
fn source_stopped_with_verified_checkpoint(record: &mj_core::state::SessionRecord) -> bool {
    record.state == SessionState::Stopped && record.checkpoint.is_some()
}

/// The recovery guidance for a failed Move whose source is already stopped with
/// a verified checkpoint.
///
/// Resume restores the retained checkpoint on the destination profile and
/// target the Move selected.
fn stopped_source_recovery(
    session_id: &str,
    destination_profile: Option<&str>,
    destination_target: Option<&str>,
) -> String {
    let flag = |name: &str, value: Option<&str>| {
        value
            .filter(|value| !value.is_empty())
            .map(|value| format!(" --{name} {value}"))
            .unwrap_or_default()
    };
    format!(
        "Source is stopped with a verified checkpoint. Bring it back with \
         `mj resume --session {session_id}{}{} --queue start`.",
        flag("profile", destination_profile),
        flag("target", destination_target),
    )
}

/// The recovery guidance a failed or cancelled Move shows, from its persisted
/// state.
fn failed_move_recovery(
    operation: &MoveOperation,
    record: Option<&mj_core::state::SessionRecord>,
) -> String {
    if operation.queue_admission_started {
        return "Destination is live; retry queue admission on this same destination. Already accepted work may have effects.".to_owned();
    }
    if operation.in_place && record.is_some_and(|record| record.target.is_some()) {
        return "Environment and checkpoint retained. Retry Move on the same target; the checkout will not be recreated.".to_owned();
    }
    match record {
        Some(record) if source_stopped_with_verified_checkpoint(record) => {
            stopped_source_recovery(
                &operation.selection.session_id,
                operation.selection.profile_id.as_deref(),
                operation.selection.target_template_id.as_deref(),
            )
        }
        _ => "Source or partial destination is retained. Retry move after resolving the reported error.".to_owned(),
    }
}

pub struct MoveMutationGuard(String);

impl MoveMutationGuard {
    pub fn reserve(session_id: &str) -> Result<Self> {
        let mut owner = move_ownership()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        ensure!(
            !matches!(
                owner.get(session_id),
                Some(MoveOwnership::Executing | MoveOwnership::ExecutingQueue)
            ),
            "session already has a move owner"
        );
        let next = if owner.contains_key(session_id) {
            MoveOwnership::ExecutingQueue
        } else {
            MoveOwnership::Executing
        };
        owner.insert(session_id.to_owned(), next);
        Ok(Self(session_id.to_owned()))
    }
}

impl Drop for MoveMutationGuard {
    fn drop(&mut self) {
        let mut owner = move_ownership()
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner);
        match owner.get(&self.0) {
            Some(MoveOwnership::ExecutingQueue) => {
                owner.insert(self.0.clone(), MoveOwnership::PendingQueue);
            }
            Some(MoveOwnership::Executing) => {
                owner.remove(&self.0);
            }
            _ => {}
        }
    }
}

pub(crate) fn move_refuses_command(session_id: &str, command: &RelayCommand) -> bool {
    move_owns_session(session_id)
        && matches!(
            command,
            RelayCommand::Prompt { .. }
                | RelayCommand::SetConfig { .. }
                | RelayCommand::SetSessionMode { .. }
                | RelayCommand::RestoreExecutionMode
                | RelayCommand::RunUserShell { .. }
                | RelayCommand::CancelUserShell { .. }
                | RelayCommand::Cancel
                | RelayCommand::RemoveQueuedPrompt { .. }
                | RelayCommand::ClearQueuedPrompts
        )
}
use crate::session_manager::{SessionManagerControl, StandaloneSession, new_command_id};
use mj_checkpoint::archive::{CanonicalQueuedCommandKind, verify_archive_streaming};
use mj_core::state::{MoveOperation, MovePhase, ResumeQueueDisposition, SessionState};

pub use mj_core::state::{MoveOutcome, MovePreparation, MoveSelection, MoveSessionRequest};

use crate::targets::{CommandExecutor, ProvisionStage, ProvisionStageGuard};
use mj_core::relay::RelayCommand;

/// Refresh source state without turning a dead source harness into a Move prerequisite.
pub async fn refresh_move_source(
    manager: &SessionManagerControl,
    id: &str,
) -> Result<Option<mj_core::state::ManagedSessionSnapshot>> {
    Ok(MoveSourceRelay::lease(manager, id).await?.snapshot())
}

/// A Move's hold on its source's relay connection, from the confirmation
/// until the checkpoint that seals the source takes it over. While it is
/// held, the session actor admits nothing to the relay, so the state the Move
/// was confirmed against is the state it interrupts. Dropping it hands the
/// connection back to the actor.
#[derive(Default)]
pub(in crate::controller) struct MoveSourceRelay(Option<super::checkpoint::ControllerRelayLease>);

impl MoveSourceRelay {
    /// Take the source's connection from its session actor, which syncs it
    /// before handing it over. Holds nothing when the source's worker cannot
    /// be reached; the Move then recovers it without its harness. Leasing
    /// preserves typed transport failures, unlike the UI's string-valued sync.
    pub(in crate::controller) async fn lease(
        manager: &SessionManagerControl,
        id: &str,
    ) -> Result<Self> {
        let handle = manager
            .wait_for_session(id, std::time::Duration::from_secs(5))
            .await?;
        match handle.lease_connection().await {
            Ok(lease) => Ok(Self(Some(
                super::checkpoint::ControllerRelayLease::Managed {
                    handle,
                    lease: Some(lease),
                },
            ))),
            Err(error) if crate::worker_client::RelayTransportDead::marks(&error) => {
                tracing::warn!(session_id = id, error = %error, "Move will recover the unavailable source without its harness");
                Ok(Self(None))
            }
            Err(error) => Err(error),
        }
    }

    /// The source's state as of its last sync, or `None` when it is unreachable.
    pub(in crate::controller) fn snapshot(
        &mut self,
    ) -> Option<mj_core::state::ManagedSessionSnapshot> {
        self.0
            .as_mut()
            .map(|relay| relay.connection_mut().snapshot())
    }

    /// Sync the held connection again. A source whose transport died since it
    /// was leased is let go and reported unreachable.
    pub(in crate::controller) async fn sync(
        &mut self,
        id: &str,
    ) -> Result<Option<mj_core::state::ManagedSessionSnapshot>> {
        let Some(relay) = self.0.as_mut() else {
            return Ok(None);
        };
        match relay.connection_mut().sync().await {
            Ok(snapshot) => Ok(Some(snapshot)),
            Err(error) if crate::worker_client::RelayTransportDead::marks(&error) => {
                tracing::warn!(session_id = id, error = %error, "Move will recover the unavailable source without its harness");
                self.0 = None;
                Ok(None)
            }
            Err(error) => Err(error),
        }
    }

    pub(in crate::controller) fn is_held(&self) -> bool {
        self.0.is_some()
    }

    /// Hand the connection to the checkpoint that seals the source.
    pub(in crate::controller) fn take(
        &mut self,
    ) -> Option<super::checkpoint::ControllerRelayLease> {
        self.0.take()
    }

    /// Keep holding the source across a worker restart, on the new worker's
    /// connection.
    pub(in crate::controller) fn replace_connection(
        &mut self,
        connection: crate::session_manager::StandaloneSession,
    ) {
        if let Some(relay) = self.0.as_mut() {
            relay.replace_connection(connection);
        }
    }
}

impl Drop for MoveSourceRelay {
    fn drop(&mut self) {
        if let Some(relay) = self.0.take() {
            relay.release();
        }
    }
}

fn digest(value: &impl serde::Serialize) -> Result<String> {
    Ok(lower_hex(Sha256::digest(serde_json::to_vec(value)?)))
}

struct MovePhaseTimer<'a> {
    session_id: &'a str,
    phase: &'static str,
    started: std::time::Instant,
}

impl<'a> MovePhaseTimer<'a> {
    fn new(session_id: &'a str, phase: &'static str) -> Self {
        Self {
            session_id,
            phase,
            started: std::time::Instant::now(),
        }
    }
}

impl Drop for MovePhaseTimer<'_> {
    fn drop(&mut self) {
        tracing::info!(
            session_id = self.session_id,
            phase = self.phase,
            elapsed_ms = self.started.elapsed().as_millis() as u64,
            "move phase finished"
        );
    }
}

/// Confirmation is an inspector, not transport for attachment bytes: every
/// surface that shows a move preparation sees a placeholder for each queued
/// image. Replay always reads the verified archive after destination readiness.
fn replace_queued_images_with_placeholders(
    queued_commands: &mut [mj_core::state::MaterializedQueuedPrompt],
) {
    for block in queued_commands
        .iter_mut()
        .flat_map(|command| command.content.iter_mut())
    {
        if block.get("type").and_then(serde_json::Value::as_str) != Some("image") {
            continue;
        }
        let mime = block
            .get("mimeType")
            .or_else(|| block.get("mime_type"))
            .and_then(serde_json::Value::as_str)
            .unwrap_or("image");
        *block = serde_json::json!({"type": "text", "text": format!("[Image attachment: {mime}]")});
    }
}

impl Controller {
    /// Returns the planned conversion when this move turns a local checkout
    /// into an isolated workspace, so the caller can describe it without
    /// reading Git a second time.
    fn validate_move_destination_paths(
        &self,
        source: &mj_core::state::SessionRecord,
        target_id: &str,
        executor: &(impl CommandExecutor + Sync),
    ) -> Result<Option<super::worktree::RawToWorkspaceConversion>> {
        use super::worktree::ResumePlan;
        match super::worktree::resume_compatibility(source, &self.config, target_id)
            .map_err(anyhow::Error::msg)?
        {
            ResumePlan::RawToWorkspace => {
                return Ok(Some(super::worktree::plan_raw_to_workspace(
                    source,
                    &self.config,
                    executor,
                )?));
            }
            ResumePlan::WorkspaceToRaw => {
                self.plan_workspace_to_raw(source, target_id, executor)?;
            }
            ResumePlan::InPlace if source.managed_worktree.is_none() => {
                if let Some(path) = &source.project_directory {
                    self.validate_project_directory(target_id, path, executor)?;
                }
            }
            ResumePlan::InPlace => {}
        }
        Ok(None)
    }
    fn move_confirmation(
        &self,
        selection: &MoveSelection,
        conversion: Option<&mj_core::state::RawConversionPreview>,
    ) -> Result<(bool, Vec<mj_core::state::MaterializedQueuedPrompt>, String)> {
        let source = self
            .state
            .sessions
            .get(&selection.session_id)
            .context("unknown move session")?;
        let (mut active, mut queued) = crate::database::move_pending_work(&source.id)?;
        if let Some(operation) = crate::database::load_move_operation(&source.id)?
            && operation.queue_admission_started
            && !operation.queue_admission_finished
        {
            ensure!(
                operation.selection == *selection,
                "queue admission is incomplete on the live destination; retry that move before selecting another destination"
            );
            let checkpoint = operation
                .restore_artifact()
                .context("retained queue checkpoint is missing")?;
            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
            ensure!(
                verified.archive_sha256 == checkpoint.sha256
                    && verified.manifest.session.id == source.id,
                "retained move checkpoint verification failed"
            );
            queued = verified
                .canonical_session
                .queued_prompts
                .into_iter()
                .map(|entry| mj_core::state::MaterializedQueuedPrompt {
                    accepted_ordinal: None,
                    command_id: entry.command_id,
                    kind: match entry.kind {
                        CanonicalQueuedCommandKind::Prompt => {
                            mj_core::state::QueuedCommandKind::Prompt
                        }
                        CanonicalQueuedCommandKind::SetConfig { key, value } => {
                            mj_core::state::QueuedCommandKind::SetConfig { key, value }
                        }
                    },
                    content: entry.content,
                    queued_at_ms: entry.queued_at_ms,
                })
                .collect();
            active = false;
        }
        let fingerprint = digest(&(
            &source.last_profile,
            &source.target_template_id,
            &source.target,
            &source.target_runtime,
            &source.native_session_id,
            &source.resource_allocation,
            &source.additional_mounts,
            &source.container_cpus,
            &source.container_memory,
            selection,
            self.move_configuration_fingerprint(selection)?,
            &queued,
            // Only what the destination is built from. The dirty counts move
            // with every keystroke of a live agent, and hashing them would
            // invalidate the confirmation the person is reading.
            conversion.map(|preview| {
                (
                    &preview.fetch_url,
                    &preview.push_urls,
                    &preview.branch,
                    &preview.destination,
                )
            }),
        ))?;
        Ok((active, queued, fingerprint))
    }
    pub(super) fn move_configuration_fingerprint(
        &self,
        selection: &MoveSelection,
    ) -> Result<String> {
        let profile = self
            .config
            .profiles
            .get(
                selection
                    .profile_id
                    .as_deref()
                    .context("move profile is unresolved")?,
            )
            .context("move profile no longer exists")?;
        let target = self
            .config
            .targets
            .get(
                selection
                    .target_template_id
                    .as_deref()
                    .context("move target is unresolved")?,
            )
            .context("move target no longer exists")?;
        // Only a digest crosses IPC or enters the move record. Configuration
        // may contain credential-bearing values and must never be copied there.
        let source = self
            .state
            .sessions
            .get(&selection.session_id)
            .context("unknown move session")?;
        digest(&(
            profile,
            target,
            &self.config.bundles,
            self.config.targets.get(&source.target_template_id),
            self.config.profiles.get(&source.last_profile),
        ))
    }

    async fn validate_move_destination_configuration(
        &self,
        selection: &MoveSelection,
        source_harness: mj_core::config::HarnessKind,
        operational: &mj_core::relay::RelayOperationalState,
    ) -> Result<()> {
        let profile_id = selection
            .profile_id
            .as_deref()
            .context("move profile is unresolved")?;
        let profile = self
            .config
            .profiles
            .get(profile_id)
            .context("move profile no longer exists")?;
        let source = self
            .state
            .sessions
            .get(&selection.session_id)
            .context("unknown move session")?;
        if profile.kind != source_harness || profile_id == source.last_profile {
            return Ok(());
        }
        let accepted = mj_core::acp::AcceptedSessionConfig::from_configuration(
            &operational.config,
            &operational.config_options,
        );
        if accepted.model.is_none() && accepted.effort.is_none() {
            return Ok(());
        }
        // A fresh probe prevents a stale local catalogue from approving a
        // move that the destination profile will immediately reset.
        let choices =
            super::profile_config::discover(profile_id.to_owned(), accepted.model.clone(), true)
                .await
                .with_context(|| {
                    format!("discover destination profile {profile_id:?} configuration")
                })?;
        validate_preserved_configuration(profile_id, &accepted, &choices)
    }

    pub async fn prepare_move_session_controlled(
        &self,
        mut selection: MoveSelection,
        executor: &(impl CommandExecutor + Sync),
    ) -> Result<MovePreparation> {
        ensure!(
            selection.profile_id.is_some() || selection.target_template_id.is_some(),
            "move requires a target or profile selection"
        );
        let source = self
            .state
            .sessions
            .get(&selection.session_id)
            .context("unknown session")?;
        ensure!(
            !self.state.subagents.contains_key(&source.id),
            "sub-agent sessions cannot move independently of their parent"
        );
        let previous = crate::database::load_move_operation(&source.id)?;
        let retry = previous.as_ref().is_some_and(|op| {
            !matches!(op.phase, MovePhase::Completed)
                && (op.restore_artifact().is_some() || source.checkpoint.is_some())
        });
        ensure!(
            matches!(
                source.state,
                SessionState::Running | SessionState::Disconnected
            ) || retry,
            "only active sessions can move; run `mj resume` (or POST /api/v1/sessions/{}/resume) for a stopped or lost session",
            source.id
        );
        selection
            .profile_id
            .get_or_insert_with(|| source.last_profile.clone());
        selection
            .target_template_id
            .get_or_insert_with(|| source.target_template_id.clone());
        selection
            .additional_mounts
            .get_or_insert_with(|| source.additional_mounts.clone());
        ensure!(
            !selection.clear_resource_allocation || selection.resource_allocation.is_none(),
            "select resource allocation or explicitly clear it, not both"
        );
        if !selection.clear_resource_allocation {
            selection.resource_allocation = selection
                .resource_allocation
                .or_else(|| source.resource_allocation.clone());
        }
        if selection.clear_resource_allocation
            && source.resource_allocation.is_none()
            && source.container_cpus.is_none()
            && source.container_memory.is_none()
        {
            selection.clear_resource_allocation = false;
        }
        if let Some(retained) = previous.as_ref().filter(|op| {
            op.retains_source_environment()
                && op.phase != MovePhase::Completed
                && op.recovery_session.is_some()
        }) {
            ensure!(
                retained.selection == selection,
                "a sealed Move must be retried with its prepared destination and file selection"
            );
            ensure!(
                !retained.in_place
                    || (retained.source_target.is_some()
                        && source.target == retained.source_target),
                "retained Move target is missing or changed; refusing to recreate it"
            );
        }
        let profile_id = selection.profile_id.as_deref().unwrap();
        let target_id = selection.target_template_id.as_deref().unwrap();
        let profile = self
            .config
            .profiles
            .get(profile_id)
            .context("unknown destination profile")?;
        ensure!(
            profile.enabled,
            "destination profile {profile_id:?} is disabled"
        );
        if let Some(policy) = &selection.subagents {
            super::profile_config::validate_session_subagent_policy(
                &self.config,
                profile_id,
                policy,
            )
            .await?;
        }
        let target = self
            .config
            .targets
            .get(target_id)
            .context("unknown destination target")?;
        self.validate_muse_resume_destination(source, profile.kind, target_id)?;
        super::worktree::resume_compatibility(source, &self.config, target_id)
            .map_err(anyhow::Error::msg)?;
        super::backend::validate_resource_allocation(
            target,
            selection.resource_allocation.as_ref(),
        )?;
        let mounts = selection.additional_mounts.as_deref().unwrap_or_default();
        ensure!(
            profile.kind != mj_core::config::HarnessKind::Muse || mounts.is_empty(),
            "Muse Code ACP supports one workspace root; attached directories are unsupported"
        );
        ensure!(
            mounts.is_empty() || mj_core::config::mount_history_host(target).is_some(),
            "attached resources are unsupported for this target; select compatible resources explicitly"
        );
        crate::targets::validate_additional_mounts(mounts)?;
        for mount in mounts {
            self.validate_mount_source(target_id, &mount.source, executor)?;
        }
        let planned_conversion =
            self.validate_move_destination_paths(source, target_id, executor)?;
        ensure!(
            profile.home.is_dir(),
            "destination profile home is unavailable; configure the profile before moving"
        );
        super::worker_binary::preflight_worker_binary(target, executor)?;
        super::backend::preflight_target(target, executor, super::backend::TargetCheck::Launch)?;
        let source_harness = previous
            .as_ref()
            .filter(|operation| {
                !operation.queue_admission_started && operation.phase != MovePhase::Completed
            })
            .and_then(|operation| operation.recovery_session.as_ref())
            .map_or(source.harness_kind, |record| record.harness_kind);
        let cross_harness = profile.kind != source_harness;
        if cross_harness {
            let cancel = tokio_util::sync::CancellationToken::new();
            let resolve =
                crate::utility_llm::UtilityLlmRuntime::shared().resolve(&self.config, &cancel);
            tokio::pin!(resolve);
            loop {
                tokio::select! {
                    result = &mut resolve => { result.context("cross-harness move needs an available utility model")?; break; }
                    _ = tokio::time::sleep(std::time::Duration::from_millis(50)) => {
                        if executor.cancellation_requested() { cancel.cancel(); bail!("move preparation cancelled"); }
                    }
                }
            }
        }
        // What moving a local checkout into a target really does, computed
        // before anything is stopped so a person can confirm it.
        let conversion = planned_conversion
            .map(|conversion| {
                super::worktree::raw_conversion_preview(source, &conversion, executor)
                    .context("describe the move of this checkout into the target")
            })
            .transpose()?
            .map(Box::new);
        let (active, mut queued_commands, fingerprint) =
            self.move_confirmation(&selection, conversion.as_deref())?;
        replace_queued_images_with_placeholders(&mut queued_commands);
        let operation_id = previous
            .as_ref()
            .filter(|operation| {
                operation.selection == selection
                    && operation.phase != MovePhase::Completed
                    && operation.restore_artifact().is_some()
            })
            .map(|operation| operation.operation_id.clone())
            .unwrap_or(new_command_id("move")?);
        let in_place = previous
            .as_ref()
            .is_some_and(|op| retry && op.in_place && op.selection == selection)
            || in_place_move_eligible(
                source,
                &selection,
                &self.config.targets,
                self.state.subagents.contains_key(&source.id),
                retry,
            );
        let workspace = if in_place {
            None
        } else {
            Some(self.assess_move_workspace(&selection, executor)?)
        };
        Ok(MovePreparation {
            workspace,
            source_unavailable: false,
            in_place,
            conversion,
            selection,
            source_profile_id: source.last_profile.clone(),
            source_target_template_id: source.target_template_id.clone(),
            cross_harness,
            active,
            queued_commands,
            fingerprint,
            operation_id,
        })
    }

    /// Called with one daemon lifecycle and recovery reservation already held.
    pub async fn move_session_managed_controlled(
        &mut self,
        request: MoveSessionRequest,
        executor: &(impl CommandExecutor + Sync),
        manager: &SessionManagerControl,
    ) -> Result<MoveOutcome> {
        let prepared = &request.preparation;
        let id = prepared.selection.session_id.clone();
        let started = std::time::Instant::now();
        executor.notify_notice("Checking destination");
        let mut source_relay = MoveSourceRelay::default();
        let checked = {
            let _checking_destination =
                ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
            let mut checked = self
                .prepare_move_session_controlled(prepared.selection.clone(), executor)
                .await?;
            // Destination checks can outlast a turn. Confirm against the relay
            // immediately before interruption, and hold its connection from
            // here until the checkpoint seals the source, so nothing reaches
            // the relay between this confirmation and the interruption.
            if matches!(
                self.state.sessions[&id].state,
                SessionState::Running | SessionState::Disconnected
            ) {
                let source_harness = self.state.sessions[&id].harness_kind;
                source_relay = MoveSourceRelay::lease(manager, &id).await?;
                let snapshot = source_relay.snapshot();
                let (active, queue, fingerprint) =
                    self.move_confirmation(&checked.selection, checked.conversion.as_deref())?;
                checked.source_unavailable = snapshot
                    .as_ref()
                    .is_none_or(|snapshot| !snapshot.operational.native_session_is_ready());
                checked.active = active
                    || checked.source_unavailable
                    || snapshot.as_ref().is_some_and(|snapshot| {
                        let mut operational = snapshot.operational.clone();
                        operational.queued_prompts.clear();
                        operational.checkpoint_barrier = None;
                        !operational.safe_to_replace(source_harness)
                    });
                if let Some(snapshot) = &snapshot {
                    self.validate_move_destination_configuration(
                        &checked.selection,
                        source_harness,
                        &snapshot.operational,
                    )
                    .await?;
                }
                checked.queued_commands = queue;
                checked.fingerprint = fingerprint;
            }
            checked
        };
        ensure!(
            checked.fingerprint == prepared.fingerprint,
            "session, pending work, or destination configuration changed; prepare and confirm Move again"
        );
        let queue = request.queue.unwrap_or(ResumeQueueDisposition::Discard);
        let source = self.state.sessions[&id].clone();
        if let Some(assessment) = &checked.workspace {
            checked.selection.workspace.validate(assessment)?;
        }
        let old_operation = crate::database::load_move_operation(&id)?;
        let retry = old_operation.filter(|op| {
            op.selection == prepared.selection
                && op.phase != MovePhase::Completed
                && op.restore_artifact().is_some()
        });
        if retry.is_none()
            && source.state == SessionState::Running
            && source.last_profile == checked.selection.profile_id.as_deref().unwrap()
            && move_environment_change(&source, &checked.selection, false).is_none()
        {
            return Ok(outcome(
                &prepared.operation_id,
                &prepared.selection,
                "unchanged",
                None,
                None,
            ));
        }
        ensure!(
            !checked.active || request.acknowledge_interruption,
            "active work will be interrupted; confirm Move again with interruption acknowledgement"
        );
        ensure!(
            checked.queued_commands.is_empty() || request.queue.is_some(),
            "pending work requires an explicit queue choice: discard or start"
        );
        let timestamp = now();
        let mut operation = match retry {
            Some(mut op) => {
                ensure!(
                    !op.queue_admission_started || op.queue == queue,
                    "queued work may already have run; retry with the original queue choice on the same destination"
                );
                crate::database::clear_move_cancellation_for_retry(&id)?;
                op.configuration_fingerprint =
                    self.move_configuration_fingerprint(&checked.selection)?;
                op.queue = queue;
                op.cancellation_requested = false;
                op.error = None;
                op
            }
            None => MoveOperation {
                workspace_transfer: if checked.in_place {
                    None
                } else {
                    Some(
                        self.new_workspace_transfer(
                            &id,
                            &prepared.operation_id,
                            checked
                                .workspace
                                .clone()
                                .context("Move workspace assessment missing")?,
                            executor,
                        )?,
                    )
                },
                handoff: None,
                source_checkpoint_only: false,
                in_place: in_place_move_eligible(
                    &source,
                    &checked.selection,
                    &self.config.targets,
                    self.state.subagents.contains_key(&id),
                    false,
                ),
                operation_id: prepared.operation_id.clone(),
                selection: checked.selection.clone(),
                source_profile_id: source.last_profile.clone(),
                source_target_template_id: source.target_template_id.clone(),
                source_target: source.target.clone(),
                source_native_session_id: source.native_session_id.clone(),
                source_additional_mounts: source.additional_mounts.clone(),
                source_resource_allocation: source.resource_allocation.clone(),
                destination_target: None,
                destination_native_session_id: None,
                destination_store_id: None,
                configuration_fingerprint: self
                    .move_configuration_fingerprint(&checked.selection)?,
                checkpoint: None,
                recovery_session: None,
                queue,
                phase: MovePhase::Preparing,
                queue_admission_started: false,
                queue_admission_finished: false,
                cancellation_requested: false,
                created_at: timestamp.clone(),
                updated_at: timestamp,
                error: None,
            },
        };
        crate::database::save_move_operation(&operation)?;
        tracing::info!(
            session_id = id,
            in_place = operation.in_place,
            reason = move_environment_change(
                &source,
                &checked.selection,
                bare_targets_share_environment(
                    &self.config.targets,
                    &source.target_template_id,
                    checked
                        .selection
                        .target_template_id
                        .as_deref()
                        .unwrap_or_default(),
                ),
            )
            .unwrap_or(if operation.in_place {
                "environment unchanged"
            } else {
                "source environment unavailable or previously released"
            }),
            "move environment decision"
        );
        tracing::info!(
            session_id = id,
            phase = "preflight",
            elapsed_ms = started.elapsed().as_millis() as u64,
            "move phase completed"
        );
        // Move nests checkpoint and restore state machines. Heap-own their
        // futures so dev builds fit the runtime's ordinary thread stacks.
        let result = Box::pin(self.execute_move(
            &mut operation,
            Some(&checked),
            executor,
            manager,
            source_relay,
        ))
        .await;
        self.finish_move_result(&mut operation, result, executor)
    }

    fn finish_move_result(
        &self,
        operation: &mut MoveOperation,
        result: Result<()>,
        executor: &impl CommandExecutor,
    ) -> Result<MoveOutcome> {
        if result.is_err()
            && operation.workspace_transfer.is_some()
            && !crate::upgrade::gate().is_open()
        {
            // Handoff cancellation is not user cancellation. Leave the durable
            // phase active so the next daemon resumes the accepted Move.
            return Ok(outcome(
                &operation.operation_id,
                &operation.selection,
                "interrupted",
                None,
                Some("Move will continue after the daemon upgrade".into()),
            ));
        }
        let (status, error, recovery) = match result {
            Ok(()) => {
                operation.phase = MovePhase::Completed;
                ("completed", None, None)
            }
            Err(error) => {
                let cancelled =
                    executor.cancellation_requested() || operation.cancellation_requested;
                operation.phase = if cancelled {
                    MovePhase::Cancelled
                } else {
                    MovePhase::Failed
                };
                operation.cancellation_requested = cancelled;
                let recovery = failed_move_recovery(
                    operation,
                    self.state.sessions.get(&operation.selection.session_id),
                );
                let error = format!("{error:#}");
                operation.error = Some(error.clone());
                (
                    if cancelled { "cancelled" } else { "failed" },
                    Some(error),
                    Some(recovery),
                )
            }
        };
        operation.updated_at = now();
        crate::database::save_move_operation(operation)?;
        Ok(outcome(
            &operation.operation_id,
            &operation.selection,
            status,
            error,
            recovery,
        ))
    }

    pub async fn recover_move_managed_controlled(
        &mut self,
        mut operation: MoveOperation,
        executor: &(impl CommandExecutor + Sync),
        manager: &SessionManagerControl,
    ) -> Result<MoveOutcome> {
        let id = operation.selection.session_id.clone();
        let result = async {
            let session = self.state.sessions.get(&id).context("move session is missing")?.clone();
            if operation.queue_admission_started {
                ensure!(!operation.cancellation_requested, "Move was cancelled; destination retained without further queue admission");
                self.finish_workspace_transfer(&mut operation, executor)?;
                return self.admit_move_queue(&mut operation, executor).await;
            }
            if operation.workspace_transfer.is_some() && operation.recovery_session.is_some() && !operation.cancellation_requested
                && !(operation.phase == MovePhase::ResumingDestination && session.state == SessionState::Running) {
                if session.state == SessionState::Provisioning || session.target != operation.source_target {
                    self.rollback_move_destination(&operation, anyhow::anyhow!("resume interrupted Move transfer"), executor)?;
                }
                return Box::pin(self.execute_move(&mut operation, None, executor, manager, MoveSourceRelay::default())).await;
            }
            if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
                let cleanup = crate::targets::CancellableProcessExecutor::with_timeout(std::time::Duration::from_secs(15));
                Box::pin(self.recover_move_source_stop(&mut operation, &cleanup, manager)).await?;
                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
                if operation.retains_source_environment() && self.state.sessions[&id].state == SessionState::Closing {
                    let previous = self.state.sessions[&id].clone();
                    operation.recovery_session = Some(previous.clone());
                    let cause = anyhow::anyhow!("Move source sealed; environment retained for explicit retry");
                    return Err(self.retain_failed_in_place_move(&id, &previous, cause)?);
                }
                if !operation.retains_source_environment() && self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
                    self.cleanup_stopped_target(&id, &cleanup)?;
                }
                bail!("{}", interrupted_source_stop_message(
                    "Move source stop recovered; no destination work was started. Retry Move or Resume with previous settings",
                    operation.in_place,
                ));
            }
            match operation.phase {
                MovePhase::Preparing => bail!("Move preparation was interrupted; source retained. Prepare Move again."),
                MovePhase::ResumingDestination if session.state == SessionState::Running => {
                    // Running is installed only after native readiness and the
                    // handoff. A crash before the next intent write is safe to
                    // advance, since restore started with an empty queue.
                    ensure!(Some(&session.last_profile) == operation.selection.profile_id.as_ref()
                        && Some(&session.target_template_id) == operation.selection.target_template_id.as_ref(),
                        "ready destination does not match the move intent");
                    operation.destination_target = session.target.clone();
                    operation.destination_native_session_id = session.native_session_id.clone();
                    operation.queue_admission_started = true;
                    operation.phase = MovePhase::StartingQueue;
                    crate::database::save_move_operation(&operation)?;
                    restore_move_queue_hold(&operation);
                    ensure!(!operation.cancellation_requested, "Move was cancelled; ready destination retained");
                    self.finish_workspace_transfer(&mut operation, executor)?;
                    self.admit_move_queue(&mut operation, executor).await
                }
                MovePhase::ResumingDestination => {
                    let previous = operation.recovery_session.as_ref().context("move lacks its stopped recovery identity; retain resources for inspection")?;
                    // The retained environment belongs to this Move, even
                    // when only part of its worker installation completed.
                    let cause = anyhow::anyhow!("destination restoration was interrupted; checkpoint retained for an explicit retry");
                    let error = if operation.in_place {
                        self.retain_failed_in_place_move(&id, previous, cause)?
                    } else if operation.workspace_transfer.is_some() {
                        self.rollback_move_destination(&operation, cause, executor)?
                    } else {
                        self.rollback_failed_resume(&id, previous, false, cause, executor)?
                    };
                    Err(error)
                }
                MovePhase::ClosingSource => {
                    if matches!(session.state, SessionState::Closing | SessionState::Destroying) {
                        Box::pin(self.recover_move_source_stop(&mut operation, executor, manager)).await?;
                    }
                    operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
                    if !operation.retains_source_environment() && self.state.sessions[&id].state == SessionState::Stopped && self.state.sessions[&id].target.is_some() {
                        self.cleanup_stopped_target(&id, executor)?;
                    }
                    bail!("{}", interrupted_source_stop_message(
                        "source stop was recovered; verified checkpoint retained. Retry move or Resume with previous settings",
                        operation.in_place,
                    ))
                }
                _ => bail!("Move requires an explicit retry after the daemon restarted"),
            }
        }.await;
        self.finish_move_result(&mut operation, result, executor)
    }

    async fn recover_move_source_stop(
        &mut self,
        operation: &mut MoveOperation,
        executor: &(impl CommandExecutor + Sync),
        manager: &SessionManagerControl,
    ) -> Result<()> {
        let id = operation.selection.session_id.clone();
        if self.state.sessions[&id].state == SessionState::Closing {
            self.prepare_move_source_checkpoint(
                &id,
                executor,
                manager,
                operation,
                &mut MoveSourceRelay::default(),
            )
            .await?;
            let handle = manager
                .wait_for_session(&id, std::time::Duration::from_secs(5))
                .await?;
            let mut lease = handle.lease_connection().await?;
            let execution = lease.connection_mut().sync().await?.operational.execution;
            if operation.retains_source_environment()
                && matches!(
                    execution,
                    mj_core::relay::RelayExecutionState::Closing
                        | mj_core::relay::RelayExecutionState::Closed
                )
            {
                super::checkpoint::wait_for_relay_closed(lease.connection_mut()).await?;
                lease.release();
                ensure!(
                    operation.restore_artifact().is_some()
                        || self.state.sessions[&id].checkpoint.is_some(),
                    "sealed Move source has no checkpoint"
                );
                return Ok(());
            }
            lease.release();
            if matches!(
                execution,
                mj_core::relay::RelayExecutionState::Idle
                    | mj_core::relay::RelayExecutionState::Running
            ) {
                if operation.cancellation_requested || operation.retains_source_environment() {
                    let record = self.state.sessions.get_mut(&id).unwrap();
                    record.state = SessionState::Running;
                    record.updated_at = now();
                    record.last_error = Some(
                        "Move was interrupted before the source was sealed; source retained".into(),
                    );
                    crate::database::save_lifecycle_session(record)?;
                } else {
                    // Fresh-environment moves finish their admitted source stop.
                    Box::pin(self.suspend_session_for_move(
                        &id,
                        executor,
                        manager,
                        operation,
                        None,
                        SourceTargetDisposition::Destroy,
                        MoveSourceRelay::default(),
                    ))
                    .await?;
                }
                return Ok(());
            }
        }
        ensure!(
            !operation.retains_source_environment(),
            "retained Move source cannot be proven; refusing target teardown"
        );
        // A move's source stop was admitted by the move itself.
        self.recover_interrupted_close_managed(&id, executor, manager, true, None)
            .await?;
        Ok(())
    }

    /// `source_relay` is the source connection the Move confirmed against,
    /// held until the checkpoint that seals the source takes it over.
    async fn execute_move(
        &mut self,
        operation: &mut MoveOperation,
        preparation: Option<&MovePreparation>,
        executor: &(impl CommandExecutor + Sync),
        manager: &SessionManagerControl,
        mut source_relay: MoveSourceRelay,
    ) -> Result<()> {
        let id = operation.selection.session_id.clone();
        ensure!(
            !executor.cancellation_requested(),
            "move cancelled before source interruption"
        );
        if !operation.queue_admission_started {
            if operation.in_place {
                ensure!(
                    operation.source_target.is_some()
                        && self.state.sessions[&id].target == operation.source_target,
                    "retained Move target is missing or changed; refusing to recreate the environment"
                );
            }
            if self.state.sessions[&id].state == SessionState::Error
                && let Some(previous) = operation.recovery_session.as_ref()
            {
                // A prior failed teardown retains its exact partial checkout.
                // Restore source identity only after that owner is stopped.
                let cause = anyhow::anyhow!("clean up the partial Move destination before retry");
                if operation.in_place {
                    self.retain_failed_in_place_move(&id, previous, cause)?;
                    let record = self.state.sessions.get_mut(&id).unwrap();
                    record.state = SessionState::Closing;
                    crate::database::save_resumed_session(record, None)?;
                } else if operation.workspace_transfer.is_some() {
                    self.rollback_move_destination(operation, cause, executor)?;
                    let record = self.state.sessions.get_mut(&id).unwrap();
                    record.state = SessionState::Closing;
                    crate::database::save_resumed_session(record, None)?;
                } else {
                    let failure =
                        self.rollback_failed_resume(&id, previous, false, cause, executor)?;
                    ensure!(
                        self.state.sessions[&id].state == SessionState::Stopped,
                        "{failure:#}"
                    );
                }
            }
            let state = self.state.sessions[&id].state;
            if matches!(state, SessionState::Closing | SessionState::Destroying)
                && !(operation.retains_source_environment() && operation.recovery_session.is_some())
            {
                Box::pin(self.recover_move_source_stop(operation, executor, manager)).await?;
                operation.checkpoint = self.state.sessions[&id].checkpoint.clone();
            }
            if matches!(
                self.state.sessions[&id].state,
                SessionState::Running | SessionState::Disconnected
            ) && operation.destination_target.is_none()
            {
                executor.notify_notice("Stopping source");
                let _timing = MovePhaseTimer::new(&id, "checkpoint and source stop");
                operation.phase = MovePhase::ClosingSource;
                operation.updated_at = now();
                crate::database::save_move_operation(operation)?;
                // An eligible move keeps its environment: the close stops at
                // the sealed relay and the record keeps its target for
                // `restore_session_in_place`.
                let disposition = if operation.in_place {
                    SourceTargetDisposition::RetainForInPlaceSwap
                } else {
                    SourceTargetDisposition::Destroy
                };
                Box::pin(self.suspend_session_for_move(
                    &id,
                    executor,
                    manager,
                    operation,
                    preparation,
                    disposition,
                    std::mem::take(&mut source_relay),
                ))
                .await?;
            }
            // Past the source stop, nothing else needs the source's connection.
            drop(source_relay);
            // An in-place move never reaches `Stopped` with a target: its
            // source stays `Closing` in the environment the destination reuses.
            if !operation.in_place
                && operation.workspace_transfer.is_none()
                && self.state.sessions[&id].state == SessionState::Stopped
                && self.state.sessions[&id].target.is_some()
            {
                executor.notify_notice("Cleaning up source");
                let _timing = MovePhaseTimer::new(&id, "source storage cleanup");
                self.cleanup_stopped_target(&id, executor)?;
            }
            operation.checkpoint = operation
                .checkpoint
                .clone()
                .or_else(|| self.state.sessions[&id].checkpoint.clone());
            ensure!(
                operation.restore_artifact().is_some(),
                "move has no verified checkpoint"
            );
            ensure!(
                !executor.cancellation_requested(),
                "move cancelled after source sealing; checkpoint and remaining environment retained"
            );
            operation.phase = MovePhase::ResumingDestination;
            operation.recovery_session = Some(self.state.sessions[&id].clone());
            operation.updated_at = now();
            crate::database::save_move_operation(operation)?;
            executor.reserve_move_destination();
            executor.notify_notice("Preparing destination");
            // The destination worker reads its delegation policy from the
            // record at launch. `recovery_session` above keeps the old one
            // for a rollback.
            if let Some(policy) = &operation.selection.subagents {
                let session = self.state.sessions.get_mut(&id).unwrap();
                session.subagents = Some(policy.clone());
                crate::database::save_resumed_session(session, None)?;
            }
            if operation.in_place {
                // The environment is kept, so there is nothing to provision and
                // no allocation to clear: eligibility already required the
                // allocation to be unchanged.
                Box::pin(self.restore_session_in_place(
                    &id,
                    operation.selection.profile_id.as_deref().unwrap(),
                    operation.selection.target_template_id.as_deref().unwrap(),
                    executor,
                ))
                .await?;
            } else {
                if operation.selection.clear_resource_allocation {
                    let session = self.state.sessions.get_mut(&id).unwrap();
                    session.resource_allocation = None;
                    session.container_cpus = None;
                    session.container_memory = None;
                    crate::database::save_resumed_session(session, None)?;
                }
                if operation.workspace_transfer.is_some() {
                    self.capture_move_workspace(operation, executor)?;
                    Box::pin(self.resume_session_for_move(operation, executor)).await?;
                    operation.workspace_transfer = crate::database::load_move_operation(&id)?
                        .context("Move intent disappeared during restore")?
                        .workspace_transfer;
                } else {
                    Box::pin(self.resume_session_controlled(
                        &id,
                        operation.selection.profile_id.as_deref().unwrap(),
                        operation.selection.target_template_id.as_deref().unwrap(),
                        SessionResumeOptions {
                            additional_mounts: operation.selection.additional_mounts.clone(),
                            resource_allocation: operation.selection.resource_allocation.clone(),
                            discard_queue: true,
                        },
                        executor,
                    ))
                    .await?;
                }
            }
            let destination = &self.state.sessions[&id];
            operation.destination_target = destination.target.clone();
            operation.destination_native_session_id = destination.native_session_id.clone();
            // Persist readiness before submitting even the first queued command.
            operation.phase = MovePhase::StartingQueue;
            operation.queue_admission_started = true;
            operation.updated_at = now();
            crate::database::save_move_operation(operation)?;
        }
        restore_move_queue_hold(operation);
        self.finish_workspace_transfer(operation, executor)?;
        self.admit_move_queue(operation, executor).await
    }

    async fn admit_move_queue(
        &self,
        operation: &mut MoveOperation,
        executor: &(impl CommandExecutor + Sync),
    ) -> Result<()> {
        let timing_id = operation.selection.session_id.clone();
        let _timing = MovePhaseTimer::new(&timing_id, "queue admission");
        let id = &operation.selection.session_id;
        let mut relay = {
            let _checking_destination =
                ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
            let destination = &self.state.sessions[id];
            ensure!(
                destination.state == SessionState::Running
                    && destination.target == operation.destination_target
                    && destination.native_session_id == operation.destination_native_session_id,
                "cannot prove the same ready destination; refusing to replay potentially executed work"
            );
            let spec = self.reconnect_command(id)?;
            let relay = StandaloneSession::connect_command(&spec, id).await?;
            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")?;
            if let Some(expected) = &operation.destination_store_id {
                ensure!(
                    *expected == store_id,
                    "destination relay storage was replaced; refusing to replay potentially executed work"
                );
            } else {
                // No command can be admitted until this identity is durable.
                operation.destination_store_id = Some(store_id);
                crate::database::save_move_operation(operation)?;
            }
            ensure!(
                relay.snapshot().operational.native_session_id
                    == operation.destination_native_session_id,
                "destination relay native identity changed; refusing queue replay"
            );
            relay
        };
        if operation.queue == ResumeQueueDisposition::Start {
            let _starting_queue = ProvisionStageGuard::new(executor, ProvisionStage::Starting);
            executor.notify_notice("Starting queued work");
            let checkpoint = operation
                .restore_artifact()
                .context("move queue archive is missing")?;
            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
            ensure!(
                verified.archive_sha256 == checkpoint.sha256 && verified.manifest.session.id == *id,
                "move queue checkpoint verification failed"
            );
            for queued in verified.canonical_session.queued_prompts {
                if operation.queue_admission_finished {
                    continue;
                }
                ensure!(
                    !executor.cancellation_requested(),
                    "move cancelled during queue admission; destination retained"
                );
                let command = match queued.kind {
                    CanonicalQueuedCommandKind::Prompt => RelayCommand::Prompt {
                        prompt: queued
                            .content
                            .into_iter()
                            .map(serde_json::from_value)
                            .collect::<serde_json::Result<_>>()?,
                    },
                    CanonicalQueuedCommandKind::SetConfig { key, value } => {
                        RelayCommand::SetConfig { key, value }
                    }
                };
                relay.submit_accepted(queued.command_id, command).await?;
            }
        }
        operation.queue_admission_finished = true;
        crate::database::save_move_operation(operation)?;
        restore_move_queue_hold(operation);
        let queue_sentence = if operation.queue == ResumeQueueDisposition::Discard {
            "Queued work was discarded; ready and idle."
        } else {
            "Queued work was accepted."
        };
        let source_profile = &operation.source_profile_id;
        let source_target = &operation.source_target_template_id;
        let destination_profile = operation.selection.profile_id.as_deref().unwrap();
        let destination_target = operation.selection.target_template_id.as_deref().unwrap();
        // The two moves are different events for the person reading the
        // conversation: one rebuilt the environment, the other kept it.
        let text = if operation.in_place {
            format!(
                "Switched from {source_profile} / {source_target} to {destination_profile} / {destination_target} in place; the workspace and environment were kept. {queue_sentence} The interrupted prompt was not replayed."
            )
        } else {
            format!(
                "Moved from {source_profile} / {source_target} to {destination_profile} / {destination_target} in a fresh environment. {queue_sentence} The interrupted prompt was not replayed."
            )
        };
        relay
            .submit(
                format!("{}-notice", operation.operation_id),
                RelayCommand::RecordNotice { text },
            )
            .await?;
        Ok(())
    }

    pub(super) fn validate_move_checkpoint(
        &self,
        operation: &MoveOperation,
        preparation: Option<&MovePreparation>,
        executor: &(impl CommandExecutor + Sync),
    ) -> Result<()> {
        let _verifying = ProvisionStageGuard::new(executor, ProvisionStage::Verifying);
        let current = Controller {
            config: mj_core::config::Config::load()?,
            state: self.state.clone(),
        };
        ensure!(
            current.move_configuration_fingerprint(&operation.selection)?
                == operation.configuration_fingerprint,
            "destination configuration changed during move"
        );
        let id = &operation.selection.session_id;
        current.validate_move_destination_paths(
            &self.state.sessions[id],
            operation.selection.target_template_id.as_deref().unwrap(),
            executor,
        )?;
        if !operation.in_place
            && operation.workspace_transfer.is_none()
            && let super::ResumeRepositorySourcePreflight::RepositoryMoved(mismatch) = self
                .preflight_resume_repository_sources(
                    id,
                    operation.selection.target_template_id.as_deref().unwrap(),
                    executor,
                )?
        {
            bail!(
                "destination repository source is missing checkpoint commit {}; source retained",
                mismatch.missing_commit
            );
        }
        if let Some(prepared) = preparation {
            let checkpoint = operation
                .restore_artifact()
                .or(self.state.sessions[id].checkpoint.as_ref())
                .context("no move checkpoint")?;
            let verified = verify_archive_streaming(&checkpoint.archive_path)?;
            let actual: Vec<_> = verified
                .canonical_session
                .queued_prompts
                .iter()
                .map(|p| p.command_id.as_str())
                .collect();
            let expected: Vec<_> = prepared
                .queued_commands
                .iter()
                .map(|p| p.command_id.as_str())
                .collect();
            ensure!(
                actual == expected,
                "pending queue changed before checkpoint capture; source retained, confirm Move again"
            );
        }
        Ok(())
    }
}

fn validate_preserved_configuration(
    profile_id: &str,
    accepted: &mj_core::acp::AcceptedSessionConfig,
    choices: &mj_core::worker_launch::ProfileConfig,
) -> Result<()> {
    for (key, value, offered) in [
        ("model", accepted.model.as_deref(), &choices.models),
        ("effort", accepted.effort.as_deref(), &choices.efforts),
    ] {
        let Some(value) = value else { continue };
        ensure!(
            offered.iter().any(|choice| choice.value == value),
            "destination profile {profile_id:?} does not offer the session's accepted {key} {value:?}; choices: {}",
            offered
                .iter()
                .map(|choice| choice.value.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        );
    }
    Ok(())
}

/// Whether this move can replace only the harness inside the source target.
///
/// The environment is kept only when nothing about it changes: the same target
/// template (or another one that names the same bare machine), the same
/// attached mounts, and the same resource allocation. A retry takes its retention decision from the durable Move intent instead;
/// a sub-agent never owns its own target.
pub(super) fn in_place_move_eligible(
    source: &mj_core::state::SessionRecord,
    selection: &MoveSelection,
    targets: &std::collections::BTreeMap<String, mj_core::config::TargetTemplate>,
    is_subagent: bool,
    retry: bool,
) -> bool {
    !retry
        && !is_subagent
        && source.target.is_some()
        && matches!(
            source.state,
            SessionState::Running | SessionState::Disconnected
        )
        && move_environment_change(
            source,
            selection,
            bare_targets_share_environment(
                targets,
                &source.target_template_id,
                selection.target_template_id.as_deref().unwrap_or_default(),
            ),
        )
        .is_none()
}

/// Whether two target templates are bare targets on the same machine, so the
/// session's worker root and workspace are already where the destination wants
/// them. Two local bare targets qualify, and so do two SSH bare targets with
/// the same connection; only the template the session names changes.
fn bare_targets_share_environment(
    targets: &std::collections::BTreeMap<String, mj_core::config::TargetTemplate>,
    source_id: &str,
    destination_id: &str,
) -> bool {
    use mj_core::config::TargetTemplate::{LocalBare, SshBare};
    match (targets.get(source_id), targets.get(destination_id)) {
        (Some(LocalBare), Some(LocalBare)) => true,
        (
            Some(SshBare { ssh: source, .. }),
            Some(SshBare {
                ssh: destination, ..
            }),
        ) => {
            crate::targets::SshTarget::from(source) == crate::targets::SshTarget::from(destination)
        }
        _ => false,
    }
}
fn outcome(
    operation_id: &str,
    selection: &MoveSelection,
    status: &str,
    error: Option<String>,
    recovery: Option<String>,
) -> MoveOutcome {
    MoveOutcome {
        operation_id: operation_id.into(),
        session_id: selection.session_id.clone(),
        profile_id: selection.profile_id.clone().unwrap_or_default(),
        target_template_id: selection.target_template_id.clone().unwrap_or_default(),
        outcome: status.into(),
        error,
        recovery,
    }
}

/// One decision shared by no-op detection and environment retention. A
/// different target template counts as a change unless `same_environment` says
/// the two name the same bare machine.
fn move_environment_change(
    source: &mj_core::state::SessionRecord,
    selection: &MoveSelection,
    same_environment: bool,
) -> Option<&'static str> {
    if Some(&source.target_template_id) != selection.target_template_id.as_ref()
        && !same_environment
    {
        Some("target changed")
    } else if Some(&source.additional_mounts) != selection.additional_mounts.as_ref() {
        Some("attached mounts changed")
    } else if source.resource_allocation != selection.resource_allocation
        || (selection.clear_resource_allocation
            && (source.container_cpus.is_some() || source.container_memory.is_some()))
    {
        Some("resource allocation changed")
    } else {
        None
    }
}