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
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
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
//! MCP servers from a Git repository or a local folder (#5).
//!
//! [`resolve`] turns a source into **drafts**: proposed store servers read
//! from the folder's files (`server.json` of the MCP Registry, an MCPB
//! manifest, committed client configs, or the folder as a package). It
//! runs nothing: the system git clones shallow at the ref (no submodules,
//! no hooks from the repository) into `cache/mcp-sources/.tmp-<ulid>`, the
//! files are read (dependency and build folders left out, [`SKIP_DIRS`])
//! and scanned (M40), and the clone is removed when the [`Resolved`] is
//! dropped ([`sweep_temp_clones`] removes what a crash left). [`save`]
//! stores the drafts the user picked and edited in one commit, after the
//! source trust gate (M39) and the scan gate; a draft that runs from the
//! repository's files keeps the clone as the machine-local
//! `<SURJECTION_HOME>/servers/<id>` (never synced), placed under the store
//! lock and marked with the commit it holds.
//!
//! Only provenance goes into the synced server file (`[meta.source]`), so
//! [`check_update`] can read the source again and show what changed. A
//! server runs only where its code is what the file names ([`runnable`]):
//! a checkout at another commit, or a folder of another machine, blocks its
//! entries. Secrets: a declared secret becomes a `${secret:<alias>}`
//! reference for the user to set; a literal the classifier flags is
//! replaced by a reference and its value dropped: no value is kept or
//! returned. Every check covers the base definition and each `[os.*]`
//! override alike.

mod convert;
pub mod snippet;
#[cfg(test)]
mod tests;

use std::collections::{BTreeMap, BTreeSet};
use std::ffi::OsStr;
use std::path::{Path, PathBuf};
use std::time::Duration;

use crate::apply::{ApplyEnv, ApplyReport, Touched, instant_apply};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::model::ids;
use crate::model::server::{Meta, Server, ServerFields, ServerSource, ServerSourceKind};
use crate::paths::STATE_DIR;
use crate::scan::{self, ScanReport, Scanner};
use crate::secrets::catalog::Catalog;
use crate::secrets::extract::{Aliases, Extractor};
use crate::skills::install::{
    self, ChangeKind, Decisions, FileChange, Source, UpdateStatus, check_repo_path, git_path,
    is_commit_ref, join_rel, looks_executable, remove_dir, run_git,
};
use crate::skills::{SkillFiles, SkillsEnv, confine, content_hash, io_error, read_folder_skipping};
use crate::sources::{self, SourceChange, SourceChangeKind, SourceRef, TrustCheck, TrustGrant};
use crate::store::{CommitId, Machine, Operation, Store, server_path};

pub(crate) use convert::custom_registry_url;
use convert::{CHECKOUT_TOKEN, Ctx, GitPin, ID_TOKEN, IMAGE_PREFIX, RawDraft};

/// Machine-local clones servers run from: `<SURJECTION_HOME>/servers/<id>`.
pub const CHECKOUTS_DIR: &str = "servers";
/// Temporary clones of a resolve, below `<SURJECTION_HOME>/cache`.
pub const TEMP_DIR: &str = "mcp-sources";
/// `meta.origin` of a server drafted from a git source.
pub const ORIGIN_GIT: &str = "source:git";
/// `meta.origin` of a server drafted from a local folder.
pub const ORIGIN_LOCAL: &str = "source:local";
/// Dependency and build folders a source read leaves out (scan, size cap,
/// diffs): installed or built on this machine, not part of the source.
pub const SKIP_DIRS: [&str; 8] = [
    "node_modules",
    ".venv",
    "venv",
    "__pycache__",
    ".git",
    "target",
    "dist",
    "build",
];
/// The data folder template variable written into store files: Loadout
/// 1.0.x's spelling, which both versions read (Appendix C.1).
const HOME_VAR: &str = "loadout_home";
/// The checkout's marker, inside its `.git`: the commit and URL it holds.
const MARKER_FILE: &str = "surjection-checkout";
/// The marker Loadout 1.0.x wrote; still read, so its checkouts stay current.
const LEGACY_MARKER_FILE: &str = "loadout-checkout";
/// A checkout moved aside while its replacement is committed.
const ASIDE_PREFIX: &str = ".old-";

/// A store id from a server or entry name: lower case, other characters
/// become `-`, at most 64 characters.
pub fn id_from_name(name: &str) -> String {
    let mut id: String = name
        .trim()
        .chars()
        .map(|c| {
            let c = c.to_ascii_lowercase();
            if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
                c
            } else {
                '-'
            }
        })
        .collect();
    id = id.trim_matches(|c| matches!(c, '-' | '.' | '_')).to_owned();
    id.truncate(64);
    if id.is_empty() {
        "server".to_owned()
    } else {
        id
    }
}

/// Which converter made a draft.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DraftKind {
    /// `server.json` (MCP Registry).
    Registry,
    /// An MCPB/DXT `manifest.json`.
    Bundle,
    /// A committed client config.
    ClientConfig,
    /// The folder is the server (`package.json`, `pyproject.toml`,
    /// `Dockerfile`).
    Package,
}

impl DraftKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            DraftKind::Registry => "registry",
            DraftKind::Bundle => "bundle",
            DraftKind::ClientConfig => "client_config",
            DraftKind::Package => "package",
        }
    }
}

/// A value the user provides: a secret to set under `alias`, or a
/// variable the draft reads from the environment.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DraftInput {
    /// `env.NAME`, `headers.NAME`, `args[N]` (1-based), `url`, `command`,
    /// each also as `os.<name>.<field>` for an override, or
    /// `client.<id>.<key>` for a native passthrough value.
    pub field: String,
    pub description: Option<String>,
    /// The draft holds `${secret:<alias>}` (or, for a passthrough value,
    /// the value was left out).
    pub secret: bool,
    pub required: bool,
    pub alias: Option<String>,
    /// The file held a literal value here; it was replaced by the
    /// reference (or left out) and not kept.
    pub value_dropped: bool,
}

/// One launch line: the base definition (`os` `None`) or an `[os.<name>]`
/// override merged over it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LaunchLine {
    pub os: Option<String>,
    /// The command and arguments joined by spaces, or the URL.
    pub line: String,
}

/// One proposed server.
#[derive(Debug, Clone)]
pub struct Draft {
    /// Names the draft in [`Pick::key`]: `<file>#<entry>` or `<file>`.
    pub key: String,
    pub kind: DraftKind,
    /// The proposed store server: `meta.origin` and `meta.source` set, no
    /// enablement.
    pub server: Server,
    pub inputs: Vec<DraftInput>,
    /// It runs code from the source (the folder's files, or the
    /// repository as a package) every time a client starts it.
    pub runs_repo_code: bool,
    /// It runs from `<SURJECTION_HOME>/servers/<id>` (git sources).
    pub checkout: bool,
    /// The command names a version or commit; `false` for a registry
    /// package without a concrete version (the scan flags it too).
    pub pinned: bool,
    /// Steps the user runs before it works (`docker build ...`); never run
    /// by Surjection. They may hold `${home}` and `${surjection_home}`
    /// ([`setup_text`]).
    pub setup: Vec<String>,
    /// Other files that held an identical definition.
    pub also_in: Vec<String>,
    /// The folder's files and every launch line of this draft.
    pub scan: ScanReport,
    /// What this draft runs, gated on its own (a registry entry's package
    /// or remote host, #26); `None`: [`Resolved::trust_source`] gates it.
    pub trust_source: Option<SourceRef>,
}

impl Draft {
    /// The draft's provenance.
    pub fn provenance(&self) -> &ServerSource {
        self.server
            .body
            .meta
            .as_ref()
            .and_then(|meta| meta.source.as_ref())
            .expect("a draft has its source")
    }
}

/// A definition the folder holds that cannot be drafted.
#[derive(Debug, Clone)]
pub struct Skipped {
    pub file: String,
    /// The entry inside the file, when it holds several.
    pub entry: Option<String>,
    pub error: CoreError,
}

/// What to resolve.
#[derive(Debug, Clone)]
pub struct ResolveRequest {
    pub source: Source,
    /// Branch, tag or commit of a git source (overrides the URL's).
    pub git_ref: Option<String>,
    /// The folder inside a git source (overrides the URL's).
    pub path: Option<String>,
    /// The catalog entry the source comes from, `<catalog>/<entry id>`
    /// (#26): recorded as `meta.source.catalog`.
    pub catalog: Option<String>,
    /// A Claude Code marketplace entry's `mcpServers` (#26), as JSON: an
    /// object of server definitions, or a path to a config file in the
    /// folder. Drafted with the folder's own configs.
    pub mcp_servers: Option<String>,
}

impl ResolveRequest {
    pub fn new(source: Source) -> Self {
        Self {
            source,
            git_ref: None,
            path: None,
            catalog: None,
            mcp_servers: None,
        }
    }
}

/// An MCP registry entry to draft from (#26): its `server.json` as the
/// registry served it (the `server` object of the entry).
#[derive(Debug, Clone)]
pub struct RegistryRequest {
    /// `<catalog>/<server name>`.
    pub catalog: String,
    /// The registry's base URL.
    pub registry: String,
    /// The server name (`io.github.acme/weather`).
    pub name: String,
    /// The entry's version.
    pub version: String,
    /// The version was asked for (`--ref`): updates do not follow the
    /// latest one.
    pub pinned: bool,
    pub server_json: String,
}

/// A resolved source waiting for the user's picks ([`resolve`], then
/// [`save`]). The temporary clone is removed when this is dropped without
/// a save that keeps it.
#[derive(Debug)]
pub struct Resolved {
    base: ServerSource,
    drafts: Vec<Draft>,
    skipped: Vec<Skipped>,
    skipped_folders: Vec<String>,
    files: SkillFiles,
    files_scan: ScanReport,
    trust_source: Option<SourceRef>,
    moved_source: Option<SourceRef>,
    source_change: Option<SourceChange>,
    /// The temporary clone (git sources).
    clone: Option<PathBuf>,
    spent: bool,
}

impl Resolved {
    pub fn drafts(&self) -> &[Draft] {
        &self.drafts
    }

    pub fn skipped(&self) -> &[Skipped] {
        &self.skipped
    }

    /// Dependency and build folders left out of the read and the scan
    /// (relative paths, [`SKIP_DIRS`]).
    pub fn skipped_folders(&self) -> &[String] {
        &self.skipped_folders
    }

    /// Where the drafts come from (`file` and `converter` empty).
    pub fn source(&self) -> &ServerSource {
        &self.base
    }

    /// The scan of the folder's files.
    pub fn files_scan(&self) -> &ScanReport {
        &self.files_scan
    }

    /// The source the trust gate admits with [`Decisions::trust`]: the
    /// repository the URL names, or the local folder. `None` for a
    /// registry entry: each draft carries its own
    /// ([`Draft::trust_source`]).
    pub fn trust_source(&self) -> Option<&SourceRef> {
        self.trust_source.as_ref()
    }

    /// Where the host redirected the repository (another key): gated too,
    /// with [`Decisions::moved_trust`].
    pub fn moved_source(&self) -> Option<&SourceRef> {
        self.moved_source.as_ref()
    }

    /// The repository the URL names moved.
    pub fn source_change(&self) -> Option<&SourceChange> {
        self.source_change.as_ref()
    }

    /// The trust gate (#24): the requested source with the user's answer
    /// for it, and a redirect target with the answer for that one. A
    /// redirect only ever adds a question. Each of `drafts` that runs from
    /// its own source (a registry entry) is gated on it, with the answer
    /// given with it (a [`Pick::trust`]), or [`Decisions::trust`] when the
    /// drafts run from one source.
    fn admit(
        &self,
        store: &Store<'_>,
        decisions: &Decisions,
        drafts: &[(&Draft, Option<TrustGrant>)],
    ) -> Result<(), CoreError> {
        if let Some(source) = &self.trust_source {
            sources::admit(store, source, decisions.trust, decisions.via)?;
        }
        if let Some(moved) = &self.moved_source {
            sources::admit(store, moved, decisions.moved_trust, decisions.via)?;
        }
        let mut own: Vec<(&SourceRef, Option<TrustGrant>)> = Vec::new();
        for (draft, grant) in drafts {
            let Some(source) = draft.trust_source.as_ref() else {
                continue;
            };
            match own
                .iter_mut()
                .find(|(known, _)| known.key() == source.key())
            {
                Some((_, known)) => *known = known.or(*grant),
                None => own.push((source, *grant)),
            }
        }
        // Blocks first: no "always trust" is recorded for a save that a
        // block refuses anyway.
        for (source, _) in &own {
            sources::refuse_blocked(store, source)?;
        }
        let single = own.len() == 1 && self.trust_source.is_none();
        for (source, grant) in own {
            let grant = grant.or(if single { decisions.trust } else { None });
            sources::admit(store, source, grant, decisions.via)?;
        }
        Ok(())
    }
}

impl Drop for Resolved {
    fn drop(&mut self) {
        if let Some(clone) = self.clone.take() {
            // Below `SURJECTION_HOME/cache`; a leftover is swept later.
            let _ = std::fs::remove_dir_all(clone);
        }
    }
}

/// What [`fetch`] read.
struct Fetched {
    base: ServerSource,
    files: SkillFiles,
    skipped_folders: Vec<String>,
    /// How commands name the folder.
    root: String,
    pin: Option<GitPin>,
    name: String,
    clone: Option<PathBuf>,
    /// `None`: a registry entry (each draft is gated on what it runs).
    trust_source: Option<SourceRef>,
    moved_source: Option<SourceRef>,
    source_change: Option<SourceChange>,
    /// [`ResolveRequest::mcp_servers`].
    plugin_servers: Option<String>,
}

/// `<SURJECTION_HOME>/servers/<id>`.
pub fn checkout_dir(sx: &SkillsEnv<'_>, id: &str) -> PathBuf {
    sx.home.path.join(CHECKOUTS_DIR).join(id)
}

/// The URL kept in the store (and in a checkout's `.git/config`): a
/// password or token in an `http(s)` URL is removed; ssh users (`git@`)
/// stay, the clone needs them.
fn provenance_url(url: &str) -> String {
    let url = url.trim();
    let lower = url.to_ascii_lowercase();
    for scheme in ["https://", "http://"] {
        if lower.starts_with(scheme) {
            let rest = &url[scheme.len()..];
            let (authority, path) = rest.split_once('/').unwrap_or((rest, ""));
            if let Some((_, host)) = authority.rsplit_once('@') {
                return format!("{}{host}/{path}", &url[..scheme.len()]);
            }
        }
    }
    url.to_owned()
}

/// A folder as commands name it: `${home}/...` below the home folder, else
/// the absolute path, `/`-separated.
fn folder_template(sx: &SkillsEnv<'_>, folder: &Path) -> String {
    let home = sx.env.home();
    let text = match folder.strip_prefix(home) {
        Ok(rest) if !rest.as_os_str().is_empty() => {
            format!("${{home}}/{}", rest.to_string_lossy())
        }
        _ => folder.to_string_lossy().into_owned(),
    };
    convert::escape(&text.replace('\\', "/")).replace("$${home}", "${home}")
}

/// The folder a [`folder_template`] names.
fn folder_of(sx: &SkillsEnv<'_>, template: &str) -> PathBuf {
    let text = template.replace("$${", "${");
    match text.strip_prefix("${home}/") {
        Some(rest) => rest
            .split('/')
            .fold(sx.env.home().to_path_buf(), |path, part| path.join(part)),
        None => PathBuf::from(text),
    }
}

fn name_of(text: &str) -> String {
    text.trim_end_matches(['/', '\\'])
        .rsplit(['/', '\\', ':'])
        .next()
        .unwrap_or("server")
        .trim_end_matches(".git")
        .to_owned()
}

/// A setup step for a person to run: `${surjection_home}` and `${home}` (store
/// templates, not shell variables) written as `surjection_home` and `home`.
pub fn setup_text(step: &str, home: &str, surjection_home: &str) -> String {
    step.replace("${surjection_home}", surjection_home)
        .replace("${loadout_home}", surjection_home)
        .replace("${home}", home)
        .replace("$${", "${")
}

/// Reads a source folder ([`SKIP_DIRS`] left out).
fn read_source(fs: &dyn Fs, dir: &Path) -> Result<(SkillFiles, Vec<String>), CoreError> {
    read_folder_skipping(fs, dir, &SKIP_DIRS)
}

/// Reads a folder inside a clone, refused when it (or a link on its way)
/// resolves outside the clone.
fn read_in(
    sx: &SkillsEnv<'_>,
    clone: &Path,
    dir: &Path,
) -> Result<(SkillFiles, Vec<String>), CoreError> {
    let resolve = |path: &Path| {
        sx.fs
            .canonicalize(path)
            .map_err(|err| io_error("cannot resolve folder", path, &err))
    };
    if !resolve(dir)?.starts_with(resolve(clone)?) {
        return Err(CoreError::new(
            ErrorCode::InvalidPath,
            "the folder points outside the repository",
        )
        .with_path(dir));
    }
    read_source(sx.fs, dir)
}

/// Clones `url` into a new temporary folder at `git_ref` (a branch, tag or
/// commit), sparse to `path`, and points its `origin` at the URL without
/// credentials. Returns the clone, the commit, the branch followed and
/// where the host redirected the URL.
fn clone_at(
    sx: &SkillsEnv<'_>,
    url: &str,
    git_ref: Option<&str>,
    path: Option<&str>,
) -> Result<(PathBuf, String, Option<String>, Option<String>), CoreError> {
    let git = git_path(sx)?;
    let temp = sx.home.cache_dir().join(TEMP_DIR).join(format!(
        ".tmp-{}",
        ids::new_ulid(sx.env.now())?.to_ascii_lowercase()
    ));
    let cloned = install::clone(sx, &git, url, git_ref, path, &temp)?;
    let fail = |err: CoreError| {
        let _ = remove_dir(sx.fs, &temp);
        err
    };
    // A token in the URL never stays in the clone's `.git/config`, which
    // a checkout keeps for good.
    let clean = provenance_url(url);
    let args: Vec<&OsStr> = ["remote", "set-url", "origin", clean.as_str()]
        .into_iter()
        .map(OsStr::new)
        .collect();
    let output = run_git(sx, &git, &temp, &args).map_err(fail)?;
    if !output.success {
        return Err(fail(CoreError::new(
            ErrorCode::GitError,
            "cannot set the clone's remote URL",
        )));
    }
    Ok((temp, cloned.commit, cloned.branch, cloned.redirect))
}

fn fetch(sx: &SkillsEnv<'_>, request: &ResolveRequest) -> Result<Fetched, CoreError> {
    match &request.source {
        Source::Local(folder) => {
            if request.git_ref.is_some() || request.path.is_some() {
                return Err(CoreError::new(
                    ErrorCode::InvalidValue,
                    "a ref and a path apply to git sources only",
                ));
            }
            if !sx.fs.is_dir(folder) {
                return Err(
                    CoreError::new(ErrorCode::NotFound, "the folder does not exist")
                        .with_path(folder),
                );
            }
            let root = folder_template(sx, folder);
            let (files, skipped_folders) = read_source(sx.fs, folder)?;
            Ok(Fetched {
                base: ServerSource {
                    kind: ServerSourceKind::Local,
                    url: None,
                    folder: Some(root.clone()),
                    path: None,
                    git_ref: None,
                    commit: None,
                    file: String::new(),
                    converter: String::new(),
                    entry: None,
                    checkout: None,
                    machine: None,
                    catalog: request.catalog.clone(),
                    version: None,
                    extra: toml::Table::new(),
                },
                files,
                skipped_folders,
                root,
                pin: None,
                name: name_of(&folder.to_string_lossy()),
                clone: None,
                trust_source: Some(SourceRef::from_local_path(folder)?),
                moved_source: None,
                source_change: None,
                plugin_servers: request.mcp_servers.clone(),
            })
        }
        Source::Git { url, git_ref, path } => {
            let requested = SourceRef::from_git_url(url)?;
            let git_ref = request.git_ref.clone().or_else(|| git_ref.clone());
            let path = request
                .path
                .clone()
                .or_else(|| path.clone())
                .map(|path| check_repo_path(&path))
                .transpose()?;
            let (clone, commit, branch, redirect) =
                clone_at(sx, url, git_ref.as_deref(), path.as_deref())?;
            let read = || -> Result<(SkillFiles, Vec<String>), CoreError> {
                let dir = match &path {
                    Some(path) => join_rel(&clone, path),
                    None => clone.clone(),
                };
                if !sx.fs.is_dir(&dir) {
                    return Err(CoreError::new(
                        ErrorCode::NotFound,
                        format!(
                            "the repository has no folder {:?}",
                            path.as_deref().unwrap_or("")
                        ),
                    ));
                }
                read_in(sx, &clone, &dir)
            };
            let (files, skipped_folders) = match read() {
                Ok(read) => read,
                Err(err) => {
                    let _ = remove_dir(sx.fs, &clone);
                    return Err(err);
                }
            };
            let moved_to = redirect
                .as_deref()
                .and_then(|target| SourceRef::from_git_url(target).ok())
                .filter(|target| target.key() != requested.key());
            let source_change = moved_to.as_ref().map(|target| SourceChange {
                kind: SourceChangeKind::Moved,
                detail: Some(target.key().to_owned()),
            });
            let url = provenance_url(url);
            let followed = match git_ref.as_deref() {
                Some(r) if is_commit_ref(r) => Some(r.to_owned()),
                _ => branch,
            };
            let name = path
                .as_deref()
                .and_then(|path| path.rsplit('/').next())
                .map_or_else(|| name_of(&url), str::to_owned);
            Ok(Fetched {
                base: ServerSource {
                    kind: ServerSourceKind::Git,
                    url: Some(url.clone()),
                    folder: None,
                    path: path.clone(),
                    git_ref: followed,
                    commit: Some(commit.clone()),
                    file: String::new(),
                    converter: String::new(),
                    entry: None,
                    checkout: None,
                    machine: None,
                    catalog: request.catalog.clone(),
                    version: None,
                    extra: toml::Table::new(),
                },
                files,
                skipped_folders,
                root: CHECKOUT_TOKEN.to_owned(),
                pin: Some(GitPin { url, commit, path }),
                name,
                clone: Some(clone),
                trust_source: Some(requested),
                moved_source: moved_to,
                source_change,
                plugin_servers: request.mcp_servers.clone(),
            })
        }
    }
}

/// `${loadout_home}/servers/<id>[/<path>]`: the data folder variable is
/// written with the spelling Loadout 1.0.x reads (synced store files, like
/// `store/loadout.toml`; Appendix C.1).
fn checkout_root(id: &str, path: Option<&str>) -> String {
    match path {
        Some(path) => format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{id}/{path}"),
        None => format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{id}"),
    }
}

/// Every launch string of `fields` through `edit`.
fn edit_fields(fields: &mut ServerFields, edit: &dyn Fn(&str) -> String) {
    let apply = |value: &mut String| *value = edit(value);
    fields.command.iter_mut().for_each(apply);
    fields.cwd.iter_mut().for_each(apply);
    fields.url.iter_mut().for_each(apply);
    fields.args.iter_mut().flatten().for_each(apply);
    fields
        .env
        .iter_mut()
        .flatten()
        .for_each(|(_, value)| apply(value));
    fields
        .headers
        .iter_mut()
        .flatten()
        .for_each(|(_, value)| apply(value));
}

/// Every launch string of `server`, base and overrides, through `edit`.
fn edit_server(server: &mut Server, edit: &dyn Fn(&str) -> String) {
    let mut fields = server.body.fields();
    edit_fields(&mut fields, edit);
    set_launch(server, &fields);
    for over in server.body.os.iter_mut().flatten().map(|(_, over)| over) {
        edit_fields(&mut over.fields, edit);
    }
}

/// Writes the launch fields of `fields` into `server`.
fn set_launch(server: &mut Server, fields: &ServerFields) {
    let body = &mut server.body;
    body.transport = fields.transport;
    body.command.clone_from(&fields.command);
    body.args.clone_from(&fields.args);
    body.cwd.clone_from(&fields.cwd);
    body.url.clone_from(&fields.url);
    body.headers.clone_from(&fields.headers);
    body.env.clone_from(&fields.env);
}

/// `value` with each whole `from` (followed by the end, `/` or `:`)
/// replaced by `to`.
fn replace_whole(value: &str, from: &str, to: &str) -> String {
    let mut out = String::new();
    let mut rest = value;
    while let Some(at) = rest.find(from) {
        let after = &rest[at + from.len()..];
        out.push_str(&rest[..at]);
        if after.is_empty() || after.starts_with(['/', ':']) {
            out.push_str(to);
        } else {
            out.push_str(from);
        }
        rest = after;
    }
    out.push_str(rest);
    out
}

/// Points what a draft names by its id (its checkout folder, its local
/// image tag) at `to` instead of `from`.
fn rename_id(server: &mut Server, from: &str, to: &str) {
    if from == to {
        return;
    }
    let pairs = [
        (
            format!("${{surjection_home}}/{CHECKOUTS_DIR}/{from}"),
            format!("${{surjection_home}}/{CHECKOUTS_DIR}/{to}"),
        ),
        (
            format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{from}"),
            format!("${{{HOME_VAR}}}/{CHECKOUTS_DIR}/{to}"),
        ),
        (
            format!("{IMAGE_PREFIX}{from}"),
            format!("{IMAGE_PREFIX}{to}"),
        ),
    ];
    edit_server(server, &|value| {
        pairs.iter().fold(value.to_owned(), |value, (old, new)| {
            replace_whole(&value, old, new)
        })
    });
}

fn rename_steps(steps: &[String], from: &str, to: &str) -> Vec<String> {
    let mut server = Server::new(to.to_owned());
    server.body.args = Some(steps.to_vec());
    rename_id(&mut server, from, to);
    server.body.args.unwrap_or_default()
}

fn line_of(fields: &ServerFields) -> String {
    match (&fields.url, &fields.command) {
        (Some(url), _) => url.clone(),
        (None, Some(command)) => std::iter::once(command)
            .chain(fields.args.iter().flatten())
            .cloned()
            .collect::<Vec<_>>()
            .join(" "),
        (None, None) => String::new(),
    }
}

/// The launch fields as each OS sees them: the base, then each
/// `[os.<name>]` override merged over it.
fn effective(server: &Server) -> Vec<(Option<String>, ServerFields)> {
    let base = server.body.fields();
    let mut out = vec![(None, base.clone())];
    for (name, over) in server.body.os.iter().flatten() {
        out.push((Some(name.clone()), base.merged(&over.fields)));
    }
    out
}

/// Every launch line of `server`: the base and each OS override.
pub fn launch_lines(server: &Server) -> Vec<LaunchLine> {
    effective(server)
        .into_iter()
        .map(|(os, fields)| LaunchLine {
            os,
            line: line_of(&fields),
        })
        .collect()
}

/// The scan of every command line `server` can run, base and overrides.
fn scan_commands(scanner: &Scanner<'_>, server: &Server) -> ScanReport {
    let mut lines = effective(server)
        .into_iter()
        .map(|(_, fields)| match &fields.command {
            Some(command) => scanner.scan_command(command, &fields.args.unwrap_or_default()),
            None => scanner.scan_command(&fields.url.unwrap_or_default(), &[]),
        });
    let mut report = lines.next().expect("the base definition");
    for other in lines {
        report.merge(other);
    }
    report
}

fn store_ids(store: Option<&Store<'_>>) -> Result<BTreeSet<String>, CoreError> {
    Ok(match store {
        Some(store) => store.servers()?.into_iter().map(|entry| entry.id).collect(),
        None => BTreeSet::new(),
    })
}

fn aliases(store: Option<&Store<'_>>, sx: &SkillsEnv<'_>) -> Result<Aliases, CoreError> {
    let Some(store) = store else {
        return Ok(Aliases::default());
    };
    let machine = Machine::load(sx.fs, &sx.home.state_dir())?;
    let catalog = Catalog::load(store, machine.as_ref().map(|m| m.id.as_str()))?;
    Ok(Aliases::new(
        catalog.iter().map(|alias| alias.alias.clone()),
    ))
}

/// `base`, or `base-2`, `base-3`, ... free of `taken`.
fn free_id(base: &str, taken: &BTreeSet<String>) -> String {
    if !taken.contains(base) {
        return base.to_owned();
    }
    let stem: String = base.chars().take(60).collect();
    (2..)
        .map(|n| format!("{stem}-{n}"))
        .find(|id| !taken.contains(id))
        .expect("a free id")
}

/// Replaces the literals of `fields` the classifier flags by references
/// (the values are dropped), listing each as an input named
/// `<prefix><field>`.
fn extract(
    fields: &mut ServerFields,
    prefix: &str,
    id: &str,
    aliases: &mut Aliases,
    inputs: &mut Vec<DraftInput>,
) -> Result<(), CoreError> {
    let mut extractor = Extractor::new(id, aliases);
    if let Some(args) = fields.args.take() {
        fields.args = Some(extractor.args(args));
    }
    if let Some(url) = fields.url.take() {
        fields.url = Some(extractor.url(url)?);
    }
    if let Some(env) = fields.env.take() {
        fields.env = Some(extractor.map("env", env));
    }
    if let Some(headers) = fields.headers.take() {
        fields.headers = Some(extractor.map("headers", headers));
    }
    for extracted in extractor.finish() {
        let extraction = extracted.extraction;
        // The value (`extracted.value`) is dropped here.
        inputs.push(DraftInput {
            field: format!("{prefix}{}", extraction.field),
            description: None,
            secret: true,
            required: true,
            alias: Some(extraction.alias),
            value_dropped: true,
        });
    }
    Ok(())
}

/// Renames the provisional secret references of `raw` to free aliases of
/// server `id`, then replaces every other literal the classifier flags, in
/// the base definition and in each override, by a reference.
fn secure(raw: &mut RawDraft, id: &str, aliases: &mut Aliases) -> Result<(), CoreError> {
    let mut renames = BTreeMap::new();
    for input in raw.inputs.iter_mut().filter(|input| input.secret) {
        if let Some(key) = input.alias.clone() {
            let alias = renames
                .entry(key)
                .or_insert_with_key(|key| aliases.new_alias(id, key))
                .clone();
            input.alias = Some(alias);
        }
    }
    if !renames.is_empty() {
        let edit = |value: &str| {
            let mut out = value.to_owned();
            for (key, alias) in &renames {
                out = out.replace(
                    &format!("${{secret:{key}}}"),
                    &format!("${{secret:{alias}}}"),
                );
            }
            out
        };
        edit_fields(&mut raw.fields, &edit);
        for over in raw.os.iter_mut().flatten().map(|(_, over)| over) {
            edit_fields(&mut over.fields, &edit);
        }
    }
    extract(&mut raw.fields, "", id, aliases, &mut raw.inputs)?;
    for (name, over) in raw.os.iter_mut().flatten() {
        let prefix = format!("os.{name}.");
        extract(&mut over.fields, &prefix, id, aliases, &mut raw.inputs)?;
    }
    Ok(())
}

/// Resolves a source into drafts: fetches (a git source into a temporary
/// clone), converts and scans, without touching the store. `store` (when
/// there is one) keeps ids and secret aliases free of those in use, and a
/// source it blocks is refused before it is contacted.
pub fn resolve(
    store: Option<&Store<'_>>,
    sx: &SkillsEnv<'_>,
    request: &ResolveRequest,
) -> Result<Resolved, CoreError> {
    if let Some(store) = store {
        // A blocked source is never contacted (#24).
        let requested = match &request.source {
            Source::Git { url, .. } => SourceRef::from_git_url(url)?,
            Source::Local(folder) => SourceRef::from_local_path(folder)?,
        };
        sources::refuse_blocked(store, &requested)?;
    }
    let fetched = fetch(sx, request)?;
    build(store, sx, fetched)
}

/// The `meta.origin` of a catalog install: `catalog:<catalog id>`.
pub fn catalog_origin(catalog: &str) -> String {
    let id = catalog.split_once('/').map_or(catalog, |(id, _)| id);
    format!("catalog:{id}")
}

/// Resolves an MCP registry entry (#26) into drafts: its `server.json`
/// goes through the `registry` converter as a `registry` source. Nothing
/// is fetched here (the catalog already read the entry); `store` keeps
/// ids and aliases free. Each draft is gated on what it runs
/// ([`crate::catalog::registry::trust_keys`]): a draft without a usable
/// key is skipped, and an entry whose every draft is blocked is refused.
pub fn resolve_registry(
    store: Option<&Store<'_>>,
    sx: &SkillsEnv<'_>,
    request: &RegistryRequest,
) -> Result<Resolved, CoreError> {
    let keys = crate::catalog::registry::trust_keys(&request.server_json)?;
    let files = SkillFiles::from([(
        "server.json".to_owned(),
        request.server_json.as_bytes().to_vec(),
    )]);
    let fetched = Fetched {
        base: ServerSource {
            kind: ServerSourceKind::Registry,
            url: Some(request.registry.clone()),
            folder: None,
            path: None,
            git_ref: request.pinned.then(|| request.version.clone()),
            commit: None,
            file: String::new(),
            converter: String::new(),
            entry: None,
            checkout: None,
            machine: None,
            catalog: Some(request.catalog.clone()),
            version: Some(request.version.clone()),
            extra: toml::Table::new(),
        },
        files,
        skipped_folders: Vec::new(),
        root: String::new(),
        pin: None,
        name: name_of(&request.name),
        clone: None,
        trust_source: None,
        moved_source: None,
        source_change: None,
        plugin_servers: None,
    };
    let mut resolved = build(store, sx, fetched)?;
    let drafts = std::mem::take(&mut resolved.drafts);
    for mut draft in drafts {
        let entry = draft.provenance().entry.clone();
        match keys
            .iter()
            .find(|(name, _)| Some(name) == entry.as_ref())
            .map(|(_, key)| key.clone())
        {
            Some(Ok(source)) => {
                draft.trust_source = Some(source);
                resolved.drafts.push(draft);
            }
            Some(Err(error)) => resolved.skipped.push(Skipped {
                file: draft.provenance().file.clone(),
                entry,
                error,
            }),
            None => resolved.skipped.push(Skipped {
                file: draft.provenance().file.clone(),
                entry,
                error: CoreError::new(
                    ErrorCode::InvalidValue,
                    "Surjection cannot tell what this definition runs from",
                ),
            }),
        }
    }
    if let Some(store) = store {
        let mut blocked = None;
        for draft in &resolved.drafts {
            let source = draft.trust_source.as_ref().expect("set above");
            match sources::refuse_blocked(store, source) {
                Ok(_) => {
                    blocked = None;
                    break;
                }
                Err(err) => blocked = blocked.or(Some(err)),
            }
        }
        if let Some(err) = blocked {
            return Err(err);
        }
    }
    Ok(resolved)
}

fn build(
    store: Option<&Store<'_>>,
    sx: &SkillsEnv<'_>,
    fetched: Fetched,
) -> Result<Resolved, CoreError> {
    let Fetched {
        base,
        files,
        skipped_folders,
        root,
        pin,
        name,
        clone,
        trust_source,
        moved_source,
        source_change,
        plugin_servers,
    } = fetched;
    let ctx = Ctx {
        files: &files,
        skipped: &skipped_folders,
        root: root.clone(),
        git: pin.as_ref(),
        os: sx.env.os(),
        name,
        content_hash: content_hash(&files),
        plugin_servers: plugin_servers.as_deref(),
    };
    let (raws, mut skipped) = convert::all(&ctx);
    // Identical definitions collapse into the first.
    let mut kept: Vec<(RawDraft, Vec<String>)> = Vec::new();
    for raw in raws {
        match kept
            .iter_mut()
            .find(|(first, _)| first.fields == raw.fields && first.os == raw.os)
        {
            Some((_, also_in)) => also_in.push(raw.file),
            None => kept.push((raw, Vec::new())),
        }
    }
    let mut taken = store_ids(store)?;
    let mut aliases = aliases(store, sx)?;
    let scanner = Scanner::new(sx.fs, sx.home);
    let files_scan = scanner.scan_files(&files);
    let mut drafts = Vec::new();
    for (mut raw, also_in) in kept {
        let id = free_id(&id_from_name(&raw.name), &taken);
        if let Err(error) = secure(&mut raw, &id, &mut aliases) {
            skipped.push(Skipped {
                file: raw.file,
                entry: raw.entry,
                error,
            });
            continue;
        }
        let checkout = pin.is_some() && convert::uses_root(&raw, CHECKOUT_TOKEN);
        let root_text = match &pin {
            Some(pin) => checkout_root(&id, pin.path.as_deref()),
            None => root.clone(),
        };
        let mut server = Server::new(id.clone());
        set_launch(&mut server, &raw.fields);
        let body = &mut server.body;
        body.display_name = raw.display_name.clone();
        body.description = raw.description.clone();
        body.os = raw.os.clone();
        body.tools = raw.tools.clone();
        body.client = raw
            .passthrough
            .clone()
            .map(|(client, table)| BTreeMap::from([(client, table)]));
        let mut source = base.clone();
        source.file.clone_from(&raw.file);
        source.converter.clone_from(&raw.converter);
        source.entry.clone_from(&raw.entry);
        source.checkout = checkout.then_some(true);
        body.meta = Some(Meta {
            homepage: raw.homepage.clone(),
            origin: Some(match (&base.catalog, base.kind) {
                (Some(catalog), _) => catalog_origin(catalog),
                (None, ServerSourceKind::Git) => ORIGIN_GIT.to_owned(),
                (None, ServerSourceKind::Local) => ORIGIN_LOCAL.to_owned(),
                (None, ServerSourceKind::Registry) => "catalog".to_owned(),
            }),
            source: Some(source),
            ..Meta::default()
        });
        let fill = |value: &str| {
            value
                .replace(CHECKOUT_TOKEN, &root_text)
                .replace(ID_TOKEN, &id)
        };
        edit_server(&mut server, &fill);
        let setup = raw.setup.iter().map(|step| fill(step)).collect();
        if let Some(error) = server.validate(Some(&id)).first_error(None) {
            skipped.push(Skipped {
                file: raw.file,
                entry: raw.entry,
                error,
            });
            continue;
        }
        taken.insert(id);
        let mut scan = files_scan.clone();
        scan.merge(scan_commands(&scanner, &server));
        let key = match &raw.entry {
            Some(entry) => format!("{}#{entry}", raw.file),
            None => raw.file.clone(),
        };
        drafts.push(Draft {
            key,
            kind: raw.kind,
            server,
            inputs: raw.inputs,
            runs_repo_code: raw.runs_repo_code || checkout,
            checkout,
            pinned: raw.pinned,
            setup,
            also_in,
            scan,
            trust_source: None,
        });
    }
    Ok(Resolved {
        base,
        drafts,
        skipped,
        skipped_folders,
        files,
        files_scan,
        trust_source,
        moved_source,
        source_change,
        clone,
        spent: false,
    })
}

// --------------------------------------------------------------- checkouts

/// `<checkout>/.git/surjection-checkout`.
fn marker_path(dir: &Path) -> PathBuf {
    dir.join(".git").join(MARKER_FILE)
}

fn marker_text(commit: &str, url: &str) -> String {
    format!("{commit}\n{url}\n")
}

/// Whether the checkout of server `id` below `surjection_home` holds what
/// `source` names (its marker: commit and URL).
fn checkout_current(fs: &dyn Fs, surjection_home: &Path, id: &str, source: &ServerSource) -> bool {
    let dir = surjection_home.join(CHECKOUTS_DIR).join(id);
    let Ok(bytes) = fs
        .read(&marker_path(&dir))
        .or_else(|_| fs.read(&dir.join(".git").join(LEGACY_MARKER_FILE)))
    else {
        return false;
    };
    let expected = marker_text(
        source.commit.as_deref().unwrap_or_default(),
        source.url.as_deref().unwrap_or_default(),
    );
    String::from_utf8_lossy(&bytes) == expected
}

/// Whether `server` may run on this machine (checked when its entries are
/// rendered): a server from a Git repository that runs from a checkout
/// needs this machine's checkout at the commit and URL its file names
/// (`checkout_out_of_date` otherwise, so the old code never runs with the
/// new command); a server from a local folder runs only on the machine
/// that added it (`folder_on_other_machine`).
pub fn runnable(fs: &dyn Fs, surjection_home: &Path, server: &Server) -> Result<(), CoreError> {
    let Some(source) = server
        .body
        .meta
        .as_ref()
        .and_then(|meta| meta.source.as_ref())
    else {
        return Ok(());
    };
    match source.kind {
        ServerSourceKind::Git if source.uses_checkout() => {
            if checkout_current(fs, surjection_home, &server.id, source) {
                Ok(())
            } else {
                Err(CoreError::new(
                    ErrorCode::CheckoutOutOfDate,
                    format!(
                        "checkout out of date: run `surject server checkout {}`",
                        server.id
                    ),
                ))
            }
        }
        ServerSourceKind::Local => match &source.machine {
            Some(machine) => {
                let here = Machine::load(fs, &surjection_home.join(STATE_DIR))?;
                if here.as_ref().is_some_and(|here| &here.id == machine) {
                    Ok(())
                } else {
                    Err(CoreError::new(
                        ErrorCode::FolderOnOtherMachine,
                        "added from a folder on another machine; it does not run here",
                    ))
                }
            }
            None => Ok(()),
        },
        ServerSourceKind::Git | ServerSourceKind::Registry => Ok(()),
    }
}

/// A checkout being put in place: the new folder placed (moved from a
/// clone, or copied), the folder it replaces moved aside. [`Swap::finish`]
/// keeps the new one (and deletes the old) or undoes it all.
#[derive(Debug)]
struct Swap {
    target: PathBuf,
    aside: Option<PathBuf>,
    /// Where the new folder was moved from, to move it back on undo.
    moved_from: Option<PathBuf>,
}

impl Swap {
    fn finish(self, fs: &dyn Fs, keep: bool) {
        if keep {
            if let Some(aside) = &self.aside {
                let _ = remove_dir(fs, aside);
            }
            return;
        }
        match &self.moved_from {
            Some(from) => {
                let _ = std::fs::rename(&self.target, from);
            }
            None => {
                let _ = remove_dir(fs, &self.target);
            }
        }
        if let Some(aside) = &self.aside {
            let _ = std::fs::rename(aside, &self.target);
        }
    }
}

/// `<SURJECTION_HOME>/servers/.old-<id>-<ulid>`.
fn aside_path(sx: &SkillsEnv<'_>, id: &str) -> Result<PathBuf, CoreError> {
    Ok(sx.home.path.join(CHECKOUTS_DIR).join(format!(
        "{ASIDE_PREFIX}{id}-{}",
        ids::new_ulid(sx.env.now())?.to_ascii_lowercase()
    )))
}

/// Moves the checkout of `id` aside, if there is one.
fn set_aside(sx: &SkillsEnv<'_>, id: &str) -> Result<Option<(PathBuf, PathBuf)>, CoreError> {
    let target = checkout_dir(sx, id);
    confine(sx.fs, &target)?;
    if !sx.fs.exists(&target) {
        return Ok(None);
    }
    let aside = aside_path(sx, id)?;
    std::fs::rename(&target, &aside)
        .map_err(|err| io_error("cannot move the old checkout aside", &target, &err))?;
    Ok(Some((aside, target)))
}

/// Copies the tree `from` into `to` (a second checkout of one clone).
fn copy_tree(fs: &dyn Fs, from: &Path, to: &Path) -> Result<(), CoreError> {
    confine(fs, from)?;
    confine(fs, to)?;
    std::fs::create_dir_all(to).map_err(|err| io_error("cannot create directory", to, &err))?;
    let entries =
        std::fs::read_dir(from).map_err(|err| io_error("cannot list directory", from, &err))?;
    for entry in entries {
        let entry = entry.map_err(|err| io_error("cannot list directory", from, &err))?;
        let kind = entry
            .file_type()
            .map_err(|err| io_error("cannot read file metadata", &entry.path(), &err))?;
        let target = to.join(entry.file_name());
        if kind.is_dir() {
            copy_tree(fs, &entry.path(), &target)?;
        } else if kind.is_file() {
            std::fs::copy(entry.path(), &target)
                .map_err(|err| io_error("cannot copy file", &target, &err))?;
        }
    }
    Ok(())
}

/// Puts `clone` in place as the checkout of `id` (moved, or copied with
/// `copy`), marked with `commit` and `url`; an existing checkout is moved
/// aside. On an error nothing is left changed.
fn place_checkout(
    sx: &SkillsEnv<'_>,
    clone: &Path,
    id: &str,
    copy: bool,
    commit: &str,
    url: &str,
) -> Result<Swap, CoreError> {
    let target = checkout_dir(sx, id);
    confine(sx.fs, clone)?;
    confine(sx.fs, &target)?;
    let aside = set_aside(sx, id)?.map(|(aside, _)| aside);
    let mut swap = Swap {
        target: target.clone(),
        aside,
        moved_from: None,
    };
    let place = |swap: &mut Swap| -> Result<(), CoreError> {
        if let Some(parent) = target.parent() {
            sx.fs
                .create_dir_all(parent)
                .map_err(|err| io_error("cannot create directory", parent, &err))?;
        }
        if copy {
            copy_tree(sx.fs, clone, &target)?;
        } else {
            std::fs::rename(clone, &target)
                .map_err(|err| io_error("cannot move the clone", &target, &err))?;
            swap.moved_from = Some(clone.to_path_buf());
        }
        let marker = marker_path(&target);
        sx.fs
            .write(&marker, marker_text(commit, url).as_bytes())
            .map_err(|err| io_error("cannot mark the checkout", &marker, &err))
    };
    if let Err(err) = place(&mut swap) {
        swap.finish(sx.fs, false);
        return Err(err);
    }
    Ok(swap)
}

/// Checkouts of removed servers, moved aside under the store lock until
/// the removal commits ([`CheckoutRemoval::finish`]).
#[derive(Debug, Default)]
pub struct CheckoutRemoval {
    moved: Vec<(PathBuf, PathBuf)>,
}

impl CheckoutRemoval {
    /// Moves the checkouts of `ids` aside (call it inside the removal's
    /// transaction).
    pub fn begin(sx: &SkillsEnv<'_>, ids: &[String]) -> Result<Self, CoreError> {
        let mut removal = Self::default();
        for id in ids {
            ids::check(ids::IdKind::Server, id)?;
            match set_aside(sx, id) {
                Ok(Some(pair)) => removal.moved.push(pair),
                Ok(None) => {}
                Err(err) => {
                    removal.finish(sx.fs, false);
                    return Err(err);
                }
            }
        }
        Ok(removal)
    }

    /// Deletes the checkouts (`committed`) or puts them back.
    pub fn finish(self, fs: &dyn Fs, committed: bool) {
        for (aside, target) in self.moved {
            if committed {
                let _ = remove_dir(fs, &aside);
            } else {
                let _ = std::fs::rename(&aside, &target);
            }
        }
    }
}

/// Removes temporary clones of resolves and checkouts moved aside that are
/// older than `older_than` (left by a crash or an app that ended with
/// reviews open). Returns how many were removed.
pub fn sweep_temp_clones(sx: &SkillsEnv<'_>, older_than: Duration) -> usize {
    let now = sx.env.now();
    let sweep = |dir: PathBuf, prefix: &str| {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            return 0;
        };
        entries
            .flatten()
            .filter(|entry| entry.file_name().to_string_lossy().starts_with(prefix))
            .filter(|entry| {
                entry
                    .metadata()
                    .and_then(|meta| meta.modified())
                    .is_ok_and(|modified| {
                        now.duration_since(modified).unwrap_or_default() >= older_than
                    })
            })
            .filter(|entry| std::fs::remove_dir_all(entry.path()).is_ok())
            .count()
    };
    sweep(sx.home.cache_dir().join(TEMP_DIR), ".tmp-")
        + sweep(sx.home.path.join(CHECKOUTS_DIR), ASIDE_PREFIX)
}

// -------------------------------------------------------------------- save

/// One draft to save, as the user edited it.
#[derive(Debug, Clone)]
pub struct Pick {
    /// [`Draft::key`].
    pub key: String,
    /// The server to store: its id, launch fields, enablement and names as
    /// edited; `meta.origin` and `meta.source` are set from the draft.
    pub server: Server,
    /// The user's answer for what this draft runs, when it is gated on
    /// its own source ([`Draft::trust_source`]: registry entries, which
    /// can name several). `None` leaves it to [`Decisions::trust`] when
    /// the picks run from one source.
    pub trust: Option<TrustGrant>,
}

/// What [`save`] did.
#[derive(Debug, Clone)]
pub struct Saved {
    pub ids: Vec<String>,
    pub commit: Option<CommitId>,
    pub apply: Option<ApplyReport>,
    /// The scan the gate checked: the folder's files and every saved
    /// launch line.
    pub scan: ScanReport,
}

/// The server `pick` stores for `draft`.
fn picked_server(draft: &Draft, pick: &Pick) -> Result<Server, CoreError> {
    let mut server = pick.server.clone();
    ids::check(ids::IdKind::Server, &server.id)?;
    rename_id(&mut server, &draft.server.id, &pick.server.id);
    let meta = server.body.meta.get_or_insert_with(Meta::default);
    let draft_meta = draft.server.body.meta.as_ref();
    meta.origin = draft_meta.and_then(|m| m.origin.clone());
    let mut source = draft.provenance().clone();
    if draft.checkout {
        source.checkout = Some(true);
    }
    meta.source = Some(source);
    if meta.homepage.is_none() {
        meta.homepage = draft_meta.and_then(|m| m.homepage.clone());
    }
    if let Some(error) = server.validate(Some(&server.id)).first_error(None) {
        return Err(error);
    }
    Ok(server)
}

/// Where a commit message says the servers come from: the URL, or the
/// folder (`${home}/...`, or only its name when it is outside the home
/// folder: no absolute path goes into history).
fn from_text(source: &ServerSource) -> String {
    if source.kind == ServerSourceKind::Registry {
        let entry = source.catalog.as_deref().unwrap_or_default();
        return match &source.version {
            Some(version) => format!("catalog {entry}@{version}"),
            None => format!("catalog {entry}"),
        };
    }
    let place = match (&source.url, &source.folder) {
        (Some(url), _) => url.clone(),
        (None, Some(folder)) if folder.starts_with("${home}") => folder.clone(),
        (None, Some(folder)) => format!("folder {}", name_of(folder)),
        (None, None) => String::new(),
    };
    match &source.commit {
        Some(commit) => format!("{place}@{}", &commit[..commit.len().min(7)]),
        None => place,
    }
}

/// Stores the picked drafts (one commit, with the instant apply) when the
/// decisions let them through: the source must be trusted or
/// [`Decisions::trust`] carries the user's answer (`source_trust_required`,
/// `source_blocked`); then a `dangerous` scan of the folder's files and
/// every saved launch line needs [`Decisions::allow_dangerous`]
/// (`scan_blocked`). A taken id is `already_exists`. Checkouts are placed
/// under the store lock and undone when the commit fails; a local folder's
/// servers are bound to this machine. On an error `resolved` stays usable;
/// once saved it is spent.
pub fn save(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    ax: &ApplyEnv<'_>,
    resolved: &mut Resolved,
    picks: &[Pick],
    decisions: &Decisions,
) -> Result<Saved, CoreError> {
    if resolved.spent {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            "these drafts are already saved",
        ));
    }
    if picks.is_empty() {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            "pick at least one draft to save",
        ));
    }
    let mut servers: Vec<(Server, bool)> = Vec::new();
    let mut gated: Vec<(&Draft, Option<TrustGrant>)> = Vec::new();
    for pick in picks {
        let draft = resolved
            .drafts
            .iter()
            .find(|draft| draft.key == pick.key)
            .ok_or_else(|| {
                CoreError::new(ErrorCode::NotFound, format!("no draft {:?}", pick.key))
            })?;
        let server = picked_server(draft, pick)?;
        if servers.iter().any(|(other, _)| other.id == server.id)
            || store.server(&server.id)?.is_some()
        {
            return Err(CoreError::new(
                ErrorCode::AlreadyExists,
                format!("server {:?} already exists", server.id),
            ));
        }
        servers.push((server, draft.checkout));
        gated.push((draft, pick.trust));
    }
    resolved.admit(store, decisions, &gated)?;
    drop(gated);
    let scanner = Scanner::new(sx.fs, sx.home);
    let mut report = resolved.files_scan.clone();
    for (server, _) in &servers {
        report.merge(scan_commands(&scanner, server));
    }
    scan::gate(&report, decisions.allow_dangerous)?;

    let ids: Vec<String> = servers
        .iter()
        .map(|(server, _)| server.id.clone())
        .collect();
    let from = from_text(&resolved.base);
    let summary = match ids.as_slice() {
        [one] => format!("server: add {one} from {from}"),
        many => format!(
            "server: add {} servers ({}) from {from}",
            many.len(),
            many.join(", ")
        ),
    };
    let operation = ids
        .iter()
        .fold(Operation::new("server.add", summary), |operation, id| {
            operation.entity(format!("server/{id}"))
        });
    let clone = resolved.clone.clone();
    let commit = resolved.base.commit.clone().unwrap_or_default();
    let url = resolved.base.url.clone().unwrap_or_default();
    let mut swaps: Vec<Swap> = Vec::new();
    let result = store.transaction(operation, |tx| {
        // Under the store lock: no other save or removal of these ids
        // runs between placing the checkouts and the commit.
        let wanted: Vec<&str> = servers
            .iter()
            .filter(|(_, checkout)| *checkout)
            .map(|(server, _)| server.id.as_str())
            .collect();
        if !wanted.is_empty() {
            let clone = clone.as_deref().ok_or_else(|| {
                CoreError::new(
                    ErrorCode::InvalidValue,
                    "the clone of this source is gone; resolve it again",
                )
            })?;
            // Copies first, then the move of the clone itself.
            for (index, id) in wanted.iter().enumerate() {
                let last = index + 1 == wanted.len();
                swaps.push(place_checkout(sx, clone, id, !last, &commit, &url)?);
            }
        }
        let machine = tx.machine().id.clone();
        for (server, _) in &servers {
            let mut server = server.clone();
            if let Some(source) = server.body.meta.as_mut().and_then(|m| m.source.as_mut())
                && source.kind == ServerSourceKind::Local
            {
                source.machine = Some(machine.clone());
            }
            tx.add_server(server)?;
        }
        instant_apply(tx, ax, &Touched::Servers(ids.clone()))
    });
    let keep = result.is_ok();
    let moved = swaps.iter().any(|swap| swap.moved_from.is_some());
    for swap in swaps {
        swap.finish(sx.fs, keep);
    }
    let committed = result?;
    resolved.spent = true;
    if moved {
        resolved.clone = None;
    }
    Ok(Saved {
        ids,
        commit: committed.commit,
        apply: committed.value,
        scan: report,
    })
}

// ------------------------------------------------------------------ update

/// One launch field that differs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FieldChange {
    /// `transport`, `command`, `args`, `url`, `cwd`, `env.NAME`,
    /// `headers.NAME`, each also as `os.<name>.<field>`.
    pub field: String,
    pub old: Option<String>,
    pub new: Option<String>,
}

/// What [`check_update`] found.
#[derive(Debug, Clone)]
pub struct UpdateCheck {
    pub id: String,
    pub status: UpdateStatus,
    /// The commit the server came from.
    pub current: Option<String>,
    /// The source's commit now; for a local folder, the content hash of
    /// what was read (pass it to [`update`] as `expected`).
    pub latest: Option<String>,
    /// A registry entry's version now (its `latest` is the content hash
    /// of its `server.json`, so other content under one version is seen).
    pub version: Option<String>,
    pub changes: Vec<FieldChange>,
    /// Changed files of a checkout ([`SKIP_DIRS`] left out).
    pub files: Vec<FileChange>,
    /// The server an update stores.
    pub server: Option<Server>,
    /// The folder's files and every new launch line, when an update is
    /// available.
    pub scan: Option<ScanReport>,
    pub trust: Option<TrustCheck>,
    /// The trust check of where the host redirected the repository, when
    /// that is another source; an update needs its answer too.
    pub moved_trust: Option<TrustCheck>,
    pub source_change: Option<SourceChange>,
    pub runs_repo_code: bool,
    /// The setup steps of the new version ([`setup_text`]).
    pub setup: Vec<String>,
    /// The update replaces the checkout: what its setup steps installed
    /// there (dependencies, a build) has to be done again.
    pub setup_again: bool,
    /// This machine's checkout is missing or not at the commit the server
    /// file names; its entries are blocked until [`restore_checkout`].
    pub checkout_out_of_date: bool,
    pub error: Option<CoreError>,
}

impl UpdateCheck {
    fn new(id: &str, status: UpdateStatus, current: Option<String>) -> Self {
        Self {
            id: id.to_owned(),
            status,
            current,
            latest: None,
            version: None,
            changes: Vec::new(),
            files: Vec::new(),
            server: None,
            scan: None,
            trust: None,
            moved_trust: None,
            source_change: None,
            runs_repo_code: false,
            setup: Vec::new(),
            setup_again: false,
            checkout_out_of_date: false,
            error: None,
        }
    }
}

fn stored(store: &Store<'_>, id: &str) -> Result<(Server, Option<ServerSource>), CoreError> {
    ids::check(ids::IdKind::Server, id)?;
    let doc = store.server(id)?.ok_or_else(|| {
        CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
    })?;
    let server = doc.into_value();
    let source = server
        .body
        .meta
        .as_ref()
        .and_then(|meta| meta.source.clone());
    Ok((server, source))
}

/// The `mcpServers` of the marketplace entry a catalog install came from,
/// read again from the catalog's cached index (no network): an update
/// drafts what the install drafted.
fn catalog_servers(store: &Store<'_>, sx: &SkillsEnv<'_>, catalog: Option<&str>) -> Option<String> {
    let (catalog, entry) = catalog?.split_once('/')?;
    crate::catalog::cached_entry(sx, Some(store), catalog, entry)
        .ok()?
        .mcp_servers
}

fn request_of(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    source: &ServerSource,
) -> Result<ResolveRequest, CoreError> {
    match source.kind {
        ServerSourceKind::Git => {
            let url = source.url.clone().ok_or_else(|| {
                CoreError::new(ErrorCode::MissingField, "the git source has no url")
            })?;
            Ok(ResolveRequest {
                source: Source::Git {
                    url,
                    git_ref: None,
                    path: None,
                },
                git_ref: source.git_ref.clone(),
                path: source.path.clone(),
                catalog: source.catalog.clone(),
                mcp_servers: catalog_servers(store, sx, source.catalog.as_deref()),
            })
        }
        ServerSourceKind::Local => {
            let folder = source.folder.as_deref().ok_or_else(|| {
                CoreError::new(ErrorCode::MissingField, "the local source has no folder")
            })?;
            Ok(ResolveRequest::new(Source::Local(folder_of(sx, folder))))
        }
        ServerSourceKind::Registry => Err(CoreError::new(
            ErrorCode::InvalidValue,
            "a registry source is read through its catalog",
        )),
    }
}

/// The value at `field` (`command`, `url`, `cwd`, `env.X`, `headers.X`,
/// `args[N]`, each optionally `os.<name>.`-prefixed) of `server`.
fn field_value<'a>(server: &'a Server, field: &str) -> Option<&'a str> {
    let (fields_command, fields_args, fields_url, fields_cwd, fields_env, fields_headers, rest) =
        match field.strip_prefix("os.") {
            Some(rest) => {
                let (os, rest) = rest.split_once('.')?;
                let over = &server.body.os.as_ref()?.get(os)?.fields;
                (
                    &over.command,
                    &over.args,
                    &over.url,
                    &over.cwd,
                    &over.env,
                    &over.headers,
                    rest,
                )
            }
            None => {
                let body = &server.body;
                (
                    &body.command,
                    &body.args,
                    &body.url,
                    &body.cwd,
                    &body.env,
                    &body.headers,
                    field,
                )
            }
        };
    match rest {
        "command" => fields_command.as_deref(),
        "url" => fields_url.as_deref(),
        "cwd" => fields_cwd.as_deref(),
        _ => {
            if let Some(name) = rest.strip_prefix("env.") {
                return fields_env.as_ref()?.get(name).map(String::as_str);
            }
            if let Some(name) = rest.strip_prefix("headers.") {
                return fields_headers.as_ref()?.get(name).map(String::as_str);
            }
            let index: usize = rest
                .strip_prefix("args[")?
                .strip_suffix(']')?
                .parse()
                .ok()?;
            fields_args
                .as_ref()?
                .get(index.checked_sub(1)?)
                .map(String::as_str)
        }
    }
}

/// The first `${secret:<alias>}` alias in `text`.
fn secret_alias(text: &str) -> Option<&str> {
    let start = text.find("${secret:")? + "${secret:".len();
    let end = text[start..].find('}')?;
    Some(&text[start..start + end])
}

/// Keeps the secret aliases `stored` uses: a re-read draft names its
/// secrets after a fresh id, so each one whose field already held a
/// reference gets that reference's alias back.
fn keep_aliases(proposed: &mut Server, stored: &Server, inputs: &[DraftInput]) {
    let renames: Vec<(String, String)> = inputs
        .iter()
        .filter(|input| input.secret)
        .filter_map(|input| {
            let new = input.alias.clone()?;
            let old = secret_alias(field_value(stored, &input.field)?)?.to_owned();
            (old != new).then_some((new, old))
        })
        .collect();
    if renames.is_empty() {
        return;
    }
    edit_server(proposed, &|value| {
        renames.iter().fold(value.to_owned(), |value, (new, old)| {
            value.replace(&format!("${{secret:{new}}}"), &format!("${{secret:{old}}}"))
        })
    });
}

/// The fields of `a` and `b` that differ, named with `prefix`.
fn diff_fields(prefix: &str, a: &ServerFields, b: &ServerFields, changes: &mut Vec<FieldChange>) {
    let mut push = |field: &str, old: Option<String>, new: Option<String>| {
        if old != new {
            changes.push(FieldChange {
                field: format!("{prefix}{field}"),
                old,
                new,
            });
        }
    };
    push(
        "transport",
        a.transport.map(|t| t.as_str().to_owned()),
        b.transport.map(|t| t.as_str().to_owned()),
    );
    push("command", a.command.clone(), b.command.clone());
    let join = |args: &Option<Vec<String>>| args.as_ref().map(|args| args.join(" "));
    push("args", join(&a.args), join(&b.args));
    push("url", a.url.clone(), b.url.clone());
    push("cwd", a.cwd.clone(), b.cwd.clone());
    for (label, old, new) in [("env", &a.env, &b.env), ("headers", &a.headers, &b.headers)] {
        let keys: BTreeSet<&String> = old
            .iter()
            .flatten()
            .chain(new.iter().flatten())
            .map(|(k, _)| k)
            .collect();
        for key in keys {
            let get = |map: &Option<BTreeMap<String, String>>| {
                map.as_ref().and_then(|m| m.get(key).cloned())
            };
            push(&format!("{label}.{key}"), get(old), get(new));
        }
    }
}

/// The launch fields that differ between `old` and `new`, base and each
/// override.
fn field_changes(old: &Server, new: &Server) -> Vec<FieldChange> {
    let mut changes = Vec::new();
    diff_fields("", &old.body.fields(), &new.body.fields(), &mut changes);
    let names: BTreeSet<&String> = old
        .body
        .os
        .iter()
        .flatten()
        .chain(new.body.os.iter().flatten())
        .map(|(name, _)| name)
        .collect();
    let empty = ServerFields::default();
    for name in names {
        let get = |server: &Server| {
            server
                .body
                .os
                .as_ref()
                .and_then(|os| os.get(name.as_str()))
                .map_or(empty.clone(), |over| over.fields.clone())
        };
        diff_fields(&format!("os.{name}."), &get(old), &get(new), &mut changes);
    }
    changes
}

/// `stored` with `draft`'s launch fields and provenance under the stored
/// id: `env` and `headers` keys present before and after keep the stored
/// value, secret references keep their aliases, the machine a local folder
/// is bound to stays.
fn updated_server(stored: &Server, draft: &Draft) -> Server {
    let mut server = stored.clone();
    let mut fields = draft.server.body.fields();
    let keep = |new: &mut Option<BTreeMap<String, String>>,

                old: &Option<BTreeMap<String, String>>| {
        if let (Some(new), Some(old)) = (new.as_mut(), old.as_ref()) {
            for (key, value) in new.iter_mut() {
                if let Some(kept) = old.get(key) {
                    value.clone_from(kept);
                }
            }
        }
    };
    keep(&mut fields.env, &stored.body.env);
    keep(&mut fields.headers, &stored.body.headers);
    set_launch(&mut server, &fields);
    server.body.os = draft.server.body.os.clone();
    rename_id(&mut server, &draft.server.id, &stored.id);
    keep_aliases(&mut server, stored, &draft.inputs);
    let machine = stored
        .body
        .meta
        .as_ref()
        .and_then(|meta| meta.source.as_ref())
        .and_then(|source| source.machine.clone());
    let meta = server.body.meta.get_or_insert_with(Meta::default);
    let mut source = draft.provenance().clone();
    source.machine = machine;
    meta.source = Some(source);
    server
}

/// Files that differ between a checkout and the source now.
fn file_changes(old: &SkillFiles, new: &SkillFiles) -> Vec<FileChange> {
    let paths: BTreeSet<&String> = old.keys().chain(new.keys()).collect();
    paths
        .into_iter()
        .filter_map(|path| {
            let kind = match (old.get(path), new.get(path)) {
                (Some(a), Some(b)) if a == b => return None,
                (Some(_), Some(_)) => ChangeKind::Modified,
                (None, Some(_)) => ChangeKind::Added,
                (Some(_), None) => ChangeKind::Removed,
                (None, None) => return None,
            };
            let script = kind != ChangeKind::Removed
                && new
                    .get(path)
                    .is_some_and(|bytes| looks_executable(path, bytes));
            Some(FileChange {
                path: path.clone(),
                kind,
                script,
            })
        })
        .collect()
}

/// The folder of `id`'s checkout that holds the server's files.
fn checkout_folder(sx: &SkillsEnv<'_>, id: &str, source: &ServerSource) -> PathBuf {
    let dir = checkout_dir(sx, id);
    match &source.path {
        Some(path) => join_rel(&dir, path),
        None => dir,
    }
}

/// This machine's id, if it has one yet.
fn this_machine(sx: &SkillsEnv<'_>) -> Result<Option<String>, CoreError> {
    Ok(Machine::load(sx.fs, &sx.home.state_dir())?.map(|machine| machine.id))
}

/// The check and what an update would store.
struct Latest {
    check: UpdateCheck,
    resolved: Option<Resolved>,
}

fn latest(store: &Store<'_>, sx: &SkillsEnv<'_>, id: &str) -> Result<Latest, CoreError> {
    let (server, source) = stored(store, id)?;
    let Some(source) = source else {
        return Ok(Latest {
            check: UpdateCheck::new(id, UpdateStatus::NotTracked, None),
            resolved: None,
        });
    };
    let registry = source.kind == ServerSourceKind::Registry;
    let current = if registry {
        source.version.clone()
    } else {
        source.commit.clone()
    };
    let mut check = UpdateCheck::new(id, UpdateStatus::UpToDate, current.clone());
    check.checkout_out_of_date =
        source.uses_checkout() && !checkout_current(sx.fs, &sx.home.path, id, &source);
    let gated = match source.kind {
        ServerSourceKind::Git => source
            .url
            .as_deref()
            .and_then(|url| SourceRef::from_git_url(url).ok()),
        ServerSourceKind::Local => source
            .folder
            .as_deref()
            .map(|f| folder_of(sx, f))
            .and_then(|folder| SourceRef::from_local_path(&folder).ok()),
        // Its trust source is in the entry, read below.
        ServerSourceKind::Registry => None,
    };
    let not_fetched = |mut check: UpdateCheck,

                       status: UpdateStatus,
                       err: CoreError|

     -> Result<Latest, CoreError> {
        check.status = status;
        check.trust = gated
            .as_ref()
            .map(|source| sources::check(store, source))
            .transpose()?;
        check.error = Some(err);
        Ok(Latest {
            check,
            resolved: None,
        })
    };
    if source.kind == ServerSourceKind::Local
        && let Some(machine) = &source.machine
        && this_machine(sx)?.as_ref() != Some(machine)
    {
        let err = CoreError::new(
            ErrorCode::FolderOnOtherMachine,
            "added from a folder on another machine; check it there",
        );
        return not_fetched(check, UpdateStatus::Unreachable, err);
    }
    let pinned = match source.kind {
        ServerSourceKind::Git => source.git_ref.as_deref().is_some_and(is_commit_ref),
        ServerSourceKind::Registry => source.git_ref.is_some(),
        ServerSourceKind::Local => false,
    };
    if pinned {
        // Pinned to a commit or a registry version: nothing to follow.
        check.latest = current;
        return Ok(Latest {
            check,
            resolved: None,
        });
    }
    let resolved = if registry {
        crate::catalog::registry_latest(store, sx, &source)
            .and_then(|request| resolve_registry(Some(store), sx, &request))
    } else {
        request_of(store, sx, &source).and_then(|request| resolve(Some(store), sx, &request))
    };
    let resolved = match resolved {
        Ok(resolved) => resolved,
        Err(err) if err.code() == ErrorCode::SourceBlocked => {
            return not_fetched(check, UpdateStatus::Blocked, err);
        }
        // Whatever stops the read (unreachable, gone, too large) is this
        // server's result, not an error of the whole check.
        Err(err) => return not_fetched(check, UpdateStatus::Unreachable, err),
    };
    let latest_commit = match source.kind {
        ServerSourceKind::Git => resolved.base.commit.clone(),
        ServerSourceKind::Local => Some(content_hash(&resolved.files)),
        // The content, not the version string: a registry serving other
        // content under the same version is another update to review.
        ServerSourceKind::Registry => Some(content_hash(&resolved.files)),
    };
    let mut change = resolved.source_change.clone();
    if change.is_none()
        && let (Some(old), Some(new), Some(clone), Some(url)) = (
            source.commit.as_deref(),
            resolved.base.commit.as_deref(),
            resolved.clone.as_deref(),
            source.url.as_deref(),
        )
    {
        let git = git_path(sx)?;
        let in_clone = |args: &[&OsStr]| run_git(sx, &git, clone, args);
        if sources::detect::history_rewritten(&in_clone, url, source.git_ref.as_deref(), old, new)?
        {
            change = Some(SourceChange {
                kind: SourceChangeKind::HistoryRewritten,
                detail: None,
            });
        }
    }
    if let (Some(gated), Some(change)) = (resolved.trust_source(), &change) {
        sources::lapse(store, gated, change)?;
    }
    check.trust = resolved
        .trust_source()
        .map(|source| sources::check(store, source))
        .transpose()?;
    check.moved_trust = resolved
        .moved_source()
        .map(|source| sources::check(store, source))
        .transpose()?;
    check.source_change = change;
    check.latest.clone_from(&latest_commit);
    if registry {
        check.version.clone_from(&resolved.base.version);
    }
    let Some(draft) = resolved.drafts.iter().find(|draft| {
        let p = draft.provenance();
        p.file == source.file && p.converter == source.converter && p.entry == source.entry
    }) else {
        let err = CoreError::new(
            ErrorCode::SourceUnreachable,
            format!(
                "the source no longer holds this server ({}{})",
                source.file,
                source
                    .entry
                    .as_deref()
                    .map(|entry| format!(" {entry}"))
                    .unwrap_or_default()
            ),
        );
        return not_fetched(check, UpdateStatus::Unreachable, err);
    };
    if let Some(own) = &draft.trust_source {
        check.trust = Some(sources::check(store, own)?);
        if let Err(err) = sources::refuse_blocked(store, own) {
            check.status = UpdateStatus::Blocked;
            check.error = Some(err);
            return Ok(Latest {
                check,
                resolved: None,
            });
        }
    }
    let proposed = updated_server(&server, draft);
    check.changes = field_changes(&server, &proposed);
    check.setup = rename_steps(&draft.setup, &draft.server.id, id);
    if draft.checkout {
        let folder = checkout_folder(sx, id, &source);
        if sx.fs.is_dir(&folder) {
            match read_source(sx.fs, &folder) {
                Ok((files, _)) => check.files = file_changes(&files, &resolved.files),
                Err(err) => return not_fetched(check, UpdateStatus::Unreachable, err),
            }
        }
    }
    let moved_on = match source.kind {
        ServerSourceKind::Git => current.is_some() && resolved.base.commit != current,
        ServerSourceKind::Registry => current.is_some() && resolved.base.version != current,
        ServerSourceKind::Local => false,
    };
    if !check.changes.is_empty() || moved_on || !check.files.is_empty() {
        check.status = UpdateStatus::Available;
        check.setup_again = draft.checkout && !check.setup.is_empty();
        let scanner = Scanner::new(sx.fs, sx.home);
        let mut scan = resolved.files_scan.clone();
        scan.merge(scan_commands(&scanner, &proposed));
        check.scan = Some(scan);
    }
    check.runs_repo_code = draft.runs_repo_code;
    check.server = Some(proposed);
    Ok(Latest {
        check,
        resolved: Some(resolved),
    })
}

/// Checks a source server for an update: reads its source again (a fresh
/// temporary clone, or the folder) and compares the definition it gives
/// now with the stored one. Whatever stops the read (unreachable, gone,
/// too large, a folder of another machine) is reported in the check, not
/// returned as an error. A force-push or a move of a trusted source makes
/// its trust lapse (one store commit).
pub fn check_update(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    id: &str,
) -> Result<UpdateCheck, CoreError> {
    Ok(latest(store, sx, id)?.check)
}

/// What [`update`] did.
#[derive(Debug, Clone)]
pub struct Updated {
    pub id: String,
    pub from: Option<String>,
    pub to: Option<String>,
    pub changes: Vec<FieldChange>,
    pub commit: Option<CommitId>,
    pub apply: Option<ApplyReport>,
    /// `None` when nothing was updated (up to date).
    pub scan: Option<ScanReport>,
}

/// Updates a source server to what its source gives now (one commit,
/// `server: update <id> to <sha7>`, with the instant apply): the launch
/// fields are replaced, `env` and `headers` values of keys kept keep the
/// stored value, secret references keep their aliases, a checkout is
/// replaced: the new one is built beside the old, committed, then swapped
/// (the old stays when anything fails). `expected` is what the user
/// reviewed (the commit, or a folder's content hash): another one is
/// `entry_changed`. The gates are those of [`save`]. Nothing is written
/// when it is up to date.
pub fn update(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    ax: &ApplyEnv<'_>,
    id: &str,
    expected: Option<&str>,
    decisions: &Decisions,
) -> Result<Updated, CoreError> {
    let Latest { check, resolved } = latest(store, sx, id)?;
    match check.status {
        UpdateStatus::NotTracked => {
            return Err(CoreError::new(
                ErrorCode::InvalidValue,
                format!("server {id:?} does not come from a git repository, folder or catalog"),
            ));
        }
        UpdateStatus::Unreachable | UpdateStatus::Blocked => {
            return Err(check.error.unwrap_or_else(|| {
                CoreError::new(ErrorCode::SourceUnreachable, "the source cannot be reached")
            }));
        }
        _ => {}
    }
    if let Some(expected) = expected
        && check.latest.as_deref() != Some(expected)
    {
        return Err(CoreError::new(
            ErrorCode::EntryChanged,
            "the source changed since it was checked; check again and review it",
        ));
    }
    let (Some(mut resolved), Some(server), UpdateStatus::Available) =
        (resolved, check.server.clone(), check.status)
    else {
        return Ok(Updated {
            id: id.to_owned(),
            from: check.current.clone(),
            to: check.version.clone().or_else(|| check.latest.clone()),
            changes: Vec::new(),
            commit: None,
            apply: None,
            scan: check.scan,
        });
    };
    let source = server
        .body
        .meta
        .as_ref()
        .and_then(|meta| meta.source.clone())
        .expect("a source server");
    let gated: Vec<(&Draft, Option<TrustGrant>)> = resolved
        .drafts
        .iter()
        .filter(|draft| {
            let p = draft.provenance();
            p.file == source.file && p.converter == source.converter && p.entry == source.entry
        })
        .map(|draft| (draft, None))
        .collect();
    resolved.admit(store, decisions, &gated)?;
    drop(gated);
    let scan = check.scan.clone().expect("an available update is scanned");
    scan::gate(&scan, decisions.allow_dangerous)?;
    let summary = match source.kind {
        ServerSourceKind::Git => {
            let commit = source.commit.as_deref().unwrap_or_default();
            format!("server: update {id} to {}", &commit[..commit.len().min(7)])
        }
        ServerSourceKind::Registry => format!(
            "server: update {id} to {}",
            source.version.as_deref().unwrap_or_default()
        ),
        ServerSourceKind::Local => format!("server: update {id} from its folder"),
    };
    let mut doc = store.server(id)?.ok_or_else(|| {
        CoreError::new(ErrorCode::NotFound, format!("server {id:?} does not exist"))
    })?;
    *doc.value_mut() = server;
    let text = doc.to_text()?;
    let operation = Operation::new("server.update", summary).entity(format!("server/{id}"));
    let clone = resolved.clone.clone();
    let mut swap: Option<Swap> = None;
    let result = store.transaction(operation, |tx| {
        if source.uses_checkout() {
            let clone = clone.as_deref().ok_or_else(|| {
                CoreError::new(ErrorCode::InvalidValue, "the clone of this source is gone")
            })?;
            swap = Some(place_checkout(
                sx,
                clone,
                id,
                false,
                source.commit.as_deref().unwrap_or_default(),
                source.url.as_deref().unwrap_or_default(),
            )?);
        }
        tx.write(&server_path(id)?, text)?;
        instant_apply(tx, ax, &Touched::Servers(vec![id.to_owned()]))
    });
    if let Some(swap) = swap {
        if result.is_ok() && swap.moved_from.is_some() {
            resolved.clone = None;
        }
        swap.finish(sx.fs, result.is_ok());
    }
    let committed = result?;
    Ok(Updated {
        id: id.to_owned(),
        from: check.current,
        to: check.version.or(check.latest),
        changes: check.changes,
        commit: committed.commit,
        apply: committed.value,
        scan: Some(scan),
    })
}

// ----------------------------------------------------------------- restore

/// A checkout fetched for [`restore_checkout`]: the repository at the
/// commit the server file names, scanned with the stored launch lines.
#[derive(Debug)]
pub struct PreparedCheckout {
    id: String,
    resolved: Resolved,
    scan: ScanReport,
    commit: String,
    url: String,
}

impl PreparedCheckout {
    pub fn id(&self) -> &str {
        &self.id
    }

    pub fn commit(&self) -> &str {
        &self.commit
    }

    /// The repository's files and every launch line of the stored server.
    pub fn scan(&self) -> &ScanReport {
        &self.scan
    }

    pub fn trust_source(&self) -> Option<&SourceRef> {
        self.resolved.trust_source()
    }

    /// Where the host redirected the repository (asked about too).
    pub fn moved_source(&self) -> Option<&SourceRef> {
        self.resolved.moved_source()
    }

    pub fn source_change(&self) -> Option<&SourceChange> {
        self.resolved.source_change()
    }
}

/// Fetches what this machine's checkout of source server `id` should hold
/// (another machine saved or updated it, or it was removed): the
/// repository at the recorded commit, into a temporary clone. `None` when
/// the checkout is already current. A blocked source is not contacted.
pub fn prepare_checkout(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    id: &str,
) -> Result<Option<PreparedCheckout>, CoreError> {
    let (server, source) = stored(store, id)?;
    let source = source.filter(ServerSource::uses_checkout).ok_or_else(|| {
        CoreError::new(
            ErrorCode::InvalidValue,
            format!("server {id:?} does not run from a checkout"),
        )
    })?;
    if checkout_current(sx.fs, &sx.home.path, id, &source) {
        return Ok(None);
    }
    let (Some(url), Some(commit)) = (source.url.clone(), source.commit.clone()) else {
        return Err(CoreError::new(
            ErrorCode::MissingField,
            "the git source has no url or commit",
        ));
    };
    let request = ResolveRequest {
        source: Source::Git {
            url: url.clone(),
            git_ref: None,
            path: None,
        },
        git_ref: Some(commit.clone()),
        path: source.path.clone(),
        catalog: source.catalog.clone(),
        mcp_servers: catalog_servers(store, sx, source.catalog.as_deref()),
    };
    let resolved = resolve(Some(store), sx, &request)?;
    let scanner = Scanner::new(sx.fs, sx.home);
    let mut scan = resolved.files_scan.clone();
    scan.merge(scan_commands(&scanner, &server));
    Ok(Some(PreparedCheckout {
        id: id.to_owned(),
        resolved,
        scan,
        commit,
        url,
    }))
}

/// Puts a prepared checkout in place under the store lock, after the same
/// gates as a save: trust in the source (and a redirect target), then the
/// scan of its files and the stored launch lines (`allow_dangerous`). A
/// stale checkout is replaced atomically; the server's entries are applied
/// again.
pub fn restore_checkout(
    store: &Store<'_>,
    sx: &SkillsEnv<'_>,
    ax: &ApplyEnv<'_>,
    mut prepared: PreparedCheckout,
    decisions: &Decisions,
) -> Result<Option<ApplyReport>, CoreError> {
    prepared.resolved.admit(store, decisions, &[])?;
    scan::gate(&prepared.scan, decisions.allow_dangerous)?;
    let clone = prepared.resolved.clone.clone().ok_or_else(|| {
        CoreError::new(ErrorCode::InvalidValue, "the clone of this source is gone")
    })?;
    let id = prepared.id.clone();
    let operation = Operation::new(
        "server.checkout",
        format!(
            "server: check out {id} at {}",
            &prepared.commit[..7.min(prepared.commit.len())]
        ),
    )
    .entity(format!("server/{id}"));
    let mut swap: Option<Swap> = None;
    let result = store.transaction(operation, |tx| {
        swap = Some(place_checkout(
            sx,
            &clone,
            &id,
            false,
            &prepared.commit,
            &prepared.url,
        )?);
        instant_apply(tx, ax, &Touched::Servers(vec![id.clone()]))
    });
    if let Some(swap) = swap {
        if result.is_ok() && swap.moved_from.is_some() {
            prepared.resolved.clone = None;
        }
        swap.finish(sx.fs, result.is_ok());
    }
    Ok(result?.value)
}

/// Removes the machine-local checkout of `id`, if any.
pub fn remove_checkout(sx: &SkillsEnv<'_>, id: &str) -> Result<(), CoreError> {
    ids::check(ids::IdKind::Server, id)?;
    let dir = checkout_dir(sx, id);
    confine(sx.fs, &dir)?;
    remove_dir(sx.fs, &dir)
}