symforge 11.0.10

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
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
//! Explicit npm-managed self-update command.
//!
//! Beyond shelling `npm install -g symforge@latest`, this orchestrates a complete
//! update so the user is never left with a half-updated mix of versions:
//!  1. stops the running daemon before the swap (a live daemon holds the old
//!     binary — a Windows file-lock — and keeps serving stale behavior) and clears
//!     a demonstrably-dead sidecar record;
//!  2. forces the OS-native platform package (`symforge-<os>-<arch>`) to the same
//!     version, because `npm install -g symforge@latest` alone can retain a stale
//!     nested platform package and leave `symforge --version` behind the wrapper;
//!  3. VERIFIES the resolved `symforge --version` reached the latest published
//!     version — and FAILS LOUDLY (stale nested package, a PATH-shadowing install,
//!     or a WSL Windows-prefix bleed) instead of a hollow success, even when the
//!     npm registry is unreachable (it floors against the running binary's version
//!     and surfaces a launcher that ran but could not resolve a binary);
//!  4. re-registers every MCP client onto the freshly-installed binary; and
//!  5. only AFTER a confirmed re-registration, clears the retired `~/.symforge/bin`
//!     durable-install leftovers and prunes dead version-registry entries.

use anyhow::{Context, bail};
use std::process::Stdio;
use std::time::{Duration, Instant};

use crate::domain::ControlStateDir;

/// Hard ceiling on the npm swap so a locked-file retry can NEVER hang the
/// terminal (the original Windows failure). Layer 2 (staging the running binary
/// aside) normally frees npm's target path so the install finishes in seconds;
/// this is the safety floor for when it does not. A plain const, not config: it
/// only needs to be "longer than a healthy install, shorter than human patience".
const NPM_INSTALL_TIMEOUT: Duration = Duration::from_secs(180);
/// Poll cadence while waiting on the npm child.
const NPM_INSTALL_POLL: Duration = Duration::from_millis(200);

/// Map `(os, arch)` to the npm platform package that ships the native binary.
/// Mirrors `SUPPORTED_TARGETS` in `npm/lib/resolve-binary.js`. `os` is
/// `std::env::consts::OS`, `arch` is `std::env::consts::ARCH`.
fn platform_package_for(os: &str, arch: &str) -> Option<&'static str> {
    match (os, arch) {
        ("windows", "x86_64") => Some("symforge-windows-x64"),
        ("linux", "x86_64") => Some("symforge-linux-x64"),
        ("macos", "aarch64") => Some("symforge-macos-arm64"),
        ("macos", "x86_64") => Some("symforge-macos-x64"),
        _ => None,
    }
}

fn npm_executable_for_os(os: &str) -> &'static str {
    if os == "windows" { "npm.cmd" } else { "npm" }
}

/// The resolved `symforge` launcher name for spawning the freshly-installed
/// binary (`.cmd` shim on Windows, bare name elsewhere).
fn symforge_launcher() -> &'static str {
    if std::env::consts::OS == "windows" {
        "symforge.cmd"
    } else {
        "symforge"
    }
}

/// Build the `npm install -g` package specs. Always installs the `symforge`
/// wrapper at `@latest`; when the OS/arch is known, also names the platform
/// package explicitly so npm materializes the new nested binary instead of
/// silently reusing a stale one.
fn install_specs(os: &str, arch: &str) -> Vec<String> {
    let mut specs = vec!["symforge@latest".to_string()];
    if let Some(pkg) = platform_package_for(os, arch) {
        specs.push(format!("{pkg}@latest"));
    }
    specs
}

/// Parse a `symforge --version` semver out of arbitrary launcher output. Scans
/// EVERY line (not just the first) so a leading banner/notice on stdout does not
/// hide the version, and accepts the first digit-leading dotted token.
fn parse_symforge_version(text: &str) -> Option<String> {
    text.lines().find_map(|line| {
        line.split_whitespace()
            .map(str::trim)
            .find(|tok| tok.contains('.') && tok.chars().next().is_some_and(|c| c.is_ascii_digit()))
            .map(str::to_string)
    })
}

/// Outcome of probing the freshly-installed `symforge --version`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum InstalledProbe {
    /// The launcher ran and reported this version.
    Version(String),
    /// The launcher RAN but exited non-zero / printed no version — e.g. it could
    /// not resolve a native binary (a stale/missing platform package or the WSL
    /// Windows-prefix trap). Carries a trimmed diagnostic line from stderr.
    LauncherFailed(String),
    /// The launcher could not be executed at all (not on PATH / spawn error).
    Unprobeable,
}

/// Clear a demonstrably-dead sidecar record for the current project (CWD
/// `.symforge`). The sidecar is NOT killed: its pid is the in-process MCP server
/// (killing it would drop the user's editor connection), and a TCP-alive probe
/// does not prove the recorded pid owns the port (recycled-pid hazard). Only a
/// `Dead` record is cleaned so the next launch starts clean.
fn clear_dead_sidecar_record() -> Option<String> {
    use crate::sidecar::port_file::{
        SidecarLiveness, cleanup_files, cleanup_stale_descriptors, read_sidecar_status,
    };

    let control_state_dir: ControlStateDir = crate::version_registry::resolve_home()?;
    let project_root = std::env::current_dir().ok();
    let status = read_sidecar_status(&control_state_dir, "127.0.0.1", project_root.as_deref());
    // Task 8: purge stale per-adapter descriptors alongside the legacy files.
    cleanup_stale_descriptors(&control_state_dir, "127.0.0.1");
    if matches!(status.liveness, SidecarLiveness::Dead) {
        cleanup_files(&control_state_dir);
        Some("cleared a stale sidecar record".to_string())
    } else {
        None
    }
}

/// Resolve the durable-install `bin` directory the same way the rest of SymForge
/// resolves its home: `$SYMFORGE_HOME/bin` when `SYMFORGE_HOME` is set (it is set
/// in the standard MCP server config and routinely points at the SAME default
/// `~/.symforge`), else `~/.symforge/bin`. Returns `None` only when neither is
/// resolvable.
/// Remove the retired durable-install artifacts under the resolved durable `bin`
/// directory (`$SYMFORGE_HOME/bin` when set, else `~/.symforge/bin`) — the only
/// place the retired durable mechanism ever wrote. The real safety invariant is
/// the self-exe guard: it never deletes the binary backing the current process.
/// Best-effort; callers must only invoke this AFTER clients are re-registered off
/// the orphan.
fn remove_orphan_durable_bin() -> Vec<String> {
    let Some(control_state_dir) = crate::version_registry::resolve_home() else {
        return Vec::new();
    };
    remove_orphan_durable_bin_at(&control_state_dir)
}

fn remove_orphan_durable_bin_at(control_state_dir: &crate::domain::ControlStateDir) -> Vec<String> {
    let bin = control_state_dir.as_path().join("bin");
    let self_exe = std::env::current_exe()
        .ok()
        .and_then(|p| std::fs::canonicalize(p).ok());

    let mut removed = Vec::new();
    for name in [
        "symforge.exe",
        "symforge",
        "symforge.version",
        "symforge-desktop.cmd",
    ] {
        let path = bin.join(name);
        if !path.exists() {
            continue;
        }
        // Never delete the binary backing the running update process.
        if let Some(self_exe) = &self_exe
            && std::fs::canonicalize(&path).ok().as_ref() == Some(self_exe)
        {
            continue;
        }
        if std::fs::remove_file(&path).is_ok() {
            removed.push(name.to_string());
        }
    }
    if removed.is_empty() {
        Vec::new()
    } else {
        vec![format!(
            "removed retired durable-install leftover(s) from {}: {}",
            bin.display(),
            removed.join(", ")
        )]
    }
}

/// Side effects of an update, injected so the orchestration is unit-testable
/// without touching npm, the network, the daemon, or the filesystem.
pub(crate) trait UpdateOps {
    /// Sweep leftover `.old-*` staged binaries from a PRIOR Windows update (which
    /// moves the running binary aside before the swap). A still-locked leftover
    /// from a live old process is skipped and cleaned on a later run. Runs at the
    /// START of update, best-effort. No-op on Unix. Returns summary lines.
    fn sweep_stale_staging(&mut self) -> Vec<String>;
    /// Stop the running daemon before the binary swap + clear a dead sidecar
    /// record. Returns a human-readable summary of what was stopped.
    fn stop_processes(&mut self) -> String;
    /// Run `<program> <args...>`; return `true` on success.
    fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool>;
    /// Probe the resolved `symforge --version` after install.
    fn installed_version(&mut self) -> InstalledProbe;
    /// Latest version published to the npm registry, or `None` when offline.
    fn latest_version(&mut self) -> Option<String>;
    /// Prune dead version-registry entries (paths whose binary was deleted while
    /// the drive is online). Runs UNCONDITIONALLY and early — even when the npm
    /// swap is blocked (Windows `EBUSY`) — so a blocked update still cleans cruft.
    /// Returns summary lines (empty when nothing was pruned).
    fn prune_registry(&mut self) -> Vec<String>;
    /// Re-register every MCP client onto the freshly-installed binary by spawning
    /// the NEW launcher's `init`. Returns `true` on success.
    fn reregister_clients(&mut self) -> anyhow::Result<bool>;
    /// Remove the retired durable-install leftovers ONLY when `reregistered` is
    /// true (otherwise clients still point at the orphan and deleting it would
    /// break them). Registry pruning is handled separately by [`UpdateOps::prune_registry`].
    /// Returns summary lines.
    fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String>;
    /// Detect whether a DIFFERENT install shadows the binary npm just installed
    /// on `$PATH`. Derives "our binary" from the global npm prefix and compares
    /// it to the PATH-first `symforge`. Returns `None` when our install wins, the
    /// prefix is unresolvable, or no shadow exists. This is ADDITIVE to the
    /// reactive stale-version bail: it also fires when the shadow is the SAME
    /// version (which the stale-version check cannot see).
    fn shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport>;
}

struct RealUpdateOps;

impl UpdateOps for RealUpdateOps {
    fn sweep_stale_staging(&mut self) -> Vec<String> {
        run_stale_sweep()
    }

    fn stop_processes(&mut self) -> String {
        let mut stopped = Vec::new();

        // Daemon (global). `main()` is synchronous, so a short-lived runtime is
        // safe (no nested-runtime panic).
        let daemon = tokio::runtime::Builder::new_current_thread()
            .enable_io()
            .enable_time()
            .build()
            .ok()
            .and_then(|rt| {
                rt.block_on(crate::daemon::stop_running_daemon_for_update())
                    .ok()
            });
        match daemon {
            Some(crate::daemon::DaemonStopOutcome::Stopped { pid }) => {
                stopped.push(format!("daemon (pid {pid})"));
            }
            Some(crate::daemon::DaemonStopOutcome::StopTimedOut { pid }) => {
                stopped.push(format!(
                    "daemon (pid {pid}) did NOT stop in time — left discoverable; rerun update or stop it manually"
                ));
            }
            Some(crate::daemon::DaemonStopOutcome::SkippedSafety) => {
                stopped.push("daemon left running (failed ownership safety check)".to_string());
            }
            _ => {}
        }

        if let Some(sidecar) = clear_dead_sidecar_record() {
            stopped.push(sidecar);
        }

        // Stop every OTHER symforge process running from the SAME executable path
        // as this one — the binary npm is about to overwrite. On Windows a live
        // holder keeps an exclusive image handle and blocks the swap (EBUSY), so
        // clearing the holders BEFORE npm runs is what lets the swap proceed. The
        // set is scoped by ExecutablePath (never by image name) and excludes THIS
        // process, so unrelated installs at other paths are never touched
        // (SELF_UPDATE_PROCEDURE.md, Invariant 1).
        for line in stop_other_inscope_holders() {
            stopped.push(line);
        }

        if stopped.is_empty() {
            "no running daemon found".to_string()
        } else {
            format!("stopped {}", stopped.join(", "))
        }
    }

    fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool> {
        // Layer 2 (Windows): a running `.exe` cannot be OVERWRITTEN but CAN be
        // moved aside — a rename needs only DELETE access (the rustup
        // `self_replace` technique). Move THIS process's own binary out of npm's
        // target path so npm installs a fresh binary into a now-FREE path; the
        // running process keeps executing from the moved file (its image handle
        // follows the file object). No-op on Unix, which overwrites in place.
        //
        // The returned RAII guard rolls the binary back on drop UNLESS a binary
        // landed at the path. The pivot is "did a binary land?", never "did npm
        // return 0?" — so the spawn error and the `wait_or_kill` error below (both
        // early `?` returns), a timeout, an npm-exit-0 that did NOT re-extract the
        // binary (an already-current re-install), and a panic ALL leave the
        // install path populated rather than empty.
        let _restore = stage_running_binary_aside();

        // Layer 1: bounded wait. The blocking `.status()` this replaces spun
        // forever when npm retried the locked file; spawn + poll `try_wait`
        // against a deadline and kill the child on timeout, returning Ok(false)
        // so the EXISTING graceful bail fires instead of hanging.
        let mut child = crate::process_util::hidden_command(program)
            .args(args)
            .stdin(Stdio::inherit())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .spawn()
            .with_context(|| format!("failed to start `{}`", invocation_text(program, args)))?;
        wait_or_kill(
            &mut child,
            Instant::now() + NPM_INSTALL_TIMEOUT,
            NPM_INSTALL_POLL,
        )
        // `_restore` drops here (and on either early `?` return above), restoring
        // the staged binary iff the install path was not repopulated.
    }

    fn installed_version(&mut self) -> InstalledProbe {
        // Spawn the freshly-resolved launcher (this update process is still the
        // OLD binary, so we ask the launcher what it now resolves to). Inspect
        // BOTH stdout and the exit status: the npm launcher prints resolve errors
        // to stderr and exits non-zero with empty stdout, which must surface as a
        // loud failure, not a silent "could not probe".
        let output = match crate::process_util::hidden_command(symforge_launcher())
            .arg("--version")
            .output()
        {
            Ok(output) => output,
            Err(_) => return InstalledProbe::Unprobeable,
        };
        if let Some(version) = parse_symforge_version(&String::from_utf8_lossy(&output.stdout)) {
            return InstalledProbe::Version(version);
        }
        // Ran but produced no version: surface the launcher's own diagnostic.
        let stderr = String::from_utf8_lossy(&output.stderr);
        let detail = stderr
            .lines()
            .map(str::trim)
            .find(|line| !line.is_empty())
            .unwrap_or("launcher produced no version output")
            .to_string();
        InstalledProbe::LauncherFailed(detail)
    }

    fn latest_version(&mut self) -> Option<String> {
        crate::cli::version::latest_npm_version()
    }

    fn prune_registry(&mut self) -> Vec<String> {
        let Some(home) = crate::version_registry::resolve_home() else {
            return Vec::new();
        };
        let pruned = crate::version_registry::prune_missing_entries(&home);
        if pruned > 0 {
            vec![format!(
                "pruned {pruned} stale version-registry entr{}",
                if pruned == 1 { "y" } else { "ies" }
            )]
        } else {
            Vec::new()
        }
    }

    fn reregister_clients(&mut self) -> anyhow::Result<bool> {
        // Spawn the NEW launcher's init so clients are registered at the freshly
        // installed binary (this update process is still the OLD binary, so an
        // in-process `run_init` would re-register the OLD path).
        let status = crate::process_util::hidden_command(symforge_launcher())
            .args(["init", "--client", "all"])
            .stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status();
        Ok(matches!(status, Ok(s) if s.success()))
    }

    fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String> {
        if reregistered {
            remove_orphan_durable_bin()
        } else {
            Vec::new()
        }
    }

    fn shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport> {
        let installed = npm_installed_launcher_path()?;
        crate::path_shadow::detect_shadow(&installed)
    }
}

/// A child process we can poll for completion and force-kill. The seam exists so
/// [`wait_or_kill`]'s timeout logic is unit-testable with a fake that never
/// exits, without spawning a real slow process.
trait Waitable {
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>>;
    fn kill(&mut self) -> std::io::Result<()>;
}

impl Waitable for std::process::Child {
    fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
        std::process::Child::try_wait(self)
    }
    fn kill(&mut self) -> std::io::Result<()> {
        std::process::Child::kill(self)
    }
}

/// Poll `child` until it exits or `deadline` passes. On exit, return whether it
/// succeeded; on timeout, kill it and return `Ok(false)` so the caller takes the
/// existing graceful-bail path. The npm swap must NEVER block indefinitely — a
/// locked-file retry loop was the original Windows hang.
fn wait_or_kill<C: Waitable>(
    child: &mut C,
    deadline: Instant,
    poll: Duration,
) -> anyhow::Result<bool> {
    loop {
        if let Some(status) = child.try_wait()? {
            return Ok(status.success());
        }
        if Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.try_wait(); // best-effort reap
            return Ok(false);
        }
        std::thread::sleep(poll);
    }
}

/// The dedicated stale-staging directory for moved-aside binaries:
/// `<npm-global-prefix>/.symforge-update-stale`, a sibling of the GLOBAL
/// `node_modules`. Derived from the npm global prefix (`npm prefix -g`), NEVER by
/// walking `current_exe()`'s `node_modules` ancestors: a nested layout
/// (`.../node_modules/symforge/node_modules/symforge-windows-x64/bin/...`) would
/// resolve INSIDE the wrapper package npm rimrafs, and a divergent prefix (WSL
/// bleed) would free the wrong tree. It sits outside every package dir (npm may
/// rimraf `node_modules/*` on reinstall, so a still-locked `.old` must not live
/// inside it) and, in the normal install, on the same volume as the binary (so
/// the move is a rename, not a cross-volume copy).
#[cfg(any(windows, test))]
fn stale_staging_dir(npm_prefix: &std::path::Path) -> std::path::PathBuf {
    npm_prefix.join(".symforge-update-stale")
}

/// Best-effort delete of every staged leftover in `dir` (a prior update's
/// moved-aside binaries). Uses `remove_file` only: a file still locked by a live
/// old process errors and is silently skipped (cleaned on a later run once that
/// process exits), and a stray subdirectory is left alone. A nonexistent `dir`
/// is a no-op. Returns a summary line when anything was removed.
#[cfg(any(windows, test))]
fn sweep_stale_dir(dir: &std::path::Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut removed = 0usize;
    for entry in entries.flatten() {
        if std::fs::remove_file(entry.path()).is_ok() {
            removed += 1;
        }
    }
    if removed > 0 {
        vec![format!(
            "swept {removed} stale staged binar{} from {}",
            if removed == 1 { "y" } else { "ies" },
            dir.display()
        )]
    } else {
        Vec::new()
    }
}

/// RAII rollback for the moved-aside binary. On drop, if the install path was
/// NOT repopulated by npm, move the staged binary back so a failed OR no-op
/// update never leaves the path empty. The pivot is "did a binary land at the
/// path?", NEVER "did npm return 0?": an already-current re-install exits 0
/// without re-extracting the binary, and a failed spawn, a `try_wait` error, a
/// timeout, and a panic all bypass any exit-code check entirely. When a binary
/// DID land, the guard disarms and the staged `.old` is left for the next sweep.
///
/// Cross-platform so the signature and the guard tests are uniform, but only ever
/// CONSTRUCTED on Windows (staging is a Windows-only concern) — hence the
/// non-Windows `dead_code` allow: it is genuinely never built there.
#[cfg_attr(not(windows), allow(dead_code))]
struct StagedRestore {
    staged: std::path::PathBuf,
    original: std::path::PathBuf,
}

impl Drop for StagedRestore {
    fn drop(&mut self) {
        if !self.original.exists() {
            let _ = move_path_aside(&self.staged, &self.original);
        }
    }
}

/// Windows: move THIS process's running binary out of npm's target path to the
/// stale-staging dir under the npm GLOBAL prefix, so npm installs a fresh binary
/// into a now-free path. The running process keeps executing from the moved file.
/// Returns a [`StagedRestore`] guard that rolls the move back on drop unless a
/// binary landed. `None` (staging skipped — the timeout floor still prevents a
/// hang) when the current exe or the npm prefix cannot be resolved, or the move
/// fails (e.g. a divergent prefix that would make it a cross-volume move).
#[cfg(windows)]
fn stage_running_binary_aside() -> Option<StagedRestore> {
    let exe = std::env::current_exe().ok()?;
    let stale_dir = stale_staging_dir(&npm_global_prefix()?);
    std::fs::create_dir_all(&stale_dir).ok()?;
    let staged = stale_dir.join(format!("symforge.exe.old-{}", stage_suffix()));
    move_path_aside(&exe, &staged).ok()?;
    Some(StagedRestore {
        staged,
        original: exe,
    })
}

/// Unix replaces a running binary in place (the open image keeps the old inode
/// while the path takes the new file — same reason `stop_other_inscope_holders`
/// is a no-op), so there is no locked path to free. Always `None`.
#[cfg(not(windows))]
fn stage_running_binary_aside() -> Option<StagedRestore> {
    None
}

/// Sweep leftover staged binaries from a PRIOR update, from the npm global
/// prefix's stale dir (same derivation as staging). Runs at the start of update,
/// best-effort; `None` prefix → nothing to sweep.
#[cfg(windows)]
fn run_stale_sweep() -> Vec<String> {
    match npm_global_prefix() {
        Some(prefix) => sweep_stale_dir(&stale_staging_dir(&prefix)),
        None => Vec::new(),
    }
}

/// Unix never stages, so there is nothing to sweep.
#[cfg(not(windows))]
fn run_stale_sweep() -> Vec<String> {
    Vec::new()
}

/// A random-enough suffix for a staged `.old-*` filename: pid + wall-clock nanos
/// (no `rand` dependency needed — collisions only need avoiding across a rare
/// concurrent or repeated update, and the sweep tolerates leftovers anyway).
#[cfg(windows)]
fn stage_suffix() -> String {
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    format!("{}-{nanos}", std::process::id())
}

/// Move `src` to `dst`, freeing `src` for npm. `std::fs::rename` (which maps to
/// `MoveFileExW`) handles the common case; fall back to an explicit
/// `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` on error. A running `.exe` can be
/// renamed aside (DELETE access) even though it cannot be overwritten.
#[cfg(windows)]
fn move_path_aside(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    match std::fs::rename(src, dst) {
        Ok(()) => Ok(()),
        Err(_) => windows_native::move_file_replace_existing(src, dst),
    }
}

/// Unix never stages a running binary; this exists only because
/// [`StagedRestore`]'s drop references it on every platform (the guard is never
/// constructed on Unix, so it is never actually called).
#[cfg(not(windows))]
fn move_path_aside(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
    std::fs::rename(src, dst)
}

/// Resolve the npm global prefix via `npm prefix -g`. This is the authoritative
/// install root (the parent of the GLOBAL `node_modules`); staging and sweep
/// derive their directory from it, and shadow detection derives the launcher
/// path from it. Returns `None` when `npm` is unavailable or the prefix cannot
/// be parsed.
fn npm_global_prefix() -> Option<std::path::PathBuf> {
    let program = npm_executable_for_os(std::env::consts::OS);
    let output = crate::process_util::hidden_command(program)
        .args(["prefix", "-g"])
        .stdin(Stdio::null())
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let prefix = String::from_utf8_lossy(&output.stdout);
    let prefix = prefix.trim();
    if prefix.is_empty() {
        return None;
    }
    Some(std::path::PathBuf::from(prefix))
}

/// Derive the path of the `symforge` launcher npm installs at the global prefix.
/// On Windows the shim lives at the prefix root (`<prefix>/symforge.cmd`); on
/// Unix it lives in `<prefix>/bin/symforge`. Returns `None` when the prefix
/// cannot be resolved.
fn npm_installed_launcher_path() -> Option<std::path::PathBuf> {
    Some(launcher_path_in_prefix(
        &npm_global_prefix()?,
        std::env::consts::OS,
    ))
}

/// Pure mapping from an npm global prefix to the `symforge` launcher path it
/// installs, given the target OS. Windows places the shim at the prefix root;
/// every other platform uses the conventional `<prefix>/bin/<name>` layout.
fn launcher_path_in_prefix(prefix: &std::path::Path, os: &str) -> std::path::PathBuf {
    if os == "windows" {
        prefix.join("symforge.cmd")
    } else {
        prefix.join("bin").join("symforge")
    }
}

pub fn run_update() -> anyhow::Result<()> {
    orchestrate_update(
        std::env::consts::OS,
        std::env::consts::ARCH,
        &mut RealUpdateOps,
    )
}

pub(crate) fn orchestrate_update(
    os: &str,
    arch: &str,
    ops: &mut impl UpdateOps,
) -> anyhow::Result<()> {
    // Sweep leftover staged binaries from a prior Windows update before anything
    // else (best-effort; a still-locked `.old` from a live old process is skipped
    // and cleaned once that process exits). No-op on Unix.
    for line in ops.sweep_stale_staging() {
        eprintln!("symforge update: {line}");
    }

    // Stop first: a live daemon holds the old binary (Windows file-lock) and
    // would keep serving stale behavior. It respawns lazily on next use.
    let stop_summary = ops.stop_processes();
    eprintln!("symforge update: {stop_summary}.");

    // Prune dead version-registry entries UNCONDITIONALLY and BEFORE the npm swap.
    // The swap can be blocked (Windows `EBUSY`: a running MCP client still holds
    // the `.exe`) and bail below — but registry cruft (e.g. removed git-worktree
    // dev builds) should be cleaned regardless of whether the swap succeeds.
    for line in ops.prune_registry() {
        eprintln!("symforge update: {line}");
    }

    let program = npm_executable_for_os(os);
    let specs = install_specs(os, arch);
    let args: Vec<&str> = ["install", "-g"]
        .into_iter()
        .chain(specs.iter().map(String::as_str))
        .collect();

    if !ops.npm_install(program, &args)? {
        // Any OTHER in-scope holders were already stopped in `stop_processes`
        // (their count, if any were found, was printed above). The message stays
        // honest when enumeration found/stopped nothing: it does NOT assert "all
        // holders were stopped", and the closing hint covers an un-enumerable
        // holder. The remediation runs from a PLAIN shell — not the `symforge`
        // binary that self-locks on Windows.
        let plain_cmd = format!("npm install -g {}", specs.join(" "));
        let init_cmd = format!("{} init --client all", symforge_launcher());
        if os == "windows" {
            bail!(
                "symforge update failed: `{}` exited unsuccessfully.\n\
                 On Windows the `symforge update` process runs from the very binary npm \
                 replaces and cannot overwrite a running .exe. Any OTHER in-scope holders \
                 were stopped above (if any were found), so finish the swap from a PLAIN \
                 shell (NOT via `symforge`):\n  {}\n\
                 then re-point your MCP clients onto the new binary:\n  {}\n\
                 If it STILL fails, an MCP client (Cursor, Claude) or another symforge \
                 process is holding the binary — close them and rerun the command above.\n\
                 (The version registry was already pruned.)",
                invocation_text(program, &args),
                plain_cmd,
                init_cmd
            );
        } else {
            bail!(
                "symforge update failed: `{}` exited unsuccessfully.\n\
                 Ensure no running symforge process is holding the binary, then rerun, or \
                 install directly from a plain shell:\n  {}\n\
                 (The version registry was already pruned.)",
                invocation_text(program, &args),
                plain_cmd
            );
        }
    }

    // Verify the install actually took effect. npm can report success while the
    // resolved binary stays behind, so this is the load-bearing safety net.
    let running = env!("CARGO_PKG_VERSION");
    let pkg = platform_package_for(os, arch).unwrap_or("symforge-<os>-<arch>");
    match ops.installed_version() {
        InstalledProbe::LauncherFailed(detail) => {
            bail!(
                "symforge update incomplete: the freshly-installed `symforge` launcher could not \
                 resolve a native binary. Launcher reported:\n  {detail}\n\
                 This is usually a stale/missing platform package or a WSL Windows-prefix bleed. Try: \
                 npm install -g symforge@latest {pkg}@latest --force; on WSL, ensure your Linux npm \
                 prefix bin is on PATH ahead of /usr/local and /mnt."
            );
        }
        InstalledProbe::Unprobeable => {
            eprintln!(
                "symforge update: WARNING — could not run `symforge --version` to verify the result \
                 (the npm prefix bin may not be on PATH). The install ran; confirm with `symforge --version`."
            );
        }
        InstalledProbe::Version(installed) => {
            let latest = ops.latest_version();
            // When the registry is reachable, require the resolved binary to be
            // at the latest; otherwise floor against the version of the binary
            // running this update — the swap must produce something at least as
            // new, or it demonstrably did not take effect.
            let (stale, target) = match &latest {
                Some(l) => (
                    crate::cli::version::is_newer_version(l, &installed),
                    l.clone(),
                ),
                None => (
                    crate::cli::version::is_newer_version(running, &installed),
                    running.to_string(),
                ),
            };
            if stale {
                bail!(
                    "symforge update incomplete: npm reported success but `symforge --version` still \
                     reports {installed}, behind {target}. The resolved `symforge` is not the one just \
                     installed. Likely causes:\n  \
                     - stale nested platform package — retry: npm install -g symforge@latest {pkg}@latest --force\n  \
                     - a PATH-shadowing install — run `which -a symforge`; a root /usr/local copy can win over your npm prefix\n  \
                     - on WSL, a Windows npm prefix bleeding in via /mnt — put your Linux npm prefix bin ahead of /usr/local and /mnt on PATH\n  \
                     - on Windows, a running symforge can lock its own .exe — run the npm install from a separate shell"
                );
            }
            if latest.is_none() {
                eprintln!(
                    "symforge update: `symforge --version` reports {installed} (could not reach the npm \
                     registry to confirm it is the very latest)."
                );
            } else {
                eprintln!(
                    "symforge update complete — `symforge --version` now reports {installed}."
                );
            }
        }
    }

    // Proactive PATH-shadow check. The version-verification above bails only when
    // the resolved binary is BEHIND the target; it cannot see a same-version
    // shadow (a stale install that happens to match) or name the exact offending
    // path and fix. Compare the binary npm just installed to the PATH-first
    // `symforge` and, when a different install wins, print the precise remediation.
    if let Some(report) = ops.shadow_report() {
        eprintln!("{}", crate::path_shadow::format_shadow_warning(&report));
    }

    // Re-point all clients at the freshly-installed binary. Only AFTER a confirmed
    // re-registration do we clear the retired durable-install artifacts — deleting
    // the orphan while a client still references it would break that client.
    let reregistered = match ops.reregister_clients() {
        Ok(true) => {
            eprintln!("symforge update: re-registered all MCP clients onto the new binary.");
            true
        }
        Ok(false) => {
            eprintln!(
                "symforge update: client re-registration did not complete — run `symforge init \
                 --client all` manually. Leaving the durable-install leftovers in place until then."
            );
            false
        }
        Err(error) => {
            eprintln!(
                "symforge update: client re-registration error ({error}) — run `symforge init \
                 --client all` manually. Leaving the durable-install leftovers in place until then."
            );
            false
        }
    };
    for line in ops.reconcile_durable(reregistered) {
        eprintln!("symforge update: {line}");
    }

    Ok(())
}

fn invocation_text(program: &str, args: &[&str]) -> String {
    let mut parts = Vec::with_capacity(args.len() + 1);
    parts.push(program.to_string());
    parts.extend(args.iter().map(|arg| (*arg).to_string()));
    parts.join(" ")
}

/// Normalize a Windows executable path for identity comparison: strip the
/// extended-length verbatim prefix (`\\?\`), unify slashes, and lowercase. This
/// path is Windows-only (a case-insensitive filesystem), so always lowercasing is
/// correct AND keeps the comparison deterministic under cross-platform test
/// builds. Mirrors the slash+lowercase normalization `daemon::stable_path_identity`
/// applies, plus a verbatim-prefix strip so a `\\?\C:\..` `current_exe()` lines up
/// with WMI's plain `C:\..` `ExecutablePath`.
#[cfg(any(windows, test))]
fn normalize_exe_path(path: &str) -> String {
    let trimmed = path.trim();
    let stripped = trimmed.strip_prefix(r"\\?\").unwrap_or(trimmed);
    stripped.replace('\\', "/").to_ascii_lowercase()
}

/// Pure selection of the in-scope holder PIDs to stop before the npm swap. Given
/// a snapshot of running symforge processes as `(pid, executable_path)`, returns
/// the PIDs whose executable path identifies the SAME binary as `self_exe` (the
/// binary npm will overwrite) EXCLUDING `self_pid` (this process). Paths are
/// compared after [`normalize_exe_path`] (verbatim-strip + slash-unify +
/// lowercase) so a divergent path FORM (extended-length prefix, slash style,
/// casing) cannot silently skip a genuine holder. Scoping by executable PATH —
/// never by image name — is Invariant 1 of `SELF_UPDATE_PROCEDURE.md`: an
/// unrelated symforge install at a different path is never stopped.
#[cfg(any(windows, test))]
fn select_inscope_holder_pids(
    processes: &[(u32, String)],
    self_exe: &str,
    self_pid: u32,
) -> Vec<u32> {
    let target = normalize_exe_path(self_exe);
    processes
        .iter()
        .filter(|(pid, path)| *pid != self_pid && normalize_exe_path(path) == target)
        .map(|(pid, _)| *pid)
        .collect()
}

/// Stop every OTHER symforge process running from this process's own executable
/// path (the binary npm will overwrite), identity-gated native terminate, so
/// the Windows image lock is released before the npm swap. Excludes this
/// process. Returns a summary line when any holder was stopped.
#[cfg(windows)]
fn stop_other_inscope_holders() -> Vec<String> {
    let Ok(self_exe) = std::env::current_exe() else {
        return Vec::new();
    };
    let self_exe = self_exe.to_string_lossy().to_string();
    let self_pid = std::process::id();

    let snapshot = enumerate_symforge_processes();
    let pids = select_inscope_holder_pids(&snapshot, &self_exe, self_pid);
    if pids.is_empty() {
        return Vec::new();
    }
    for pid in &pids {
        terminate_inscope_holder(*pid, &self_exe);
    }
    vec![format!(
        "{} other in-scope symforge holder(s) (pid {})",
        pids.len(),
        pids.iter()
            .map(u32::to_string)
            .collect::<Vec<_>>()
            .join(", ")
    )]
}

/// Unix can replace a running binary's file (the open binary keeps the old inode
/// while the path takes the new file), so there is no EBUSY holder lock to clear
/// before the swap — the daemon stop in `stop_processes` is sufficient.
#[cfg(not(windows))]
fn stop_other_inscope_holders() -> Vec<String> {
    Vec::new()
}

/// Enumerate every running `symforge.exe` as `(pid, full_image_path)` natively
/// via a ToolHelp snapshot + `QueryFullProcessImageNameW` — spawning NO external
/// process (pattern ported from Terminal Commander's supervisor). The full image
/// path is required to scope by install path per Invariant 1. Returns an empty
/// list when the snapshot cannot be taken — a safe no-op that degrades to the
/// staged-guidance bail rather than killing anything on uncertainty.
#[cfg(windows)]
fn enumerate_symforge_processes() -> Vec<(u32, String)> {
    windows_native::enumerate_by_image_name("symforge.exe")
}

/// Identity-gated forced terminate of one in-scope holder. Re-verifies via the
/// OS — immediately before the kill — that `pid`'s image path is THIS install's
/// binary, then terminates natively.
///
/// There is deliberately NO graceful leg on Windows: `taskkill` without `/F`
/// is REFUSED by console processes ("can only be terminated forcefully"),
/// which is what the daemon/sidecar/MCP server are — the old graceful-then-
/// forced dance either mistook that refusal for "nothing to stop" (leaving
/// holders alive and the npm swap blocked) or added a wait that protected
/// nothing. The graceful path is the IPC daemon stop in `stop_processes`;
/// whatever still holds the binary after it is terminated here.
///
/// A pid that cannot be queried or whose image path no longer matches is left
/// alone (recycled-pid defense: never kill on uncertainty).
#[cfg(windows)]
fn terminate_inscope_holder(pid: u32, expected_exe: &str) {
    let expected = normalize_exe_path(expected_exe);
    let still_ours = windows_native::pid_image_full_path(pid)
        .is_some_and(|path| normalize_exe_path(&path) == expected);
    if still_ours {
        let _ = windows_native::terminate_process(pid);
    }
}

/// Native Win32 process control for the update swap, ported from Terminal
/// Commander's supervisor: ToolHelp enumeration, image-path identity, and
/// `TerminateProcess`. Spawns NO external process — no powershell/CIM, no
/// taskkill, no tasklist (corporate EDR flags spawned kill tools, and the
/// tools themselves were the source of the refused-graceful bug).
///
/// `unsafe` here is FFI-only, each call justified by a SAFETY comment; the
/// crate-level `unsafe_code = "deny"` is opted out per-item, matching the
/// repo's test-env precedent.
#[cfg(windows)]
mod windows_native {
    use windows::Win32::Foundation::{CloseHandle, HANDLE};
    use windows::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW,
        TH32CS_SNAPPROCESS,
    };
    use windows::Win32::System::Threading::{
        OpenProcess, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION, PROCESS_TERMINATE,
        QueryFullProcessImageNameW, TerminateProcess,
    };

    /// RAII guard so a process/snapshot handle is closed on every return path.
    /// `CloseHandle` failure on drop is ignored: the handle is being discarded
    /// regardless.
    struct OwnedHandle(HANDLE);

    impl Drop for OwnedHandle {
        fn drop(&mut self) {
            // SAFETY: `self.0` is a handle we opened (OpenProcess /
            // CreateToolhelp32Snapshot) and have not closed yet. Closing it
            // exactly once here is the paired release for that open.
            #[allow(unsafe_code)]
            unsafe {
                let _ = CloseHandle(self.0);
            }
        }
    }

    /// Read `pid`'s FULL image path via the OS, or `None` if the process
    /// cannot be opened/queried (it exited, the pid is invalid, or access was
    /// denied). Callers treat `None` as "not ours" — never kill on uncertainty.
    #[allow(unsafe_code)]
    pub(super) fn pid_image_full_path(pid: u32) -> Option<String> {
        // SAFETY: OpenProcess takes a desired-access mask, an inherit BOOL,
        // and a pid; it returns a valid handle on success or an Err we map to
        // None. PROCESS_QUERY_LIMITED_INFORMATION is the least privilege that
        // permits QueryFullProcessImageNameW.
        let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()? };
        let proc = OwnedHandle(handle);

        let mut buf = [0u16; 1024];
        let mut len = u32::try_from(buf.len()).expect("image-path buffer length fits in u32");
        // SAFETY: `proc.0` is a live handle (just opened) valid for this call.
        // PROCESS_NAME_FORMAT(0) requests the win32 path form. `buf`/`len`
        // describe a properly sized, owned u16 buffer; the call writes at most
        // `len` code units and updates `len` to the count written. We check
        // the BOOL result and a non-zero length before reading the buffer.
        let ok = unsafe {
            QueryFullProcessImageNameW(
                proc.0,
                PROCESS_NAME_FORMAT(0),
                windows::core::PWSTR(buf.as_mut_ptr()),
                &raw mut len,
            )
            .is_ok()
        };
        if !ok || len == 0 {
            return None;
        }
        Some(String::from_utf16_lossy(&buf[..len as usize]))
    }

    /// Force-terminate `pid` natively. Caller has already identity-gated the
    /// pid. Returns an IO error if the process cannot be opened for
    /// termination or the terminate call fails.
    #[allow(unsafe_code)]
    pub(super) fn terminate_process(pid: u32) -> std::io::Result<()> {
        let access = PROCESS_TERMINATE | PROCESS_QUERY_LIMITED_INFORMATION;
        // SAFETY: OpenProcess as above; PROCESS_TERMINATE is the access right
        // TerminateProcess requires. The Err arm maps the Win32 error into an
        // io::Error without dereferencing anything.
        let handle = unsafe { OpenProcess(access, false, pid) }
            .map_err(|e| std::io::Error::other(e.to_string()))?;
        let proc = OwnedHandle(handle);
        // SAFETY: `proc.0` is a live handle opened with PROCESS_TERMINATE.
        // TerminateProcess posts the exit and returns a BOOL we propagate as
        // an io::Error on failure. Exit code 1 mirrors the prior `taskkill /F`.
        unsafe { TerminateProcess(proc.0, 1) }.map_err(|e| std::io::Error::other(e.to_string()))?;
        Ok(())
    }

    /// Enumerate all processes whose image FILE NAME matches `image_name`
    /// (case-insensitive) as `(pid, full_image_path)`. The full path comes
    /// from the authoritative per-pid query, not the snapshot's base name, so
    /// callers can scope by install path. Self-exclusion is the caller's job
    /// (`select_inscope_holder_pids` excludes `self_pid`).
    #[allow(unsafe_code)]
    pub(super) fn enumerate_by_image_name(image_name: &str) -> Vec<(u32, String)> {
        // SAFETY: CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) returns a
        // valid snapshot handle or an Err we map to an empty list. The handle
        // is owned by `OwnedHandle` and released on every return path.
        let Ok(snapshot_handle) = (unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) })
        else {
            return Vec::new();
        };
        let snapshot = OwnedHandle(snapshot_handle);

        let mut entry = PROCESSENTRY32W {
            dwSize: u32::try_from(std::mem::size_of::<PROCESSENTRY32W>())
                .expect("PROCESSENTRY32W size fits in u32"),
            ..Default::default()
        };

        let mut found = Vec::new();
        // SAFETY: `snapshot.0` is a valid snapshot handle and `entry` is a
        // properly initialized PROCESSENTRY32W with `dwSize` set, as the API
        // requires. Process32FirstW fills `entry` and returns Ok/Err.
        let mut has_entry = unsafe { Process32FirstW(snapshot.0, &raw mut entry).is_ok() };
        while has_entry {
            let pid = entry.th32ProcessID;
            if exe_name_from_entry(&entry).eq_ignore_ascii_case(image_name)
                && let Some(path) = pid_image_full_path(pid)
            {
                found.push((pid, path));
            }
            // SAFETY: same invariants as Process32FirstW; advances `entry` to
            // the next process or returns Err at the end of the snapshot.
            has_entry = unsafe { Process32NextW(snapshot.0, &raw mut entry).is_ok() };
        }
        found
    }

    /// Decode the NUL-terminated UTF-16 `szExeFile` base name from a snapshot
    /// entry into a Rust string.
    fn exe_name_from_entry(entry: &PROCESSENTRY32W) -> String {
        let end = entry
            .szExeFile
            .iter()
            .position(|c| *c == 0)
            .unwrap_or(entry.szExeFile.len());
        String::from_utf16_lossy(&entry.szExeFile[..end])
    }

    /// Build a NUL-terminated UTF-16 buffer for a Win32 wide-string path arg.
    fn to_wide(path: &std::path::Path) -> Vec<u16> {
        use std::os::windows::ffi::OsStrExt;
        path.as_os_str()
            .encode_wide()
            .chain(std::iter::once(0))
            .collect()
    }

    /// Move `src` to `dst` via `MoveFileExW(MOVEFILE_REPLACE_EXISTING)` — the
    /// fallback when `std::fs::rename` fails. Renaming a running `.exe` aside
    /// needs only DELETE access, so it succeeds where an overwrite-in-place is
    /// refused. Same-volume only (no `COPY_ALLOWED`): a locked image can be
    /// renamed within its volume but never block-copied across one.
    #[allow(unsafe_code)]
    pub(super) fn move_file_replace_existing(
        src: &std::path::Path,
        dst: &std::path::Path,
    ) -> std::io::Result<()> {
        use windows::Win32::Storage::FileSystem::{MOVEFILE_REPLACE_EXISTING, MoveFileExW};
        let src_w = to_wide(src);
        let dst_w = to_wide(dst);
        // SAFETY: `src_w`/`dst_w` are NUL-terminated UTF-16 buffers that outlive
        // this call; the PCWSTR wrappers only borrow their pointers for the
        // duration of MoveFileExW. MOVEFILE_REPLACE_EXISTING is a valid flag; the
        // call returns a Result we map into an io::Error.
        unsafe {
            MoveFileExW(
                windows::core::PCWSTR(src_w.as_ptr()),
                windows::core::PCWSTR(dst_w.as_ptr()),
                MOVEFILE_REPLACE_EXISTING,
            )
        }
        .map_err(|e| std::io::Error::other(e.to_string()))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct FakeOps {
        install_calls: Vec<(String, Vec<String>)>,
        install_result: bool,
        installed: InstalledProbe,
        latest: Option<String>,
        reregister_result: anyhow::Result<bool>,
        prune_lines: Vec<String>,
        stopped_before_install: bool,
        reregistered_after_install: bool,
        reconciled_with: Option<bool>,
        pruned_before_install: Option<bool>,
        prune_calls: usize,
        shadow: Option<crate::path_shadow::ShadowReport>,
        shadow_checked_after_install: Option<bool>,
    }

    impl Default for FakeOps {
        fn default() -> Self {
            Self {
                install_calls: Vec::new(),
                install_result: false,
                installed: InstalledProbe::Unprobeable,
                latest: None,
                reregister_result: Ok(true),
                prune_lines: Vec::new(),
                stopped_before_install: false,
                reregistered_after_install: false,
                reconciled_with: None,
                pruned_before_install: None,
                prune_calls: 0,
                shadow: None,
                shadow_checked_after_install: None,
            }
        }
    }

    impl UpdateOps for FakeOps {
        fn sweep_stale_staging(&mut self) -> Vec<String> {
            Vec::new()
        }
        fn stop_processes(&mut self) -> String {
            self.stopped_before_install = self.install_calls.is_empty();
            "no running daemon found".to_string()
        }
        fn npm_install(&mut self, program: &str, args: &[&str]) -> anyhow::Result<bool> {
            self.install_calls.push((
                program.to_string(),
                args.iter().map(|a| a.to_string()).collect(),
            ));
            Ok(self.install_result)
        }
        fn installed_version(&mut self) -> InstalledProbe {
            self.installed.clone()
        }
        fn latest_version(&mut self) -> Option<String> {
            self.latest.clone()
        }
        fn prune_registry(&mut self) -> Vec<String> {
            // Record that the prune ran before any npm install was attempted, so
            // tests can assert the prune is unconditional and precedes the swap.
            self.prune_calls += 1;
            self.pruned_before_install = Some(self.install_calls.is_empty());
            self.prune_lines.clone()
        }
        fn reregister_clients(&mut self) -> anyhow::Result<bool> {
            self.reregistered_after_install = !self.install_calls.is_empty();
            match &self.reregister_result {
                Ok(value) => Ok(*value),
                Err(error) => Err(anyhow::anyhow!("{error}")),
            }
        }
        fn reconcile_durable(&mut self, reregistered: bool) -> Vec<String> {
            self.reconciled_with = Some(reregistered);
            Vec::new()
        }
        fn shadow_report(&mut self) -> Option<crate::path_shadow::ShadowReport> {
            // Record that the shadow check runs only AFTER a successful install,
            // so tests can assert ordering relative to the npm swap.
            self.shadow_checked_after_install = Some(!self.install_calls.is_empty());
            self.shadow.clone()
        }
    }

    fn ok_ops() -> FakeOps {
        FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.4".to_string()),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        }
    }

    #[test]
    fn npm_executable_is_npm_cmd_on_windows_else_npm() {
        assert_eq!(npm_executable_for_os("windows"), "npm.cmd");
        assert_eq!(npm_executable_for_os("linux"), "npm");
        assert_eq!(npm_executable_for_os("macos"), "npm");
    }

    #[test]
    fn install_specs_force_the_os_native_platform_package() {
        assert_eq!(
            install_specs("windows", "x86_64"),
            vec!["symforge@latest", "symforge-windows-x64@latest"]
        );
        assert_eq!(
            install_specs("linux", "x86_64"),
            vec!["symforge@latest", "symforge-linux-x64@latest"]
        );
        assert_eq!(
            install_specs("macos", "aarch64"),
            vec!["symforge@latest", "symforge-macos-arm64@latest"]
        );
    }

    #[test]
    fn install_specs_falls_back_to_wrapper_only_for_unknown_target() {
        assert_eq!(install_specs("linux", "riscv64"), vec!["symforge@latest"]);
        assert_eq!(install_specs("plan9", "x86_64"), vec!["symforge@latest"]);
    }

    #[test]
    fn parse_symforge_version_scans_all_lines_past_leading_banner() {
        assert_eq!(
            parse_symforge_version("symforge 7.15.4\nUpdate available: 7.16.0"),
            Some("7.15.4".to_string())
        );
        // A leading banner/notice line must not hide the version.
        assert_eq!(
            parse_symforge_version("(node:1) ExperimentalWarning: blah\nsymforge 7.15.4"),
            Some("7.15.4".to_string())
        );
        assert_eq!(parse_symforge_version("no version here"), None);
        assert_eq!(parse_symforge_version(""), None);
    }

    #[test]
    fn orchestrate_update_runs_full_sequence_on_success() {
        let mut ops = ok_ops();
        orchestrate_update("linux", "x86_64", &mut ops).expect("update should succeed");

        assert!(ops.stopped_before_install, "stop must precede install");
        assert_eq!(
            ops.install_calls,
            vec![(
                "npm".to_string(),
                vec![
                    "install".to_string(),
                    "-g".to_string(),
                    "symforge@latest".to_string(),
                    "symforge-linux-x64@latest".to_string(),
                ]
            )]
        );
        assert!(
            ops.reregistered_after_install,
            "clients re-registered after install"
        );
        assert_eq!(
            ops.reconciled_with,
            Some(true),
            "orphan reconcile must run with reregistered=true on success"
        );
        assert_eq!(
            ops.shadow_checked_after_install,
            Some(true),
            "PATH-shadow check must run, and only after a successful install"
        );
    }

    #[test]
    fn orchestrate_update_warns_but_succeeds_when_a_same_version_shadow_wins() {
        // The shadow reports the SAME version the install resolved to (7.15.4),
        // which the reactive stale-version bail cannot detect. The proactive
        // shadow check must still fire; the update must still SUCCEED (the
        // warning is advisory, not a failure).
        let mut ops = ok_ops();
        ops.shadow = Some(crate::path_shadow::ShadowReport {
            our_path: std::path::PathBuf::from("/home/you/.npm-global/bin/symforge"),
            our_version: Some("7.15.4".to_string()),
            shadow_path: std::path::PathBuf::from("/usr/local/bin/symforge"),
            shadow_version: Some("7.15.4".to_string()),
            kind: crate::path_shadow::ShadowKind::RootSystem,
        });

        orchestrate_update("linux", "x86_64", &mut ops)
            .expect("a same-version shadow is advisory, not fatal");

        assert_eq!(
            ops.shadow_checked_after_install,
            Some(true),
            "shadow check ran after the install even on the same-version case"
        );
        assert!(
            ops.reregistered_after_install,
            "the advisory shadow warning must not short-circuit re-registration"
        );
    }

    #[test]
    fn launcher_path_in_prefix_maps_per_os_layout() {
        // Windows: npm places the shim at the prefix root.
        assert_eq!(
            launcher_path_in_prefix(std::path::Path::new("C:/npm-prefix"), "windows"),
            std::path::Path::new("C:/npm-prefix").join("symforge.cmd")
        );
        // Unix: conventional <prefix>/bin/<name>.
        assert_eq!(
            launcher_path_in_prefix(std::path::Path::new("/home/you/.npm-global"), "linux"),
            std::path::Path::new("/home/you/.npm-global/bin/symforge")
        );
    }

    #[test]
    fn orchestrate_update_uses_npm_cmd_and_windows_package_on_windows() {
        let mut ops = ok_ops();
        orchestrate_update("windows", "x86_64", &mut ops).expect("update should succeed");

        let (program, args) = &ops.install_calls[0];
        assert_eq!(program, "npm.cmd");
        assert!(args.contains(&"symforge-windows-x64@latest".to_string()));
    }

    #[test]
    fn orchestrate_update_reports_failed_npm_without_reregistering() {
        let mut ops = FakeOps {
            install_result: false,
            prune_lines: vec!["pruned 1 stale version-registry entry".to_string()],
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("failed npm install should be reported");

        let msg = err.to_string();
        assert!(msg.contains("exited unsuccessfully"), "{msg}");
        // The actionable hint: clear any holder, then the exact one-step install.
        assert!(
            msg.contains("Ensure no running symforge process is holding the binary"),
            "{msg}"
        );
        assert!(
            msg.contains("npm install -g symforge@latest symforge-linux-x64@latest"),
            "{msg}"
        );
        // The registry prune must run UNCONDITIONALLY and BEFORE the (blocked) swap,
        // so a blocked update still cleans cruft.
        assert_eq!(
            ops.prune_calls, 1,
            "prune must run even on a blocked update"
        );
        assert_eq!(
            ops.pruned_before_install,
            Some(true),
            "prune must run before the npm swap is attempted"
        );
        assert!(!ops.reregistered_after_install);
        assert_eq!(ops.reconciled_with, None, "no reconcile on failed install");
    }

    #[test]
    fn orchestrate_update_windows_failure_gives_staged_self_lock_guidance() {
        // On Windows the remaining lock after stopping other holders is normally
        // the update process's OWN binary. The failure must name that self-lock and
        // give the exact one-step remediation for a plain shell — while staying
        // HONEST about other holders (it must not claim it stopped all of them).
        let mut ops = FakeOps {
            install_result: false,
            ..Default::default()
        };

        let err = orchestrate_update("windows", "x86_64", &mut ops)
            .expect_err("a blocked Windows swap must fail with staged guidance");

        let msg = err.to_string();
        assert!(msg.contains("exited unsuccessfully"), "{msg}");
        assert!(
            msg.contains("running .exe") && msg.contains("PLAIN shell"),
            "must name the self-lock + a plain-shell remediation: {msg}"
        );
        assert!(
            msg.contains("npm install -g symforge@latest symforge-windows-x64@latest"),
            "must print the exact install command: {msg}"
        );
        assert!(
            msg.contains("init --client all"),
            "must print the client re-registration step: {msg}"
        );
        // Honesty (M2): never claim ALL holders were stopped (enumeration may find
        // or stop none), and always cover an un-enumerable holder (an MCP client).
        assert!(
            !msg.contains("All OTHER"),
            "must not over-claim that all holders were stopped: {msg}"
        );
        assert!(
            msg.contains("close them and rerun"),
            "must cover an un-enumerated holder (MCP client) case: {msg}"
        );
        assert!(
            !ops.reregistered_after_install,
            "a blocked swap must not re-register clients"
        );
    }

    #[test]
    fn select_inscope_holder_pids_matches_same_path_excludes_self_and_other_installs() {
        let procs = vec![
            (100u32, r"C:\npm\symforge.exe".to_string()), // in scope
            (200u32, r"C:\NPM\SYMFORGE.EXE".to_string()), // same path, case-insensitive -> in scope
            (300u32, r"D:\other\symforge.exe".to_string()), // different install -> OUT of scope (Invariant 1)
            (999u32, r"C:\npm\symforge.exe".to_string()),   // self -> excluded
        ];
        let pids = select_inscope_holder_pids(&procs, r"C:\npm\symforge.exe", 999);
        assert_eq!(
            pids,
            vec![100, 200],
            "only OTHER processes at the same executable path are in scope"
        );
    }

    #[test]
    fn select_inscope_holder_pids_empty_when_only_self_runs() {
        let procs = vec![(999u32, r"C:\npm\symforge.exe".to_string())];
        assert!(
            select_inscope_holder_pids(&procs, r"C:\npm\symforge.exe", 999).is_empty(),
            "nothing to stop when this process is the only holder"
        );
    }

    #[test]
    fn select_inscope_holder_pids_normalizes_slash_and_verbatim_path_forms() {
        // M1: a genuine holder must be matched even when its path FORM differs from
        // current_exe() — forward vs back slash, or the extended-length verbatim
        // (\\?\) prefix that current_exe() can return on Windows.
        let procs = vec![
            (100u32, r"C:\npm\symforge.exe".to_string()), // back slashes
            (200u32, "C:/npm/symforge.exe".to_string()),  // forward slashes
            (300u32, r"\\?\C:\npm\symforge.exe".to_string()), // verbatim prefix
            (400u32, r"C:\other\symforge.exe".to_string()), // different install -> excluded
        ];
        // self_exe given in the verbatim + upper-case form; all three same-binary
        // rows (100/200/300) must still be selected, the different install excluded.
        let pids = select_inscope_holder_pids(&procs, r"\\?\C:\NPM\symforge.exe", 999);
        assert_eq!(
            pids,
            vec![100, 200, 300],
            "path-form variants of the same binary are all in scope (M1)"
        );
    }

    /// Copy a benign long-lived system exe to `<tmp>/symforge.exe` and spawn
    /// it so the process's image FILE NAME is the symforge binary name (the
    /// pattern Terminal Commander's supervisor tests use). The returned
    /// `TempDir` keeps the copied exe alive for the test's duration.
    #[cfg(windows)]
    fn spawn_fake_symforge() -> (tempfile::TempDir, std::process::Child) {
        let dir = tempfile::tempdir().expect("tempdir");
        let fake = dir.path().join("symforge.exe");
        let ping = std::path::Path::new(r"C:\Windows\System32\PING.EXE");
        std::fs::copy(ping, &fake).expect("copy ping.exe to symforge.exe");
        // `ping -n 30 127.0.0.1` stays alive ~30s; far longer than the test.
        let child = crate::process_util::hidden_command(&fake)
            .args(["-n", "30", "127.0.0.1"])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .expect("spawn fake symforge");
        (dir, child)
    }

    #[test]
    #[cfg(windows)]
    fn enumerate_symforge_processes_finds_spawned_symforge_image_with_full_path() {
        let (dir, mut child) = spawn_fake_symforge();
        let pid = child.id();
        let procs = enumerate_symforge_processes();
        let _ = child.kill();
        let _ = child.wait();
        let found = procs.iter().find(|(p, _)| *p == pid);
        let (_, path) = found.expect("native enumeration must list the spawned symforge.exe");
        assert_eq!(
            normalize_exe_path(path),
            normalize_exe_path(&dir.path().join("symforge.exe").to_string_lossy()),
            "the enumerated entry must carry the FULL image path for install scoping"
        );
    }

    #[test]
    #[cfg(windows)]
    fn terminate_inscope_holder_kills_matching_path_and_spares_mismatch() {
        // Mismatched expected path -> the holder must be left alive
        // (Invariant 1: never touch another install; recycled-pid defense).
        let (dir, mut child) = spawn_fake_symforge();
        let pid = child.id();
        terminate_inscope_holder(pid, r"C:\some\other\install\symforge.exe");
        assert!(
            child.try_wait().expect("try_wait").is_none(),
            "a path-mismatched pid must NOT be terminated"
        );

        // Matching expected path -> terminated (this is the bug the taskkill
        // graceful leg used to mask: console processes refused the graceful
        // close and never reached the forced kill).
        let expected = dir
            .path()
            .join("symforge.exe")
            .to_string_lossy()
            .to_string();
        terminate_inscope_holder(pid, &expected);
        let status = child.wait().expect("wait on terminated child");
        assert!(
            !status.success(),
            "TerminateProcess(exit=1) must make the holder exit non-zero"
        );

        // A second terminate of the now-dead pid must be a no-op (identity
        // gate: the pid no longer resolves to this image path).
        terminate_inscope_holder(pid, &expected);
    }

    #[test]
    #[cfg(windows)]
    fn terminate_inscope_holder_never_kills_the_test_runner() {
        // The test runner is alive but its image is the test binary, not the
        // expected symforge path -> must be refused (this failing would kill
        // the test host, exactly TC's guard).
        terminate_inscope_holder(std::process::id(), r"C:\npm\symforge.exe");
    }

    #[test]
    fn select_inscope_rejects_other_install_and_absent_rows() {
        let procs = vec![
            (100u32, r"C:\npm\symforge.exe".to_string()),
            (200u32, r"D:\other\symforge.exe".to_string()),
            (300u32, r"\\?\C:\NPM\symforge.exe".to_string()),
        ];
        assert_eq!(
            select_inscope_holder_pids(&procs, r"C:\NPM\symforge.exe", 999),
            vec![100, 300],
            "same-path rows (any form) are in scope; the other install is not"
        );
        assert_eq!(
            select_inscope_holder_pids(&procs, r"C:\npm\symforge.exe", 100),
            vec![300],
            "the self pid must never be selected, even at the same path"
        );
    }

    #[test]
    fn orchestrate_update_prunes_registry_before_install_on_success() {
        let mut ops = ok_ops();
        ops.prune_lines = vec!["pruned 2 stale version-registry entries".to_string()];

        orchestrate_update("linux", "x86_64", &mut ops).expect("update should succeed");

        assert_eq!(ops.prune_calls, 1, "prune runs exactly once");
        assert_eq!(
            ops.pruned_before_install,
            Some(true),
            "prune precedes the npm swap"
        );
    }

    #[test]
    fn orchestrate_update_fails_loudly_when_resolved_version_stays_stale() {
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.2".to_string()),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("stale resolved version must fail loudly");

        let msg = err.to_string();
        assert!(msg.contains("incomplete"), "{msg}");
        assert!(msg.contains("7.15.2") && msg.contains("7.15.4"), "{msg}");
        assert!(msg.contains("PATH-shadowing"), "{msg}");
        assert!(
            !ops.reregistered_after_install,
            "no re-register on a drifted install"
        );
    }

    #[test]
    fn orchestrate_update_bails_on_launcher_failure_surfacing_stderr() {
        // The marquee WSL/launcher case: install "succeeds" but the launcher
        // cannot resolve a binary. Must bail loudly, not report "skipped".
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::LauncherFailed(
                "symforge: platform package symforge-linux-x64 not found".to_string(),
            ),
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("a launcher that cannot resolve a binary must fail loudly");

        let msg = err.to_string();
        assert!(msg.contains("could not resolve a native binary"), "{msg}");
        assert!(msg.contains("symforge-linux-x64 not found"), "{msg}");
        assert!(!ops.reregistered_after_install);
    }

    #[test]
    fn orchestrate_update_floors_against_running_version_when_registry_offline() {
        // Registry unreachable (latest=None) AND the resolved binary is older than
        // the binary running the update — the swap demonstrably failed, so bail
        // even without a registry answer.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("0.0.1".to_string()),
            latest: None,
            ..Default::default()
        };

        let err = orchestrate_update("linux", "x86_64", &mut ops)
            .expect_err("a binary older than the running update binary must fail even offline");

        assert!(err.to_string().contains("incomplete"), "{err:?}");
        assert!(!ops.reregistered_after_install);
    }

    #[test]
    fn orchestrate_update_warns_but_succeeds_when_probe_is_unavailable() {
        // Launcher genuinely not spawnable: install ran, so don't fail; still
        // re-register + reconcile.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Unprobeable,
            latest: Some("7.15.4".to_string()),
            ..Default::default()
        };
        orchestrate_update("linux", "x86_64", &mut ops)
            .expect("unprobeable launcher must not fail an otherwise-successful update");
        assert!(ops.reregistered_after_install);
        assert_eq!(ops.reconciled_with, Some(true));
    }

    #[test]
    fn orchestrate_update_does_not_remove_orphan_when_reregistration_fails() {
        // reconcile must be told reregistered=false so the orphan (still
        // referenced by clients) is NOT deleted.
        let mut ops = FakeOps {
            install_result: true,
            installed: InstalledProbe::Version("7.15.4".to_string()),
            latest: Some("7.15.4".to_string()),
            reregister_result: Ok(false),
            ..Default::default()
        };
        orchestrate_update("linux", "x86_64", &mut ops).expect("update should still succeed");
        assert_eq!(
            ops.reconciled_with,
            Some(false),
            "failed re-registration must prevent orphan removal"
        );
    }

    #[test]
    fn install_invocation_uses_no_shell_wrappers() {
        let mut ops = ok_ops();
        orchestrate_update("windows", "x86_64", &mut ops).unwrap();

        let (program, args) = &ops.install_calls[0];
        let text = invocation_text(
            program,
            &args.iter().map(String::as_str).collect::<Vec<_>>(),
        )
        .to_ascii_lowercase();
        assert!(!text.contains("powershell"));
        assert!(!text.contains("cmd /c"));
        assert!(!text.contains("executionpolicy"));
    }

    // ── Windows self-update robustness: timeout floor, move-aside staging, sweep ──

    struct NeverExits {
        kills: usize,
    }
    impl Waitable for NeverExits {
        fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
            Ok(None)
        }
        fn kill(&mut self) -> std::io::Result<()> {
            self.kills += 1;
            Ok(())
        }
    }

    #[test]
    fn wait_or_kill_times_out_kills_the_child_and_returns_false() {
        // The safety floor: a child that never exits must be killed at the
        // deadline and reported as Ok(false) so the graceful bail fires — never a
        // hang. A deadline already in the past trips on the first poll (no sleep).
        let mut child = NeverExits { kills: 0 };
        let result = wait_or_kill(
            &mut child,
            std::time::Instant::now(),
            std::time::Duration::from_millis(1),
        )
        .expect("a timeout is Ok(false), not an error");
        assert!(!result, "a timed-out swap must return Ok(false)");
        assert_eq!(child.kills, 1, "the hung child must be killed exactly once");
    }

    #[test]
    fn stale_staging_dir_is_the_global_prefix_sibling_not_inside_a_wrapper() {
        // Derived from the npm GLOBAL prefix (npm prefix -g), so even a deeply
        // nested install
        // (.../node_modules/symforge/node_modules/symforge-windows-x64/bin/...)
        // stages beside the GLOBAL node_modules — never inside the wrapper package
        // npm rimrafs. The dir depends ONLY on the prefix, not on exe nesting, so
        // the old "walk to innermost node_modules ancestor" brick is gone.
        // Forward slashes so components parse identically on Windows and Unix.
        let prefix = std::path::Path::new("C:/Users/me/AppData/Roaming/npm");
        let dir = stale_staging_dir(prefix);
        assert_eq!(
            dir,
            std::path::Path::new("C:/Users/me/AppData/Roaming/npm/.symforge-update-stale"),
            "staging dir is the global prefix's .symforge-update-stale"
        );
        assert!(
            !dir.starts_with("C:/Users/me/AppData/Roaming/npm/node_modules"),
            "staging dir must be a global-prefix sibling, outside node_modules: {dir:?}"
        );
    }

    #[test]
    fn staged_restore_repopulates_the_path_when_no_binary_landed() {
        // Closes ALL THREE brick paths at once — a failed spawn, a `try_wait`
        // error, a timeout, AND the npm-exit-0-but-no-re-extract re-run: the guard
        // drops with the install path still EMPTY and must move the staged binary
        // back so the install is never bricked.
        let tmp = tempfile::tempdir().unwrap();
        let original = tmp.path().join("symforge.exe"); // npm's target — left empty
        let staged = tmp
            .path()
            .join(".symforge-update-stale")
            .join("symforge.exe.old-1");
        std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
        std::fs::write(&staged, b"the-old-binary").unwrap();
        assert!(!original.exists(), "precondition: npm landed no binary");

        drop(StagedRestore {
            staged: staged.clone(),
            original: original.clone(),
        });

        assert!(
            original.exists(),
            "the guard must restore the binary to the empty install path"
        );
        assert_eq!(std::fs::read(&original).unwrap(), b"the-old-binary");
        assert!(
            !staged.exists(),
            "the staged copy moved back, not left behind"
        );
    }

    #[test]
    fn staged_restore_disarms_when_a_binary_landed() {
        // npm re-extracted a fresh binary at the path (npm returned 0 OR not — the
        // guard never looks at the exit code, only at the path) → it must NOT
        // clobber the fresh binary; the staged `.old` is left for the next sweep.
        let tmp = tempfile::tempdir().unwrap();
        let original = tmp.path().join("symforge.exe");
        std::fs::write(&original, b"fresh-binary").unwrap(); // npm's fresh install landed
        let staged = tmp
            .path()
            .join(".symforge-update-stale")
            .join("symforge.exe.old-1");
        std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
        std::fs::write(&staged, b"the-old-binary").unwrap();

        drop(StagedRestore {
            staged: staged.clone(),
            original: original.clone(),
        });

        assert_eq!(
            std::fs::read(&original).unwrap(),
            b"fresh-binary",
            "a landed binary must survive the guard drop"
        );
        assert!(
            staged.exists(),
            "the staged .old is left for the sweep when a binary landed"
        );
    }

    #[test]
    fn sweep_stale_dir_removes_leftovers_skips_unremovable_and_tolerates_missing() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        std::fs::write(dir.join("symforge.exe.old-1"), b"a").unwrap();
        std::fs::write(dir.join("symforge.exe.old-2"), b"b").unwrap();
        // A subdirectory stands in for a still-locked entry: remove_file refuses a
        // directory on every platform, so the sweep must SKIP it, not fail.
        std::fs::create_dir(dir.join("locked-like-subdir")).unwrap();

        let lines = sweep_stale_dir(dir);
        assert!(!dir.join("symforge.exe.old-1").exists());
        assert!(!dir.join("symforge.exe.old-2").exists());
        assert!(
            dir.join("locked-like-subdir").exists(),
            "an unremovable entry must be skipped, not fail the sweep"
        );
        assert_eq!(lines.len(), 1, "one summary line: {lines:?}");
        assert!(lines[0].contains("swept 2"), "{lines:?}");

        // A nonexistent directory (no prior staging) is a silent no-op.
        assert!(sweep_stale_dir(&dir.join("nope")).is_empty());
    }

    #[test]
    #[cfg(not(windows))]
    fn staging_and_sweep_are_noops_on_unix() {
        // Unix overwrites a running binary in place, so there is nothing to stage
        // or sweep — both entry points are a no-op (and no guard is ever created).
        assert!(stage_running_binary_aside().is_none());
        assert!(run_stale_sweep().is_empty());
    }

    #[test]
    #[cfg(windows)]
    fn move_file_replace_existing_ffi_moves_a_plain_file() {
        // Exercises the load-bearing unsafe on a NON-running file (a live-binary
        // swap can't be unit-tested; see the module SAFETY notes).
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("src.bin");
        let dst = tmp.path().join("staged.old-42");
        std::fs::write(&src, b"payload").unwrap();
        windows_native::move_file_replace_existing(&src, &dst).expect("FFI move succeeds");
        assert!(!src.exists(), "the source path is freed after the move");
        assert_eq!(std::fs::read(&dst).unwrap(), b"payload");
    }

    #[test]
    #[cfg(windows)]
    fn move_path_aside_frees_the_source_path() {
        let tmp = tempfile::tempdir().unwrap();
        let src = tmp.path().join("symforge.exe");
        let staged = tmp
            .path()
            .join(".symforge-update-stale")
            .join("symforge.exe.old-1");
        std::fs::create_dir_all(staged.parent().unwrap()).unwrap();
        std::fs::write(&src, b"binary").unwrap();
        move_path_aside(&src, &staged).expect("move aside succeeds");
        assert!(!src.exists(), "the install path is freed for npm");
        assert!(staged.exists());
    }

    // Tests that mutate `SYMFORGE_HOME` serialize on this lock and rely on
    // `--test-threads=1`, so no concurrent env reader observes the transition.
    static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// RAII guard: set `SYMFORGE_HOME` for the body's duration and restore the
    /// prior value (set or unset) on drop, so the env mutation never leaks to
    /// other tests even on panic.
    struct SymforgeHomeGuard {
        prev: Option<std::ffi::OsString>,
    }

    impl SymforgeHomeGuard {
        #[allow(unsafe_code)] // test-only env mutation under ENV_LOCK + --test-threads=1.
        fn set(value: &std::path::Path) -> Self {
            let prev = std::env::var_os("SYMFORGE_HOME");
            // SAFETY: the caller holds ENV_LOCK and the suite runs single-threaded,
            // so no other thread can read or write the environment concurrently.
            unsafe { std::env::set_var("SYMFORGE_HOME", value) };
            Self { prev }
        }
    }

    impl Drop for SymforgeHomeGuard {
        #[allow(unsafe_code)] // test-only env restore under ENV_LOCK + --test-threads=1.
        fn drop(&mut self) {
            // SAFETY: see `SymforgeHomeGuard::set`.
            match &self.prev {
                Some(prev) => unsafe { std::env::set_var("SYMFORGE_HOME", prev) },
                None => unsafe { std::env::remove_var("SYMFORGE_HOME") },
            }
        }
    }

    #[test]
    fn remove_orphan_durable_bin_cleans_under_symforge_home_and_spares_self_exe() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        let home = tempfile::TempDir::new().unwrap();
        let bin = home.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();

        // A retired durable leftover that is NOT the running process binary.
        let leftover = bin.join("symforge.exe");
        std::fs::write(&leftover, b"old-7.14.4-binary").unwrap();
        // An unrelated file that is not in the watched set must be left untouched.
        let bystander = bin.join("notes.txt");
        std::fs::write(&bystander, b"keep me").unwrap();

        // Point SYMFORGE_HOME at this temp home: Bug 2 is that the cleanup used to
        // bail entirely whenever SYMFORGE_HOME was set. It must now run.
        let _home_guard = SymforgeHomeGuard::set(home.path());

        // Sanity: the running test binary is a real, canonicalizable path and is
        // NOT inside this temp bin, so the self-exe guard must never delete it.
        let self_exe = std::env::current_exe().unwrap();
        assert!(self_exe.exists(), "precondition: running exe exists");

        let summary = remove_orphan_durable_bin_at(&crate::domain::ControlStateDir::new(
            home.path().to_path_buf(),
        ));

        assert!(
            !leftover.exists(),
            "the retired durable leftover under $SYMFORGE_HOME/bin must be removed"
        );
        assert_eq!(summary.len(), 1, "exactly one summary line: {summary:?}");
        assert!(
            summary[0].contains("symforge.exe"),
            "summary names what was removed: {summary:?}"
        );
        assert!(bystander.exists(), "an unwatched file must be left alone");
        // The self-exe guard's invariant: the running process binary still exists.
        assert!(
            self_exe.exists(),
            "the binary backing the running process must never be deleted"
        );
    }

    #[test]
    fn remove_orphan_durable_bin_skips_the_running_binary_when_it_lives_in_the_bin_dir() {
        let _g = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
        // Directly exercise the self-exe guard's `continue` branch: place the
        // running test binary INTO `$SYMFORGE_HOME/bin` under a watched name via a
        // symlink (so canonicalization resolves it back to the same file, matching
        // the guard's canonical-path identity check). A plain copy would have a
        // distinct canonical path and would not be a fair test of the guard.
        let self_exe = match std::env::current_exe()
            .ok()
            .and_then(|p| std::fs::canonicalize(p).ok())
        {
            Some(p) => p,
            None => return, // no canonicalizable current exe — nothing to assert
        };

        let home = tempfile::TempDir::new().unwrap();
        let bin = home.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        let watched = bin.join("symforge.exe");

        if make_symlink(&self_exe, &watched).is_err() {
            // Symlink creation may require privilege (Windows) — skip rather than
            // fail; the other durable test still covers the spare-self invariant.
            return;
        }
        // Confirm the link resolves to the running binary, so the guard must skip it.
        let resolves_to_self =
            std::fs::canonicalize(&watched).ok().as_deref() == Some(self_exe.as_path());
        if !resolves_to_self {
            return;
        }

        let _home_guard = SymforgeHomeGuard::set(home.path());
        let summary = remove_orphan_durable_bin();

        assert!(
            watched.exists() || std::fs::symlink_metadata(&watched).is_ok(),
            "the entry resolving to the running binary must NOT be removed"
        );
        assert!(self_exe.exists(), "the running binary itself must survive");
        assert!(
            summary.is_empty(),
            "nothing should be reported removed: {summary:?}"
        );
    }

    #[cfg(unix)]
    fn make_symlink(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
        std::os::unix::fs::symlink(src, dst)
    }

    #[cfg(windows)]
    fn make_symlink(src: &std::path::Path, dst: &std::path::Path) -> std::io::Result<()> {
        std::os::windows::fs::symlink_file(src, dst)
    }
}