surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
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
//! Stop managing (M57, SPEC 8.10, `surject eject`): hand everything Surjection
//! owns on this machine back to the clients, so they keep working with
//! Surjection uninstalled.
//!
//! - Every owned MCP entry is kept byte for byte when it does not start
//!   `surject`, and rewritten into the client's own form when it does
//!   ([`rewrite`]): the `surject exec` launcher unwrapped, `!command` hooks
//!   and `headersHelper` replaced by variable references, or the value left
//!   out for the user to paste when the client cannot read the environment
//!   there. No secret value is ever written.
//! - Skill links into the store become real copies; the Surjection agent skill
//!   is removed unless kept.
//! - Ownership is dropped, and `state/eject.json` ([`record`]) keeps the
//!   planner, instant apply and skill sync away from what was handed back
//!   until the user starts managing again ([`resume`]).
//! - Writes go like an apply's (backup, self check, compare-and-swap); a
//!   read-only target is blocked and stays owned. [`rollback`] brings the
//!   files and ownership back.
//!
//! The store and its history are never changed.

mod record;
mod rewrite;

use std::collections::{BTreeMap, HashSet};
use std::path::{Path, PathBuf};

use sha2::{Digest, Sha256};

use crate::access::{self, ReadOnlyKind};
use crate::adapters::adapter;
use crate::apply::exec::{document_value, strip_container, swap_file};
use crate::apply::ledger::{EntryKind, LedgerEntry};
use crate::apply::plan::{canonical, list_members, read_target};
use crate::apply::{ApplyEnv, backup};
use crate::error::{CoreError, ErrorCode};
use crate::formats::{Document, NativeValue};
use crate::fs::Fs;
use crate::layering::{TrustStore, known_projects, same_folder, same_path};
use crate::model::applied::Scope;
use crate::model::ids;
use crate::paths::SurjectionHome;
use crate::secrets::catalog::Catalog;
use crate::skills::link::{
    self, LinkMethod, SkillLedger, SkillLink, SyncReport, marker_text, remove_copy, remove_link,
    unchanged_copy,
};
use crate::skills::{
    Entry, LEGACY_MARKER_FILE, MARKER_FILE, SkillsEnv, confine, content_hash, entry,
    new_folder_access, read_folder, write_files,
};
use crate::store::{LOCK_TIMEOUT, Machine, Store, StoreLock, utc_datetime};

#[cfg(test)]
pub(crate) use record::EJECT_SCHEMA;
pub use record::{
    ActiveRun, CopiedSkill, EJECT_FILE, EjectFile, EjectRun, Ejected, EjectedFile, status_at,
};
pub use rewrite::{EnvNeed, ManualSecret};

use rewrite::{Analysis, Rewriter, Taken};

/// What an eject covers. The default is a dry run over everything.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct EjectOptions {
    /// Only these clients; every client when `None`.
    pub clients: Option<Vec<String>>,
    /// Only the known project rooted here (its files and skill entries, no
    /// user files); everything when `None`.
    pub project: Option<PathBuf>,
    /// Keep the Surjection agent skill in client folders (as a copy).
    pub keep_agent_skill: bool,
    /// Write; without it nothing is written (no lock, no record, no file).
    pub execute: bool,
    /// Failure injection for tests.
    #[doc(hidden)]
    pub hooks: EjectHooks,
}

/// Failure injection for tests: where a run stops as if the process died,
/// or which step fails.
#[doc(hidden)]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct EjectHooks {
    /// Stop (as a crash would) right after this many files were written.
    pub crash_after_files: Option<usize>,
    /// The move of a skill copy into place fails.
    pub fail_skill_move: bool,
}

/// What happens to one owned entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum EntryAction {
    /// No Surjection reference: left byte for byte.
    Keep,
    /// Rewritten into the client's own form.
    Rewrite,
    /// Depends on Surjection but cannot be rewritten safely: left as it is.
    Manual,
    /// No longer in the file.
    Gone,
}

impl EntryAction {
    pub const fn as_str(self) -> &'static str {
        match self {
            EntryAction::Keep => "keep",
            EntryAction::Rewrite => "rewrite",
            EntryAction::Manual => "manual",
            EntryAction::Gone => "gone",
        }
    }
}

/// One owned entry.
#[derive(Debug, Clone)]
pub struct EjectEntry {
    pub client: String,
    pub scope: Scope,
    pub project_id: Option<String>,
    pub name: String,
    pub kind: EntryKind,
    pub action: EntryAction,
    /// Variables to set in the environment the client starts from.
    pub needs_env: Vec<EnvNeed>,
    /// Values left out, for the user to paste.
    pub needs_manual_secret: Vec<ManualSecret>,
    /// The entry holds a path into the data folder (keep the folder, or move
    /// what it points to).
    pub uses_data_folder: bool,
    /// Why the entry is [`EntryAction::Manual`].
    pub problem: Option<CoreError>,
}

/// What happened to a target file.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TargetOutcome {
    /// Dry run: the file would be written.
    Planned,
    /// No write needed (ownership dropped when executed).
    Unchanged,
    Written,
    /// This account cannot write the file: nothing done, still owned.
    Blocked,
    /// Nothing done, still owned; see [`EjectTarget::error`].
    Failed,
}

impl TargetOutcome {
    pub const fn as_str(self) -> &'static str {
        match self {
            TargetOutcome::Planned => "planned",
            TargetOutcome::Unchanged => "unchanged",
            TargetOutcome::Written => "written",
            TargetOutcome::Blocked => "blocked",
            TargetOutcome::Failed => "failed",
        }
    }
}

/// One client file with owned entries.
#[derive(Debug, Clone)]
pub struct EjectTarget {
    /// Clients owning entries in the file, in order of appearance.
    pub clients: Vec<String>,
    pub file: PathBuf,
    /// The project folder of the file's project entries, when known.
    pub project: Option<PathBuf>,
    pub entries: Vec<EjectEntry>,
    pub outcome: TargetOutcome,
    pub backup: Option<PathBuf>,
    pub read_only: Option<ReadOnlyKind>,
    pub error: Option<CoreError>,
    before: Option<Vec<u8>>,
    after: Option<Vec<u8>>,
    format: Option<crate::formats::Format>,
    /// Rewritten entries: container keys, entry key, client, new value.
    rewrites: Vec<(Vec<String>, String, String, NativeValue)>,
    rows: Vec<LedgerEntry>,
}

impl EjectTarget {
    /// Whether the file needs a write.
    pub fn rewrites(&self) -> bool {
        self.after.is_some()
    }
}

/// What happens to one owned skill entry.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum SkillAction {
    /// A link into the store becomes a real folder with the same files.
    Copy,
    /// An owned copy stays (its marker file goes).
    Keep,
    /// The Surjection agent skill: removed.
    Remove,
    /// Edited since, or a link to something else: left as it is.
    Changed,
    /// No longer there.
    Gone,
}

impl SkillAction {
    pub const fn as_str(self) -> &'static str {
        match self {
            SkillAction::Copy => "copy",
            SkillAction::Keep => "keep",
            SkillAction::Remove => "remove",
            SkillAction::Changed => "changed",
            SkillAction::Gone => "gone",
        }
    }
}

/// One owned skill entry.
#[derive(Debug, Clone)]
pub struct EjectSkill {
    pub client: String,
    pub scope: Scope,
    pub project_id: Option<String>,
    pub skill_id: String,
    pub path: PathBuf,
    pub method: LinkMethod,
    pub action: SkillAction,
    /// Whether the action was carried out.
    pub done: bool,
    pub read_only: Option<ReadOnlyKind>,
    pub error: Option<CoreError>,
    row: SkillLink,
}

/// A variable to set, and the entries that read it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvSummary {
    pub name: String,
    pub secret: Option<String>,
    /// The reference the first entry reading it uses.
    pub reference: String,
    /// `client: entry` names.
    pub entries: Vec<String>,
}

/// A value to paste, and where.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ManualSummary {
    pub client: String,
    pub entry: String,
    pub file: PathBuf,
    pub project: Option<PathBuf>,
    pub secret: ManualSecret,
}

/// One variable name two entries need for different secrets: the later
/// entries got the value left out instead (to paste by hand).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnvConflict {
    pub name: String,
    /// The secrets (aliases or references), the one the name stands for
    /// first.
    pub secrets: Vec<String>,
    /// `client: entry` names.
    pub entries: Vec<String>,
}

/// Why something still needs Surjection after the eject.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum StillReason {
    /// The entry still starts `surject` (it could not be rewritten).
    Manual,
    /// The entry runs or reads something in the data folder.
    UsesDataFolder,
    /// The file was left as it is (read only, or its project folder is
    /// missing) and still starts `surject`.
    Blocked,
    /// Writing the file failed; it still starts `surject`.
    Failed,
    /// A skill folder is still a link into the data folder.
    SkillLink,
}

impl StillReason {
    pub const fn as_str(self) -> &'static str {
        match self {
            StillReason::Manual => "manual",
            StillReason::UsesDataFolder => "uses_data_folder",
            StillReason::Blocked => "blocked",
            StillReason::Failed => "failed",
            StillReason::SkillLink => "skill_link",
        }
    }
}

/// Something that still needs Surjection (or its data folder) after the
/// eject: deleting the data folder or uninstalling breaks it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StillNeeded {
    pub client: String,
    /// The entry or skill, `None` for a whole file.
    pub entry: Option<String>,
    /// The client file or skill folder.
    pub file: PathBuf,
    pub project: Option<PathBuf>,
    pub reason: StillReason,
    pub detail: Option<String>,
}

/// The plan, or the result, of an eject.
#[derive(Debug, Clone)]
pub struct EjectReport {
    /// The run id (backups `backups/files/<ts>-<id>/`); `None` for a dry
    /// run.
    pub eject_id: Option<String>,
    pub executed: bool,
    pub targets: Vec<EjectTarget>,
    pub skills: Vec<EjectSkill>,
    /// Whether the run covered everything (the machine is not managed).
    pub all: bool,
    /// An earlier eject that did not finish (roll it back first).
    pub unfinished: Option<String>,
}

impl EjectReport {
    /// Variables to set, by name, with the entries reading each.
    pub fn env(&self) -> Vec<EnvSummary> {
        let mut out: Vec<EnvSummary> = Vec::new();
        for target in &self.targets {
            for entry in &target.entries {
                for need in &entry.needs_env {
                    let label = format!("{}: {}", entry.client, entry.name);
                    match out.iter_mut().find(|summary| summary.name == need.name) {
                        Some(summary) => {
                            if !summary.entries.contains(&label) {
                                summary.entries.push(label);
                            }
                        }
                        None => out.push(EnvSummary {
                            name: need.name.clone(),
                            secret: need.secret.clone(),
                            reference: need.reference.clone(),
                            entries: vec![label],
                        }),
                    }
                }
            }
        }
        out
    }

    /// Names two entries need for different secrets.
    pub fn conflicts(&self) -> Vec<EnvConflict> {
        let env = self.env();
        let mut out: Vec<EnvConflict> = Vec::new();
        for item in self.manual() {
            let Some(name) = &item.secret.conflicts_with else {
                continue;
            };
            let label = format!("{}: {}", item.client, item.entry);
            let conflict = match out.iter_mut().position(|c| &c.name == name) {
                Some(index) => &mut out[index],
                None => {
                    let first = env.iter().find(|summary| &summary.name == name);
                    out.push(EnvConflict {
                        name: name.clone(),
                        secrets: first
                            .map(|s| s.secret.clone().unwrap_or_else(|| s.reference.clone()))
                            .into_iter()
                            .collect(),
                        entries: first.map(|s| s.entries.clone()).unwrap_or_default(),
                    });
                    out.last_mut().expect("pushed")
                }
            };
            if !conflict.secrets.contains(&item.secret.secret) {
                conflict.secrets.push(item.secret.secret.clone());
            }
            if !conflict.entries.contains(&label) {
                conflict.entries.push(label);
            }
        }
        out
    }

    /// Everything that still needs Surjection or its data folder: empty when
    /// uninstalling and deleting the data folder breaks nothing.
    pub fn still_needs_surjection(&self) -> Vec<StillNeeded> {
        let mut out = Vec::new();
        for target in &self.targets {
            let stuck = match target.outcome {
                TargetOutcome::Blocked => Some(StillReason::Blocked),
                TargetOutcome::Failed => Some(StillReason::Failed),
                _ => None,
            };
            let detail = target.error.as_ref().map(|err| err.message().to_owned());
            let mut listed = false;
            for entry in &target.entries {
                let reason = match (stuck, entry.action) {
                    (Some(reason), EntryAction::Rewrite | EntryAction::Manual) => Some(reason),
                    (_, EntryAction::Manual) => Some(StillReason::Manual),
                    _ if entry.uses_data_folder => Some(StillReason::UsesDataFolder),
                    _ => None,
                };
                if let Some(reason) = reason {
                    listed = true;
                    out.push(StillNeeded {
                        client: entry.client.clone(),
                        entry: Some(entry.name.clone()),
                        file: target.file.clone(),
                        project: target.project.clone(),
                        reason,
                        detail: match reason {
                            StillReason::Manual => {
                                entry.problem.as_ref().map(|err| err.message().to_owned())
                            }
                            _ => detail.clone(),
                        },
                    });
                }
            }
            // A file that could not be read or planned: its entries may
            // start `surject`.
            if let (Some(reason), false, None) = (stuck, listed, target.after.as_ref())
                && target.entries.iter().all(|e| e.action == EntryAction::Keep)
                && target.error.is_some()
                && !target.entries.is_empty()
            {
                out.push(StillNeeded {
                    client: target.clients.join(", "),
                    entry: None,
                    file: target.file.clone(),
                    project: target.project.clone(),
                    reason,
                    detail,
                });
            }
        }
        for skill in &self.skills {
            if skill.action == SkillAction::Copy && !(self.executed && skill.done) {
                if !self.executed && skill.error.is_none() {
                    continue;
                }
                out.push(StillNeeded {
                    client: skill.client.clone(),
                    entry: Some(skill.skill_id.clone()),
                    file: skill.path.clone(),
                    project: None,
                    reason: StillReason::SkillLink,
                    detail: skill.error.as_ref().map(|err| err.message().to_owned()),
                });
            }
        }
        out
    }

    /// Values to paste by hand.
    pub fn manual(&self) -> Vec<ManualSummary> {
        let mut out = Vec::new();
        for target in &self.targets {
            for entry in &target.entries {
                for secret in &entry.needs_manual_secret {
                    out.push(ManualSummary {
                        client: entry.client.clone(),
                        entry: entry.name.clone(),
                        file: target.file.clone(),
                        project: target.project.clone(),
                        secret: secret.clone(),
                    });
                }
            }
        }
        out
    }

    /// Whether a file or skill entry failed (a read-only one is blocked,
    /// not failed).
    pub fn failed(&self) -> bool {
        self.targets
            .iter()
            .any(|target| target.outcome == TargetOutcome::Failed)
            || self
                .skills
                .iter()
                .any(|skill| skill.error.is_some() && skill.read_only.is_none())
    }
}

/// The active eject runs of this machine.
pub fn status(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<Ejected>, CoreError> {
    status_at(fs, &home.state_dir())
}

/// Plans an eject and, with [`EjectOptions::execute`], carries it out.
pub fn eject(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    options: &EjectOptions,
) -> Result<EjectReport, CoreError> {
    check_clients(options.clients.as_deref())?;
    let fs = ax.fs;
    let state = ax.home.state_dir();
    let roots = project_roots(store, ax)?;
    let project_id = match &options.project {
        Some(root) => Some(
            roots
                .iter()
                .find(|(_, known)| same_path(known, root))
                .map(|(id, _)| id.clone())
                .ok_or_else(|| {
                    CoreError::new(
                        ErrorCode::NotFound,
                        "the folder is not a project this machine knows",
                    )
                    .with_path(root)
                })?,
        ),
        None => None,
    };
    let catalog = match store {
        Some(store) => {
            let machine = Machine::load(fs, &state)?;
            Catalog::load(store, machine.as_ref().map(|machine| machine.id.as_str()))?
        }
        None => Catalog::default(),
    };
    let _lock = if options.execute {
        Some(StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?)
    } else {
        None
    };
    let mut ledger = SkillLedger::load(fs, &state)?;
    let selected = |client: &str, project: Option<&str>| {
        options
            .clients
            .as_ref()
            .is_none_or(|clients| clients.iter().any(|id| id == client))
            && project_id.as_deref().is_none_or(|id| project == Some(id))
    };
    let rows: Vec<LedgerEntry> = ledger
        .mcp_mut()
        .entries
        .iter()
        .filter(|row| selected(&row.client, row.project_id.as_deref()))
        .cloned()
        .collect();
    let planner = Planner {
        ax,
        catalog: &catalog,
        roots: &roots,
        taken: Taken::default(),
    };
    let mut targets = planner.targets(rows);
    let mut skills: Vec<EjectSkill> = ledger
        .links
        .iter()
        .filter(|link| selected(&link.client, link.project_id.as_deref()))
        .map(|link| plan_skill(fs, link, options.keep_agent_skill))
        .collect();
    let all = options.clients.is_none() && project_id.is_none();
    let mut record = EjectFile::load(fs, &state)?;
    let unfinished = record
        .runs
        .iter()
        .find(|run| !run.finished && !run.rolled_back)
        .map(|run| run.id.clone());
    if !options.execute {
        return Ok(EjectReport {
            eject_id: None,
            executed: false,
            targets,
            skills,
            all,
            unfinished,
        });
    }
    if let Some(open) = &unfinished {
        return Err(unfinished_error(open));
    }

    let now = ax.env.now();
    let id = ids::new_ulid(now)?;
    let mut run = EjectRun {
        id: id.clone(),
        time: utc_datetime(now).to_string(),
        clients: options.clients.clone(),
        project_id: project_id.clone(),
        finished: false,
        resumed: false,
        rolled_back: false,
        files: Vec::new(),
        ledger: Vec::new(),
        skill_links: Vec::new(),
        copied: Vec::new(),
        unmarked: Vec::new(),
        extra: serde_json::Map::new(),
    };
    // The record is the run's journal, saved before every change: the
    // marker first (from here on Surjection stays away from what is being
    // handed back), each file before it is swapped, each copy before it
    // replaces a link, the dropped rows before the ledger forgets them. A
    // run that stops anywhere is rolled back from it.
    record.runs.push(run.clone());
    record.save(fs, &state)?;
    let mut journal = |run: &EjectRun| -> Result<(), CoreError> {
        if let Some(saved) = record
            .runs
            .iter_mut()
            .rev()
            .find(|saved| saved.id == run.id)
        {
            *saved = run.clone();
        }
        record.save(fs, &state)
    };

    let run_dir = backup::run_dir(ax.home, now, &id);
    let mut dropped: Vec<LedgerEntry> = Vec::new();
    let mut written = 0;
    for target in &mut targets {
        execute_target(ax, &run_dir, target, &mut |file| {
            run.files.push(file);
            journal(&run)
        });
        let path = target.file.to_string_lossy().into_owned();
        if target.outcome == TargetOutcome::Written {
            written += 1;
            if options.hooks.crash_after_files == Some(written) {
                return Err(CoreError::new(
                    ErrorCode::IoError,
                    "test hook: the run stopped here",
                ));
            }
        } else if run.files.last().is_some_and(|file| file.file == path) {
            // Journaled, then not written: nothing to roll back there.
            run.files.pop();
        }
        if matches!(
            target.outcome,
            TargetOutcome::Written | TargetOutcome::Unchanged
        ) {
            dropped.extend(target.rows.iter().cloned());
        }
    }
    for skill in &mut skills {
        execute_skill(fs, skill, &mut run, &options.hooks, &mut journal);
        if skill.done {
            ledger.remove(&skill.path);
            run.skill_links.push(skill.row.clone());
        }
    }
    let mcp = ledger.mcp_mut();
    mcp.entries.retain(|row| !dropped.contains(row));
    run.ledger = dropped;
    journal(&run)?;
    ledger.save(fs, &state)?;
    run.finished = true;
    journal(&run)?;
    backup::prune(fs, ax.home, now)?;
    crate::diagnostics::log::event(
        "eject",
        &[
            ("targets", &targets.len()),
            ("writes", &written),
            ("skills", &skills.len()),
        ],
    );
    Ok(EjectReport {
        eject_id: Some(id),
        executed: true,
        targets,
        skills,
        all,
        unfinished: None,
    })
}

fn unfinished_error(id: &str) -> CoreError {
    CoreError::new(
        ErrorCode::UnfinishedApply,
        format!(
            "eject {id} did not finish; roll it back first (`{} rollback {id}`), then run it again",
            crate::brand::BIN_NAME
        ),
    )
}

fn check_clients(clients: Option<&[String]>) -> Result<(), CoreError> {
    for id in clients.into_iter().flatten() {
        if crate::model::clients::known_client(id).is_none() && adapter(id).is_none() {
            return Err(CoreError::new(
                ErrorCode::UnknownClient,
                format!("{id:?} is not a client Surjection knows"),
            ));
        }
    }
    Ok(())
}

/// Known projects of this machine, by id.
fn project_roots(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
) -> Result<BTreeMap<String, PathBuf>, CoreError> {
    let Some(store) = store else {
        return Ok(BTreeMap::new());
    };
    let state = ax.home.state_dir();
    let overlay = crate::layering::projects::this_overlay(store, ax.fs, &state)?;
    let trust = TrustStore::load(ax.fs, &state)?;
    Ok(known_projects(ax.fs, ax.env, overlay.as_ref(), &trust)
        .into_iter()
        .map(|known| (known.id, known.root))
        .collect())
}

struct Planner<'a> {
    ax: &'a ApplyEnv<'a>,
    catalog: &'a Catalog,
    roots: &'a BTreeMap<String, PathBuf>,
    /// Variable names handed out so far, across every file.
    taken: Taken,
}

impl Planner<'_> {
    /// The owned rows grouped by file, each file planned.
    fn targets(&self, rows: Vec<LedgerEntry>) -> Vec<EjectTarget> {
        let mut groups: Vec<(String, Vec<LedgerEntry>)> = Vec::new();
        for row in rows {
            match groups.iter_mut().find(|(file, _)| *file == row.file) {
                Some((_, rows)) => rows.push(row),
                None => groups.push((row.file.clone(), vec![row])),
            }
        }
        let mut targets: Vec<EjectTarget> = groups
            .into_iter()
            .map(|(file, rows)| self.target(PathBuf::from(file), rows))
            .collect();
        let wanted: Vec<(PathBuf, Option<u64>)> = targets
            .iter()
            .filter(|target| target.after.is_some())
            .map(|target| {
                (
                    target.file.clone(),
                    access::fingerprint(target.before.as_deref()),
                )
            })
            .collect();
        if !wanted.is_empty() {
            let found = access::probe_files(self.ax.fs, &wanted, None);
            for target in &mut targets {
                if let Some(kind) = found
                    .get(&target.file)
                    .and_then(|access| access.read_only())
                {
                    target.read_only = Some(kind);
                    target.outcome = TargetOutcome::Blocked;
                    target.error = Some(access::read_only_target(kind, &target.file));
                }
            }
        }
        targets
    }

    fn target(&self, file: PathBuf, rows: Vec<LedgerEntry>) -> EjectTarget {
        let mut clients: Vec<String> = Vec::new();
        for row in &rows {
            if !clients.contains(&row.client) {
                clients.push(row.client.clone());
            }
        }
        let project = rows
            .iter()
            .find_map(|row| row.project_id.as_ref())
            .and_then(|id| self.roots.get(id))
            .cloned();
        let format = rows
            .iter()
            .find_map(|row| adapter(&row.client).and_then(|spec| spec.mcp.as_ref()))
            .map(|mcp| mcp.format);
        let mut target = EjectTarget {
            clients,
            file,
            project,
            entries: Vec::new(),
            outcome: TargetOutcome::Unchanged,
            backup: None,
            read_only: None,
            error: None,
            before: None,
            after: None,
            format,
            rewrites: Vec::new(),
            rows: Vec::new(),
        };
        let fail = |mut target: EjectTarget, rows: &[LedgerEntry], err: CoreError| {
            target.entries = rows
                .iter()
                .map(|row| entry_of(row, EntryAction::Keep))
                .collect();
            target.outcome = TargetOutcome::Failed;
            target.error = Some(err);
            target
        };
        let Some(format) = format else {
            let err = CoreError::new(
                ErrorCode::NoAdapter,
                "no client of this build writes this file; its entries are left as they are",
            )
            .with_path(&target.file);
            return fail(target, &rows, err);
        };
        let bytes = match read_target(self.ax.fs, &target.file) {
            Ok(bytes) => bytes,
            Err(err) => return fail(target, &rows, err),
        };
        let Some(bytes) = bytes else {
            // A project file whose folder is missing (a drive not plugged
            // in, a moved repository) is not gone: it may come back still
            // starting `surject`. It stays owned.
            let project_missing = rows.iter().any(|row| row.project_id.is_some())
                && match &target.project {
                    Some(root) => !self.ax.fs.is_dir(root),
                    None => target
                        .file
                        .parent()
                        .is_none_or(|dir| !self.ax.fs.is_dir(dir)),
                };
            if project_missing {
                target.entries = rows
                    .iter()
                    .map(|row| entry_of(row, EntryAction::Keep))
                    .collect();
                target.outcome = TargetOutcome::Blocked;
                target.error = Some(
                    CoreError::new(
                        ErrorCode::NotFound,
                        "the project folder is missing; its entries stay managed until it is back",
                    )
                    .with_path(&target.file),
                );
                return target;
            }
            target.entries = rows
                .iter()
                .map(|row| entry_of(row, EntryAction::Gone))
                .collect();
            target.rows = rows;
            return target;
        };
        let doc = match Document::parse(&bytes, format) {
            Ok(doc) => doc,
            Err(err) => {
                let err = err.with_path(&target.file);
                return fail(target, &rows, err);
            }
        };
        let mut after_doc = doc.clone();
        for row in &rows {
            match self.entry(&doc, &mut after_doc, row, &mut target.rewrites) {
                Ok(entry) => target.entries.push(entry),
                Err(err) => {
                    let err = err.with_path(&target.file);
                    return fail(target, &rows, err);
                }
            }
        }
        if !target.rewrites.is_empty() {
            let after = after_doc.to_bytes();
            if after != bytes {
                target.after = Some(after);
                target.outcome = TargetOutcome::Planned;
            }
        }
        target.before = Some(bytes);
        target.rows = rows;
        target
    }

    fn entry(
        &self,
        doc: &Document,
        after: &mut Document,
        row: &LedgerEntry,
        rewrites: &mut Vec<(Vec<String>, String, String, NativeValue)>,
    ) -> Result<EjectEntry, CoreError> {
        let keys = pointer_keys(&row.container);
        let container: Vec<&str> = keys.iter().map(String::as_str).collect();
        if row.kind == EntryKind::ListMember {
            let present = list_members(doc, &container)?.contains(&row.key);
            let action = if present {
                EntryAction::Keep
            } else {
                EntryAction::Gone
            };
            return Ok(entry_of(row, action));
        }
        let Some(value) = doc.get(&container, &row.key)? else {
            return Ok(entry_of(row, EntryAction::Gone));
        };
        let Some(spec) = adapter(&row.client).filter(|spec| spec.mcp.is_some()) else {
            return Ok(entry_of(row, EntryAction::Keep));
        };
        let rewriter = Rewriter {
            spec,
            os: self.ax.env.os(),
            catalog: self.catalog,
            launcher: self.ax.delivery.launcher_path(),
            surjection_home: &self.ax.home.path,
            taken: &self.taken,
        };
        let mut entry = entry_of(row, EntryAction::Keep);
        match rewriter.analyze(&row.key, &value) {
            Analysis::Keep { uses_data_folder } => entry.uses_data_folder = uses_data_folder,
            Analysis::Manual(problem) => {
                entry.action = EntryAction::Manual;
                entry.problem = Some(problem);
            }
            Analysis::Rewrite {
                value,
                needs_env,
                manual,
                uses_data_folder,
            } => {
                after.upsert(&container, &row.key, &value)?;
                entry.action = EntryAction::Rewrite;
                entry.needs_env = needs_env;
                entry.needs_manual_secret = manual;
                entry.uses_data_folder = uses_data_folder;
                rewrites.push((keys.clone(), row.key.clone(), row.client.clone(), value));
            }
        }
        Ok(entry)
    }
}

fn entry_of(row: &LedgerEntry, action: EntryAction) -> EjectEntry {
    EjectEntry {
        client: row.client.clone(),
        scope: row.scope,
        project_id: row.project_id.clone(),
        name: row.key.clone(),
        kind: row.kind,
        action,
        needs_env: Vec::new(),
        needs_manual_secret: Vec::new(),
        uses_data_folder: false,
        problem: None,
    }
}

/// The keys of an RFC 6901 pointer (`/projects/C:~1x/mcpServers`).
fn pointer_keys(pointer: &str) -> Vec<String> {
    pointer
        .split('/')
        .skip(1)
        .map(|key| key.replace("~1", "/").replace("~0", "~"))
        .collect()
}

fn sha256(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut out = String::from("sha256:");
    for byte in digest {
        out.push_str(&format!("{byte:02x}"));
    }
    out
}

/// Backup, journal, self check, compare-and-swap write (SPEC 8.4 steps 2
/// to 4). `journal` records the file (its backup and the hash of what is
/// about to be written) before the swap.
fn execute_target(
    ax: &ApplyEnv<'_>,
    run_dir: &Path,
    target: &mut EjectTarget,
    journal: &mut dyn FnMut(EjectedFile) -> Result<(), CoreError>,
) {
    match target.outcome {
        TargetOutcome::Blocked | TargetOutcome::Failed | TargetOutcome::Unchanged => return,
        TargetOutcome::Planned | TargetOutcome::Written => {}
    }
    let (Some(before), Some(after)) = (target.before.clone(), target.after.clone()) else {
        target.outcome = TargetOutcome::Unchanged;
        return;
    };
    let result = self_check(target, &before, &after)
        .and_then(|()| backup::save(ax.fs, ax.home, run_dir, &target.file, &before))
        .and_then(|path| {
            target.backup = Some(path.clone());
            journal(EjectedFile {
                file: target.file.to_string_lossy().into_owned(),
                backup: Some(path.to_string_lossy().into_owned()),
                written: sha256(&after),
            })
        })
        .and_then(|()| swap_file(ax.fs, &target.file, Some(&before), &after));
    match result {
        Ok(true) => target.outcome = TargetOutcome::Written,
        Ok(false) => {
            target.outcome = TargetOutcome::Failed;
            target.error = Some(
                CoreError::new(
                    ErrorCode::FileChangedDuringApply,
                    "the file changed while ejecting; it was left as it is (run eject again)",
                )
                .with_path(&target.file),
            );
        }
        Err(err) => {
            if let Some(kind) = err.read_only() {
                target.read_only = Some(kind);
                target.outcome = TargetOutcome::Blocked;
            } else {
                target.outcome = TargetOutcome::Failed;
            }
            target.error = Some(err);
        }
    }
}

/// The written text parses, rewritten entries read back as planned, and
/// nothing else in the file changed.
fn self_check(target: &EjectTarget, before: &[u8], after: &[u8]) -> Result<(), CoreError> {
    let fail = |detail: String| {
        Err(CoreError::new(ErrorCode::SelfCheckFailed, detail).with_path(&target.file))
    };
    let format = target.format.expect("a planned target has a format");
    let before_doc = Document::parse(before, format)?;
    let after_doc = match Document::parse(after, format) {
        Ok(doc) => doc,
        Err(err) => return fail(format!("the edited file does not parse: {err}")),
    };
    let mut before_root = document_value(&before_doc)?;
    let mut after_root = document_value(&after_doc)?;
    let mut containers: Vec<&Vec<String>> = Vec::new();
    for (keys, _, _, _) in &target.rewrites {
        if !containers.contains(&keys) {
            containers.push(keys);
        }
    }
    for keys in containers {
        let container: Vec<&str> = keys.iter().map(String::as_str).collect();
        let names = before_doc.list(&container)?;
        if names != after_doc.list(&container)? {
            return fail("the entries of a container changed".to_owned());
        }
        for name in &names {
            let got = after_doc.get(&container, name)?;
            let planned = target
                .rewrites
                .iter()
                .find(|(k, key, _, _)| k == keys && key == name);
            let ok = match planned {
                Some((_, _, client, want)) => got
                    .as_ref()
                    .is_some_and(|got| canonical(client, got) == canonical(client, want)),
                None => got == before_doc.get(&container, name)?,
            };
            if !ok {
                return fail(format!("entry {name:?} does not read back as planned"));
            }
        }
        strip_container(&mut before_root, &container);
        strip_container(&mut after_root, &container);
    }
    if before_root != after_root {
        return fail("something outside the server containers changed".to_owned());
    }
    Ok(())
}

fn plan_skill(fs: &dyn Fs, link: &SkillLink, keep_agent_skill: bool) -> EjectSkill {
    let path = PathBuf::from(&link.path);
    let agent = link.skill_id == crate::agent::SKILL_ID && !keep_agent_skill;
    let mut skill = EjectSkill {
        client: link.client.clone(),
        scope: link.scope,
        project_id: link.project_id.clone(),
        skill_id: link.skill_id.clone(),
        path: path.clone(),
        method: link.method,
        action: SkillAction::Changed,
        done: false,
        read_only: None,
        error: None,
        row: link.clone(),
    };
    // A link a stopped run moved aside (`.<name>.surjection-link`) is still the
    // entry: the next run puts it back and copies it.
    let aside = aside_link(&path);
    let found = entry(fs, &path).and_then(|found| match found {
        Entry::Missing if matches!(entry(fs, &aside)?, Entry::Link(_)) => entry(fs, &aside),
        found => Ok(found),
    });
    let found = found.and_then(|found| {
        Ok(match found {
            Entry::Missing => SkillAction::Gone,
            Entry::Link(to)
                if link.method != LinkMethod::Copy
                    && same_folder(fs, &to, Path::new(&link.target)) =>
            {
                if agent {
                    SkillAction::Remove
                } else {
                    SkillAction::Copy
                }
            }
            Entry::Dir if link.method == LinkMethod::Copy => {
                match unchanged_copy(fs, &path, link)? {
                    None => SkillAction::Changed,
                    Some(_) if agent => SkillAction::Remove,
                    Some(_) => SkillAction::Keep,
                }
            }
            _ => SkillAction::Changed,
        })
    });
    match found {
        Ok(action) => skill.action = action,
        Err(err) => {
            skill.error = Some(err);
            return skill;
        }
    }
    if matches!(
        skill.action,
        SkillAction::Copy | SkillAction::Keep | SkillAction::Remove
    ) && let Some(kind) = new_folder_access(fs, &temp_folder(&path)).read_only()
    {
        skill.read_only = Some(kind);
        skill.error = Some(access::read_only_target(kind, &path));
    }
    skill
}

/// The folder a copy is made in before it replaces a link.
fn temp_folder(path: &Path) -> PathBuf {
    sibling(path, "surjection-eject")
}

/// Where a link waits while its copy moves into place.
fn aside_link(path: &Path) -> PathBuf {
    sibling(path, "surjection-link")
}

fn sibling(path: &Path, suffix: &str) -> PathBuf {
    let name = path
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    path.with_file_name(format!(".{name}.{suffix}"))
}

/// Puts back what a stopped run left next to `path`: the link moved aside
/// (when nothing took its place) and a half-made copy.
fn recover_leftovers(fs: &dyn Fs, path: &Path) -> Result<(), CoreError> {
    let aside = aside_link(path);
    if matches!(entry(fs, &aside)?, Entry::Link(_)) {
        if entry(fs, path)? == Entry::Missing {
            fs.replace(&aside, path).map_err(|err| {
                crate::access::write_error(fs, "cannot put the link back", path, &err)
            })?;
        } else {
            remove_link(fs, &aside)?;
        }
    }
    let temp = temp_folder(path);
    if fs.is_dir(&temp) {
        remove_copy(fs, &temp)?;
    }
    Ok(())
}

fn execute_skill(
    fs: &dyn Fs,
    skill: &mut EjectSkill,
    run: &mut EjectRun,
    hooks: &EjectHooks,
    journal: &mut dyn FnMut(&EjectRun) -> Result<(), CoreError>,
) {
    if skill.error.is_some() {
        return;
    }
    let path = skill.path.clone();
    let done = (|| -> Result<(), CoreError> {
        if skill.action != SkillAction::Gone {
            recover_leftovers(fs, &path)?;
        }
        match skill.action {
            SkillAction::Changed | SkillAction::Gone => Ok(()),
            SkillAction::Remove => match skill.method {
                LinkMethod::Copy => remove_copy(fs, &path),
                LinkMethod::Junction | LinkMethod::Symlink => remove_link(fs, &path),
            },
            SkillAction::Keep => {
                for marker in [MARKER_FILE, LEGACY_MARKER_FILE].map(|name| path.join(name)) {
                    if fs.exists(&marker) {
                        fs.remove_file(&marker).map_err(|err| {
                            crate::skills::removal_error(fs, "cannot remove file", &marker, &err)
                        })?;
                    }
                }
                run.unmarked.push(path.to_string_lossy().into_owned());
                Ok(())
            }
            SkillAction::Copy => {
                let files = read_folder(fs, Path::new(&skill.row.target))?;
                run.copied.push(CopiedSkill {
                    path: path.to_string_lossy().into_owned(),
                    hash: content_hash(&files),
                });
                journal(run)?;
                copy_in_place(fs, &skill.row, &files, hooks.fail_skill_move).inspect_err(|_| {
                    run.copied.pop();
                })
            }
        }
    })();
    match done {
        Ok(()) => skill.done = true,
        Err(err) => {
            skill.read_only = err.read_only();
            skill.error = Some(err);
        }
    }
}

/// Replaces the link at `link.path` with a copy of `files`: the copy is made
/// next to it, the link moved aside (renaming a link moves the link, never
/// what it points to), the copy moved into place and the link removed. A
/// failed move puts the link back.
fn copy_in_place(
    fs: &dyn Fs,
    link: &SkillLink,
    files: &crate::skills::SkillFiles,
    fail_move: bool,
) -> Result<(), CoreError> {
    let path = PathBuf::from(&link.path);
    let temp = temp_folder(&path);
    let aside = aside_link(&path);
    confine(fs, &temp)?;
    confine(fs, &aside)?;
    fs.create_dir_all(&temp)
        .map_err(|err| crate::access::write_error(fs, "cannot create directory", &temp, &err))?;
    write_files(fs, &temp, files)?;
    fs.replace(&path, &aside)
        .map_err(|err| crate::access::write_error(fs, "cannot move the link aside", &path, &err))?;
    let moved = if fail_move {
        Err(std::io::Error::other("test hook: the move failed"))
    } else {
        fs.replace(&temp, &path)
    };
    if let Err(err) = moved {
        let _ = fs.replace(&aside, &path);
        let _ = remove_copy(fs, &temp);
        return Err(crate::access::write_error(
            fs,
            "cannot move the copy into place",
            &path,
            &err,
        ));
    }
    // The copy is in place; a link left aside is removed by the next run.
    let _ = remove_link(fs, &aside);
    Ok(())
}

/// Starts managing again: every active run is marked resumed. The next
/// apply adopts entries identical to the store's and asks about the rest.
/// Returns the ids of the runs that were active (for [`unresume`]).
pub fn resume(fs: &dyn Fs, home: &SurjectionHome) -> Result<Vec<String>, CoreError> {
    set_resumed(fs, home, None, true)
}

/// Undoes a [`resume`] of `ids` (an import or adopt after it failed).
pub fn unresume(fs: &dyn Fs, home: &SurjectionHome, ids: &[String]) -> Result<(), CoreError> {
    if ids.is_empty() {
        return Ok(());
    }
    set_resumed(fs, home, Some(ids), false).map(|_| ())
}

fn set_resumed(
    fs: &dyn Fs,
    home: &SurjectionHome,
    ids: Option<&[String]>,
    resumed: bool,
) -> Result<Vec<String>, CoreError> {
    let state = home.state_dir();
    if !fs.exists(&state.join(EJECT_FILE)) {
        return Ok(Vec::new());
    }
    let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
    let mut record = EjectFile::load(fs, &state)?;
    let mut changed = Vec::new();
    for run in record.runs.iter_mut().filter(|run| !run.rolled_back) {
        let chosen = match ids {
            Some(ids) => ids.contains(&run.id),
            None => !run.resumed,
        };
        if chosen && run.resumed != resumed {
            run.resumed = resumed;
            changed.push(run.id.clone());
        }
    }
    if !changed.is_empty() {
        record.save(fs, &state)?;
    }
    Ok(changed)
}

/// Owned entries and skill entries of clients an active eject covers: what
/// it left behind (read-only or missing files, failures), for the app's
/// "Finish handing back".
pub fn left_over(fs: &dyn Fs, home: &SurjectionHome) -> Result<usize, CoreError> {
    let state = home.state_dir();
    let Some(ejected) = status_at(fs, &state)? else {
        return Ok(0);
    };
    let ledger = SkillLedger::load(fs, &state)?;
    let mcp = ledger.clone().mcp_mut().entries.clone();
    let entries = mcp
        .iter()
        .filter(|row| ejected.covers(&row.client, row.project_id.as_deref()))
        .count();
    let links = ledger
        .links
        .iter()
        .filter(|link| ejected.covers(&link.client, link.project_id.as_deref()))
        .count();
    Ok(entries + links)
}

/// The newest eject run that was not rolled back.
pub fn last_run(fs: &dyn Fs, home: &SurjectionHome) -> Result<Option<EjectRun>, CoreError> {
    Ok(EjectFile::load(fs, &home.state_dir())?
        .runs
        .into_iter()
        .rev()
        .find(|run| !run.rolled_back))
}

/// What [`rollback`] did.
#[derive(Debug)]
pub struct EjectRollback {
    pub eject_id: String,
    /// Files that hold their content from before the eject again.
    pub restored: Vec<PathBuf>,
    /// Files changed since the eject: left as they are (their backups are
    /// still there for `restore --files`).
    pub changed_since: Vec<PathBuf>,
    /// Files that could not be restored (a pruned backup, a refused
    /// write). With any, the run stays active, so the rollback can be run
    /// again.
    pub errors: Vec<(PathBuf, CoreError)>,
    /// The skill sync that turned copies back into links.
    pub skills: Option<SyncReport>,
}

/// Rolls back eject run `id` (the newest one not rolled back when `None`),
/// finished or stopped partway: each file still holding what the eject
/// wrote gets its backup back (every backup is read first; a file already
/// back counts as restored), ownership comes back where no newer row
/// replaced it, and the run is no longer active; then a skill sync remakes
/// links (with a store).
pub fn rollback(
    store: Option<&Store<'_>>,
    sx: &SkillsEnv<'_>,
    id: Option<&str>,
) -> Result<EjectRollback, CoreError> {
    let fs = sx.fs;
    let state = sx.home.state_dir();
    let mut result = {
        let _lock = StoreLock::acquire(fs, &state, LOCK_TIMEOUT)?;
        let mut record = EjectFile::load(fs, &state)?;
        let index = record
            .runs
            .iter()
            .rposition(|run| {
                !run.rolled_back && id.is_none_or(|id| run.id.eq_ignore_ascii_case(id))
            })
            .ok_or_else(|| {
                CoreError::new(
                    ErrorCode::NotFound,
                    match id {
                        Some(id) => format!("no eject run {id:?} to roll back on this machine"),
                        None => "this machine has no eject run to roll back".to_owned(),
                    },
                )
            })?;
        let run = record.runs[index].clone();
        let mut result = EjectRollback {
            eject_id: run.id.clone(),
            restored: Vec::new(),
            changed_since: Vec::new(),
            errors: Vec::new(),
            skills: None,
        };
        // Every backup first: a missing one stops nothing half way.
        let reads: Vec<_> = run
            .files
            .iter()
            .map(|file| {
                let path = PathBuf::from(&file.file);
                let backup = match &file.backup {
                    Some(backup) => fs.read(Path::new(backup)).map_err(|err| {
                        CoreError::new(ErrorCode::IoError, format!("cannot read backup: {err}"))
                            .with_path(backup)
                    }),
                    None => Err(CoreError::new(
                        ErrorCode::NotFound,
                        "the eject recorded no backup of this file",
                    )
                    .with_path(&path)),
                };
                (path, file.written.as_str(), backup)
            })
            .collect();
        for (path, written, backup) in reads {
            let outcome = backup.and_then(|backup| {
                let current = read_target(fs, &path)?;
                let now = current.as_deref().map(sha256);
                if now.as_deref() == Some(sha256(&backup).as_str()) {
                    return Ok(true);
                }
                if now.as_deref() != Some(written) {
                    return Ok(false);
                }
                swap_file(fs, &path, current.as_deref(), &backup)
            });
            match outcome {
                Ok(true) => result.restored.push(path),
                Ok(false) => result.changed_since.push(path),
                Err(err) => result.errors.push((path, err)),
            }
        }
        let mut ledger = SkillLedger::load(fs, &state)?;
        let skipped: HashSet<String> = result
            .changed_since
            .iter()
            .chain(result.errors.iter().map(|(path, _)| path))
            .map(|path| path.to_string_lossy().into_owned())
            .collect();
        for row in &run.ledger {
            // A newer row (an apply after a resume) wins.
            let newer = ledger.mcp_mut().get(&row.slot(), &row.key).is_some();
            if !skipped.contains(&row.file) && !newer {
                ledger.mcp_mut().upsert(row.clone());
            }
        }
        // A copy made from a link is owned as a copy, so the next sync makes
        // the link again; also when the run stopped before it dropped the
        // link's row.
        let as_copy = |mut row: SkillLink, copied: &CopiedSkill| {
            row.method = LinkMethod::Copy;
            row.written_hash = Some(copied.hash.clone());
            row
        };
        for copied in &run.copied {
            if let Some(owned) = ledger.get(Path::new(&copied.path)).cloned()
                && owned.method != LinkMethod::Copy
            {
                ledger.upsert(as_copy(owned, copied));
            }
        }
        for row in &run.skill_links {
            if ledger.get(Path::new(&row.path)).is_some() {
                continue;
            }
            let row = match run.copied.iter().find(|copied| copied.path == row.path) {
                Some(copied) => as_copy(row.clone(), copied),
                None => {
                    if run.unmarked.contains(&row.path) {
                        let marker = Path::new(&row.path).join(MARKER_FILE);
                        if fs.is_dir(Path::new(&row.path)) && !fs.exists(&marker) {
                            fs.write(&marker, marker_text(&row.skill_id).as_bytes())
                                .map_err(|err| {
                                    crate::access::write_error(
                                        fs,
                                        "cannot write file",
                                        &marker,
                                        &err,
                                    )
                                })?;
                        }
                    }
                    row.clone()
                }
            };
            ledger.upsert(row);
        }
        ledger.save(fs, &state)?;
        if result.errors.is_empty() {
            record.runs[index].rolled_back = true;
            record.save(fs, &state)?;
        }
        result
    };
    if let Some(store) = store {
        result.skills = Some(link::sync(store, sx)?);
    }
    Ok(result)
}