sentinela 0.1.32

sentinela — the pure-Rust Darwin GitOps node-sync daemon (the Mac peer of NixOS comin)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
//! The production [`GitopsEnv`] — pure Rust, typed `Command`, **no
//! shell**. Every impure action the daemon takes lives here behind the
//! trait the FSM is pure over. The three impure verbs (`git ls-remote`,
//! `darwin-rebuild build`, `darwin-rebuild switch`) are typed argv, and
//! the receipt chain is a content-addressed JSON file written atomically.
//!
//! The pure decision helpers (`inject_token`, `parse_ls_remote`,
//! `parse_generation`, the flake-ref + refspec builders) are separated
//! out and unit-tested — the `Command`-executing methods are thin
//! wrappers over them. No `format!` of any argv (fleet TYPED-EMISSION
//! ban): argv pieces are `concat`'d or built with typed builders.

use sentinela_config::SentinelaConfig;
use sentinela_core::{CheckResult, CheckState};
use sentinela_core::{
    BuildProgress, EnvError, Generation, GitopsEnv, HealthProbe, Heartbeat, PlanOutcome,
    PlanVerdict, ProbeCheck, ReceiptChain, RebuildDriver, Rev,
};
use std::fs::File;
use std::io::Write as _;
use std::os::unix::fs::PermissionsExt as _;
use std::os::unix::process::CommandExt as _;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
use std::time::{SystemTime, UNIX_EPOCH};
use tsunagu::exec::{BoundedRun, OnTimeout};
use url::Url;

/// The nix system profile whose generation number a switch advances.
const SYSTEM_PROFILE: &str = "/nix/var/nix/profiles/system";
/// The closure the machine is running (NixOS and nix-darwin both keep it).
const RUNNING_SYSTEM: &str = "/run/current-system";

/// How much of a failing probe's output survives into its evidence. A probe
/// runs every round of a probation, and its evidence lands in the heartbeat
/// and — on a rollback — the append-only chain; the diagnosis is at the end.
const PROBE_TAIL_BYTES: usize = 1024;
/// `darwin-rebuild` from the running system (root, no sudo needed under
/// the launchd daemon).

/// The one machine-wide rebuild lock — THE SAME absolute path `fleet
/// rebuild` uses (`pleme-io/fleet/src/commands/rebuild.rs`), so an
/// operator rebuild and the daemon's switch serialize against each other
/// instead of racing activation state (the sops-nix `/run/secrets.d`
/// generation-cleanup race fleet's lock documents).
///
/// ── ★ ABSOLUTE ON PURPOSE — `temp_dir()` SERIALIZES NOTHING ────────────
/// macOS gives every user a per-user `$TMPDIR`, so `temp_dir()` resolves a
/// DIFFERENT file per user and the "shared" lock serializes one user's
/// shell sessions only. The root daemon's launchd job sets no `TMPDIR`, so
/// it resolved yet another path — the exact race this lock exists to close
/// was running with no contention at all (measured on ryn 2026-08-02, fully
/// documented in fleet's `REBUILD_LOCK_PATH`). `/tmp` is the one
/// machine-wide writable directory; `/private/tmp` is mode `1777` (sticky,
/// world-writable), so both root and the operator can create and open this
/// file and neither can unlink the other's.
const REBUILD_LOCK_PATH: &str = sentinela_config::LEGACY_REBUILD_LOCK_PATH;

/// The production environment. Owns the config; the receipt chain lives
/// at `<state_dir>/receipts.json`.
pub struct RealEnv {
    cfg: SentinelaConfig,
}

impl RealEnv {
    /// Build from the loaded config.
    #[must_use]
    pub fn new(cfg: SentinelaConfig) -> Self {
        Self { cfg }
    }

    /// Where the receipt chain lives. **YAML**, and now named so.
    ///
    /// ── ★ THE FILENAME USED TO LIE, AND IT MISLED A CAREFUL READER ────────
    /// This returned `receipts.json` while [`Self::persist_chain`] serialises
    /// with `serde_yaml` — the heartbeat beside it is genuine JSON, so two
    /// files in one directory disagreed about what `.json` means. Verified on
    /// cid 2026-08-05: the live file begins `- seq: 0` / `  rev: …`, i.e. YAML.
    ///
    /// Not cosmetic. During a 2026-08-05 audit an agent reasoned from the
    /// extension that `fleet`'s chain reader must be broken (a bare
    /// `kind:`/`rev:` prefix scan cannot match JSON), reported it as a likely
    /// silent failure — and was wrong. The parser was right; the NAME was
    /// wrong. Anyone pointing a JSON parser at it gets a hard failure on a file
    /// that has been YAML since inception.
    fn receipts_path(&self) -> PathBuf {
        Path::new(&self.cfg.state_dir).join("receipts.yaml")
    }

    /// The pre-2026-08-05 path — `receipts.json`, containing YAML.
    ///
    /// Read-only, and never deleted by this daemon. The chain is hash-linked
    /// (`prev_hash`), so it is the only durable record that this node's deploys
    /// are what they claim to be; silently unlinking it would destroy an audit
    /// trail to tidy a filename. [`Self::load_chain`] falls back to it and
    /// [`Self::persist_chain`] writes only the canonical path, so the first
    /// save after an upgrade migrates the content forward and leaves the
    /// original for an operator to remove deliberately.
    fn legacy_receipts_path(&self) -> PathBuf {
        Path::new(&self.cfg.state_dir).join("receipts.json")
    }

    /// The liveness pulse, beside the chain. Separate file on purpose: it
    /// is rewritten every tick (the chain is append-only and rarely
    /// changes), and a reader that only wants "is this loop alive" must
    /// not have to parse a chain that reached 31 MB on ryn.
    pub fn heartbeat_path(&self) -> PathBuf {
        Path::new(&self.cfg.state_dir).join("heartbeat.json")
    }

    /// Read the last published pulse, if any. `None` means no heartbeat
    /// has ever been written — which a reader must treat as "cannot tell",
    /// never as healthy.
    pub fn load_heartbeat(&self) -> Option<Heartbeat> {
        let raw = std::fs::read_to_string(self.heartbeat_path()).ok()?;
        serde_json::from_str(&raw).ok()
    }

    /// The `<flake_url>/<rev>#<hostname>` flake ref for a rev-pinned build.
    fn flake_ref(&self, rev: &Rev) -> String {
        [
            &self.cfg.flake_url,
            "/",
            rev.as_str(),
            "#",
            &self.cfg.hostname,
        ]
        .concat()
    }

    /// The probe URL — **never carries a credential**.
    ///
    /// ── ★ THE CREDENTIAL LEFT THE URL (2026-08-17) ────────────────────────
    /// This used to return `https://x-access-token:<PAT>@github.com/...`, and
    /// that one decision leaked the token to two places at once:
    ///
    /// 1. **argv.** The URL is an argument to `ls-remote`, `clone` and
    ///    `fetch`, and argv is world-readable via `ps` on every tick — ~98k
    ///    probes over 68 days on this fleet.
    /// 2. **disk, permanently.** `git clone --bare <url>` writes the remote
    ///    URL verbatim into the mirror's `config`. Measured on ryn: the PAT
    ///    sat in `/var/log/pleme-gitops/ancestry.git/config` at mode 0644
    ///    root:wheel, in a *log* directory, written 2026-08-03 and unchanged
    ///    for 14 days — outliving any rotation of the source secret, because
    ///    nothing rewrites a mirror that already exists.
    ///
    /// The credential now travels via [`Self::apply_git_auth`] instead. Note
    /// the honest tier: this moves the secret from **world-readable** (argv +
    /// a 0644 file) to **same-uid-or-root** (the child's environment). That is
    /// mitigation, not unrepresentability — a root-capable reader still sees
    /// it, and the only structural fix is a credential the process never holds
    /// in plaintext at all.
    fn probe_url(&self) -> String {
        self.cfg.rev_probe.git_url.clone()
    }

    /// The configured token, if one is readable and non-empty.
    ///
    /// A missing/unreadable token file yields `None` → the git call runs
    /// unauthenticated. Public repos still resolve; private ones fail closed
    /// at the probe, which is the correct direction.
    fn probe_token(&self) -> Option<String> {
        let tf = self.cfg.rev_probe.token_file.as_ref()?;
        let raw = std::fs::read_to_string(tf).ok()?;
        let t = raw.trim();
        if t.is_empty() { None } else { Some(t.to_owned()) }
    }

    /// Whether the ancestry mirror can be trusted as-is.
    ///
    /// Two conditions, and a failure of either means "re-clone", never
    /// "carry on":
    ///
    /// 1. **It is a real bare repository.** `git rev-parse --git-dir` is the
    ///    question; `Path::exists()` is not. A clone killed mid-transfer
    ///    leaves a directory that passes the second and fails the first.
    /// 2. **Its stored remote URL carries no credential.** `git clone --bare
    ///    <url-with-userinfo>` persists that URL into `config`, so every
    ///    mirror created before the credential moved to a header still holds
    ///    a live PAT at mode 0644 — measured on ryn, unchanged for 14 days.
    ///    Nothing else in the loop ever rewrites an existing mirror, so
    ///    without this arm no future tick would ever clean it.
    ///
    /// Deliberately conservative: any error reading the config counts as
    /// unusable. Re-cloning costs one tick; trusting a mirror we could not
    /// inspect costs the guarantee the caller is about to relax.
    fn mirror_is_usable(&self, mirror: &Path) -> bool {
        if !mirror.exists() {
            return false;
        }
        let valid_repo = self
            .run_git(
                {
                    let mut c = Command::new("git");
                    c.arg("--git-dir").arg(mirror).arg("rev-parse").arg("--git-dir");
                    c
                },
                EnvError::AncestryFailed,
            )
            .is_ok_and(|o| o.status.success());
        if !valid_repo {
            return false;
        }
        // Read the config directly rather than shelling out again: this runs
        // on every ancestry call and the file is a few hundred bytes.
        match std::fs::read_to_string(mirror.join("config")) {
            Ok(cfg) => !cfg.contains('@') || !cfg.contains("url = http"),
            Err(_) => false,
        }
    }

    /// Attach HTTP basic auth to a git subprocess **without** putting it in
    /// argv or in any on-disk config.
    ///
    /// Uses git's environment-variable config form (`GIT_CONFIG_COUNT` /
    /// `GIT_CONFIG_KEY_<n>` / `GIT_CONFIG_VALUE_<n>`), which git applies as if
    /// the key had been passed with `-c` — but an env var is not in argv, so
    /// it never appears in `ps`, and it is not written to `.git/config`, so a
    /// cloned mirror cannot persist it.
    ///
    /// Basic, not Bearer: measured against github.com 2026-08-17, the git
    /// smart-HTTP endpoint returns **401 for `Authorization: Bearer <valid>`**
    /// and 200 for `Basic base64("x-access-token:<valid>")`. The Bearer form
    /// is the REST-API plane's, not the git plane's.
    fn apply_git_auth(&self, cmd: &mut Command) {
        let Some(token) = self.probe_token() else {
            return;
        };
        let mut header = String::from("Authorization: Basic ");
        header.push_str(&base64_std(
            ["x-access-token:", token.as_str()].concat().as_bytes(),
        ));
        cmd.env("GIT_CONFIG_COUNT", "1")
            .env("GIT_CONFIG_KEY_0", "http.extraHeader")
            .env("GIT_CONFIG_VALUE_0", &header);
        // Best-effort scrub of our own copies. Not `zeroize`: taking that
        // dependency means a `gen build` regeneration and the D2 freshness
        // tie, for a buffer whose lifetime is one exec. Labelled best-effort
        // rather than claimed as zeroization.
        scrub(header);
        scrub(token);
    }

    /// The ancestry mirror, cloned if unusable and fetched now — the shared
    /// first half of [`GitopsEnv::is_ancestor`] and [`GitopsEnv::candidates`].
    /// Fail-closed: any error is the caller's error variant's business, and
    /// both callers read an error as "do not relax the rule".
    fn sync_mirror(&self) -> Result<PathBuf, EnvError> {
        let url = self.probe_url();
        let mirror = Path::new(&self.cfg.state_dir).join("ancestry.git");

        // ── ★ `.exists()` ASKS THE WRONG QUESTION ─────────────────────────
        // The invariant is "is a valid bare repo carrying no credential",
        // not "is a directory". `git clone` CREATES the target before it is a
        // repository, so a clone killed by the `git_timeout_seconds` deadline
        // — or by any `kill -9` during the first cold clone on a fresh node —
        // leaves a path that satisfies `.exists()` forever. Every later tick
        // then skips the clone, fetches into a non-repository, and returns
        // `AncestryFailed`.
        //
        // The blast radius is why this is worth a validation rather than a
        // comment: BOTH starvation escapes route through `is_ancestor` (the
        // deferral escape at fsm.rs:509/514 and `try_land_last_good` at
        // fsm.rs:620/624), and both fail closed on `Err`. So a poisoned
        // mirror disables both at once while the daemon keeps ticking, keeps
        // publishing a fresh heartbeat, and keeps printing CONVERGED. That is
        // the rio-2026-08-05 shape — a loop that cannot make progress while
        // every liveness surface reads green.
        //
        // Validating also makes it SELF-HEALING, which a rename-only fix does
        // not: a mirror poisoned before this shipped is repaired on the next
        // tick, with no operator action, on every node.
        //
        // The credential half is the same predicate for the same reason.
        // Until today the clone URL carried `x-access-token:<PAT>@`, which
        // `git clone --bare` persists verbatim into the mirror's config; the
        // fix that stopped NEW mirrors leaking does nothing for the ones
        // already on disk, because nothing ever rewrites an existing mirror.
        // Folding it in here means one tick repairs both, fleet-wide.
        if !self.mirror_is_usable(&mirror) {
            let staging = Path::new(&self.cfg.state_dir).join("ancestry.git.new");
            let _ = std::fs::remove_dir_all(&staging);
            let out = self.run_git({ let mut c = Command::new("git");
                c.arg("clone")
                .arg("--bare")
                .arg("--filter=blob:none")
                .arg(&url)
                .arg(&staging);
                self.apply_git_auth(&mut c);c }, EnvError::AncestryFailed)?;
            if !out.status.success() {
                let _ = std::fs::remove_dir_all(&staging);
                return Err(EnvError::AncestryFailed(
                    String::from_utf8_lossy(&out.stderr).trim().to_owned(),
                ));
            }
            // Clone into a sibling and rename, so a kill during the clone can
            // never leave a half-built directory at the live path again.
            // `rename` onto a non-empty directory is ENOTEMPTY, so the old
            // one goes first — it is already known-unusable at this point.
            let _ = std::fs::remove_dir_all(&mirror);
            if let Err(e) = std::fs::rename(&staging, &mirror) {
                let _ = std::fs::remove_dir_all(&staging);
                return Err(EnvError::AncestryFailed(e.to_string()));
            }
        }

        // Fetch both revs explicitly. A branch fetch is not enough: the rev
        // we built may already have been superseded, and on a force-push it
        // may be unreachable from any ref at all — which is exactly the case
        // that must answer "not an ancestor" rather than error out into a
        // retry loop.
        // The most network-exposed call in the whole tick: an actual object
        // transfer from a remote we do not control. Bounded like the rest.
        let fetch = self.run_git(
            {
                let mut c = Command::new("git");
                c.arg("--git-dir")
                    .arg(&mirror)
                    .arg("fetch")
                    .arg("--quiet")
                    .arg(&url)
                    .arg(format!(
                        "+refs/heads/{}:refs/heads/probe",
                        self.cfg.rev_probe.branch
                    ));
                self.apply_git_auth(&mut c);
                c
            },
            EnvError::AncestryFailed,
        )?;
        if !fetch.status.success() {
            return Err(EnvError::AncestryFailed(
                String::from_utf8_lossy(&fetch.stderr).trim().to_owned(),
            ));
        }

        Ok(mirror)
    }

    /// The driver for this node's configured rebuild tool.
    ///
    /// Constructed per call rather than stored: it borrows the config, and a
    /// driver is a zero-cost dispatch wrapper, not a resource. Selection is
    /// the typed `RebuildTool` sum plus, for sui, `SuiMode`: `subprocess` runs
    /// the `sui` CLI through the same bounded shell driver, `embedded` runs
    /// sui-orchestrate in this process. `preflight` refuses `embedded` on a
    /// binary built without the `sui-driver` feature.
    fn driver(&self) -> Result<Box<dyn RebuildDriver + '_>, EnvError> {
        match self.cfg.rebuild_tool {
            sentinela_config::RebuildTool::DarwinRebuild
            | sentinela_config::RebuildTool::NixosRebuild => Ok(Box::new(ShellDriver { env: self })),
            sentinela_config::RebuildTool::Sui => match self.cfg.sui.mode {
                sentinela_config::SuiMode::Subprocess => Ok(Box::new(ShellDriver { env: self })),
                sentinela_config::SuiMode::Embedded => self.sui_driver(),
            },
        }
    }

    /// The sui driver, when this binary was built with it.
    ///
    /// A build WITHOUT the `sui-driver` feature refuses the selection rather
    /// than silently falling back to the shell: a node whose config asks for
    /// the in-process driver and quietly gets the subprocess one would report
    /// success while carrying exactly the wedge class it opted out of. The
    /// same reasoning as `preflight` refusing a sui/remote-ref pairing —
    /// fail loudly at the boundary, never behind a green heartbeat.
    #[cfg(feature = "sui-driver")]
    fn sui_driver(&self) -> Result<Box<dyn RebuildDriver + '_>, EnvError> {
        Ok(Box::new(SuiDriver))
    }

    #[cfg(not(feature = "sui-driver"))]
    #[allow(clippy::unnecessary_wraps, clippy::unused_self)]
    fn sui_driver(&self) -> Result<Box<dyn RebuildDriver + '_>, EnvError> {
        Err(EnvError::ToolMissing {
            tool: "sui (built without the `sui-driver` feature)".to_owned(),
        })
    }

    /// Where the rebuild tool is run from. See [`Self::run_rebuild`]
    /// — this is load-bearing, not incidental.
    fn rebuild_cwd(&self) -> &Path {
        Path::new(&self.cfg.state_dir)
    }

    /// Takes the flake ref as a STRING, not a `Rev`: the driver seam speaks
    /// refs, and building one from a rev is `RealEnv`'s job (it owns the
    /// flake_url and hostname), not the driver's.
    fn run_rebuild_ref(&self, verb: &str, flake_ref: &str) -> Result<std::process::Output, EnvError> {
        let mut cmd = Command::new(self.cfg.rebuild_binary());
        for word in rebuild_argv(
            self.cfg.rebuild_tool,
            verb,
            flake_ref,
            &self.cfg.extra_rebuild_args,
        ) {
            cmd.arg(word);
        }
        // ── ★ THE REBUILD MUST RUN FROM A WRITABLE DIRECTORY ──────────────
        // `darwin-rebuild` appends `--no-link` for every action EXCEPT
        // `build`, so `build` alone drops a `./result` symlink into the
        // process's cwd. A launchd daemon with no `WorkingDirectory` key
        // inherits cwd `/` — the read-only macOS system volume — so the
        // build succeeds and then dies placing the symlink:
        //     error: creating symlink '/result.tmp-79472-16807'
        //       -> '/nix/store/…-darwin-system-25.11…': Read-only file system
        //
        // MEASURED on ryn 2026-08-02: the closure built correctly and was
        // byte-identical to the generation a manual `nix run .#rebuild` had
        // just activated. Only placing the symlink failed — so this reads as
        // "build failed" in the receipt chain while the build was in fact
        // fine, which is why it survived so long undiagnosed.
        //
        // Passing `--no-link` ourselves is NOT an option: darwin-rebuild's
        // argument parser ends in a catch-all that rejects anything it does
        // not recognize (`unknown option '--no-link'`, exit 1), and it does
        // not forward that flag. Anchoring cwd is the fix, and it belongs
        // HERE rather than in the launchd plist so the daemon is correct
        // under every launcher — plist, `sentinela run` by hand, a test
        // harness — instead of only the one plist we happen to ship.
        self.anchor_activation(&mut cmd);
        // ── ★ DETACH: THE SWITCH OUTLIVES US ON PURPOSE ──────────────────
        // We are a launchd job, and the activation we spawn will reach
        // nix-darwin's "setting up launchd services" step, which for a
        // generation that changes OUR OWN plist does:
        //     launchctl unload <our plist>   # kills this job's process tree
        //     cp -f <new plist> ...          # never reached
        //     launchctl load -w <new plist>  # never reached
        // As a CHILD of that job, darwin-rebuild is killed mid-activation —
        // so the machine is left half-switched, the plist is never
        // replaced, and the daemon is never re-bootstrapped. It stays down
        // silently until someone runs `launchctl bootstrap` by hand.
        //
        // OBSERVED on ryn 2026-08-02: stderr ends abruptly at
        // "user defaults..." — the step immediately before launchd
        // services — with 15 `daemon started` entries recording the
        // restart loop that produced. sentinela could never deploy a
        // generation that updated sentinela.
        //
        // Its own process group takes the child out of the tree launchd
        // reaps, so the activation runs to completion and the new plist is
        // installed even though we die partway through. We lose only the
        // receipt for that tick: the next start re-probes, sees the rev is
        // still not the last ACTIVATED one, and converges again — this
        // time without a plist change, so it survives and attests. One
        // extra cycle, self-healing, instead of a wedged loop.
        //
        // (Both the cwd anchor above and this detach live in
        // `anchor_activation`, shared with `rollback_to`: a rollback is an
        // activation too, and one that restores an older plist hits exactly
        // the same self-unload.)

        // ── ★ CAPTURE TO A FILE, NEVER A PIPE — `output()` DEADLOCKS HERE ─
        // `Command::output()` reads stdout/stderr to EOF and only then
        // reaps. EOF arrives when the LAST holder of the write end closes
        // it — not when our direct child exits. Combined with the
        // `process_group(0)` above, that is a permanent hang: darwin-rebuild
        // spawns grandchildren (nix, the activation scripts) which inherit
        // the pipe, and detaching means they routinely outlive it. The
        // direct child exits, becomes a zombie we never reap because we are
        // still in the read, and `poll()` waits for an EOF that no longer
        // has anyone to deliver it. There is no timeout anywhere in
        // `output()`, so the tick never ends: no receipt, no cooldown, no
        // retry, and a heartbeat frozen at `in_flight` forever.
        //
        // DIAGNOSED on cid 2026-08-04 from a live `sample(1)` of the wedged
        // daemon:
        //     Sentinela::tick → run_rebuild → Command::output
        //       → read_output → poll
        // with the direct child a zombie and zero nix build activity. It
        // reads exactly like a slow build from the outside, which is why it
        // survived: the operator-visible signal — "building, in_flight" —
        // is identical to health.
        //
        // A file has no EOF contract to wait on. `wait()` returns when the
        // direct child exits, no matter how many descendants still hold the
        // descriptor, and a grandchild appending afterwards is harmless. The
        // capture also keeps the failure text, which plain inheritance
        // (writing straight to the daemon log) would have cost us.
        // A build has mutated nothing, so a hung one is killed outright. A
        // switch may be mid-activation, where killing is the damage — see
        // `OnTimeout`.
        let (timeout, on_timeout) = match verb {
            "switch" => self.activation_bound(),
            _ => (
                std::time::Duration::from_secs(self.cfg.build_timeout_seconds),
                OnTimeout::KillGroup,
            ),
        };
        // ── ★ AN ABSENT REBUILD BINARY IS `ToolMissing`, NOT `BuildFailed` ──
        // `BoundedRun::run` ends in `cmd.spawn()?`
        // (`tsunagu-0.1.4/src/exec.rs:178`), so a rebuild tool that is not on
        // disk arrives here as an ordinary `io::Error` with
        // `ErrorKind::NotFound`. Collapsing that into `BuildFailed` is exactly
        // the defect `exec_err` was written for on 2026-08-05 — it was applied
        // to the four `git` sites and NOT to this one, which is the site the
        // daemon exists to drive. A structural fault would have been retried
        // on the cooldown cadence forever, indistinguishable in the receipt
        // chain from a red HEAD.
        //
        // The split must stay narrow: `OnTimeout` returns `ErrorKind::TimedOut`
        // through this same `Result`, and a hang IS a build failure — it must
        // keep feeding the cooldown + `land_last_good_after_failures` machinery
        // rather than being relabelled a broken installation.
        // ── ★ SILENCE IS THE ONLY SIGNAL THAT SEPARATES STUCK FROM SLOW ──
        // The deadline above is generous by design, and a wedge exploits
        // exactly that: it costs the FULL bound to notice, every tick.
        // Measured on cid 2026-08-11 — four ticks, 5400s each, while the tree
        // was provably idle (zero /nix/store writes, no nix process, a `jq`
        // holding at 89 minutes for an EOF nothing would send). The wedge sat
        // inside `darwin-rebuild`'s own `nix build --json … | jq -r` command
        // substitution, a level BELOW anything handed to BoundedRun — so it
        // can only be detected here, never prevented.
        //
        // Only the build verb gets it. A `switch` is `OnTimeout::Abandon`
        // precisely because it may be mid-activation, and a silence-kill is
        // still a kill — the one place where killing is the damage.
        let silence = std::time::Duration::from_secs(self.cfg.build_silence_seconds);
        // Bound to a local: the builder borrows this path, and splitting the
        // chain across `let`s (below) means the temporary would otherwise die
        // at the end of this statement while still borrowed.
        let capture_path = self.rebuild_capture_path(verb);
        let run = BoundedRun::new(&capture_path)
            .timeout(timeout)
            .on_timeout(on_timeout);
        let run = if verb == "switch" || silence.is_zero() {
            run
        } else {
            run.silent_after(silence)
        };
        // The stronger signal: nix reports its own failures with an `error:`
        // line, so a rebuild that has printed one and then stopped moving is
        // wedged, not slow. Same switch-verb exclusion and for the same
        // reason — a silence-kill mid-activation is the damage.
        let err_quiet = std::time::Duration::from_secs(self.cfg.build_error_quiet_seconds);
        let run = if verb == "switch" || err_quiet.is_zero() {
            run
        } else {
            run.error_wedge("error:", err_quiet)
        };
        run.run(cmd)
            .map_err(|e| {
                exec_err(self.cfg.rebuild_binary(), &e, |msg| {
                    Self::rebuild_err(verb, msg)
                })
            })
    }

    /// Anchor an activating subprocess: a writable cwd and its own process
    /// group. See the two ★ blocks in [`Self::run_rebuild_ref`] for why each
    /// is load-bearing. Shared by the switch and the rollback, which are the
    /// two activations this daemon starts.
    fn anchor_activation(&self, cmd: &mut Command) {
        cmd.current_dir(self.rebuild_cwd());
        cmd.process_group(0);
    }

    /// The bound every activation runs under: the switch deadline, and
    /// `Abandon` rather than a kill — a half-activated machine is worse than
    /// a slow one, for a rollback exactly as for a switch.
    fn activation_bound(&self) -> (std::time::Duration, OnTimeout) {
        (
            std::time::Duration::from_secs(self.cfg.switch_timeout_seconds),
            OnTimeout::Abandon,
        )
    }

    /// Where one rebuild's merged output is captured. Per-verb rather than
    /// per-run: the file is consumed and deleted at the end of the call, and
    /// a stable name means a crash leaves exactly one inspectable artifact
    /// instead of accumulating them in the state dir forever.
    /// Where one git invocation's output is captured — one file, reused,
    /// because these are short and only the last failure is interesting.
    fn git_capture_path(&self) -> PathBuf {
        Path::new(&self.cfg.state_dir).join("git.out")
    }

    /// Run a git command under the SAME bound the rebuild already uses.
    ///
    /// ── ★ THE TICK WAS BOUNDED EVERYWHERE EXCEPT ITS NETWORK CALLS ──
    /// `run_rebuild` has driven `BoundedRun` since 0.1.10, and the receipt
    /// above this impl block says the primitive was lifted into
    /// `tsunagu::exec` precisely so "a fix reaches the fleet instead of one
    /// daemon". These four git call sites — `ls-remote` in `probe_head`,
    /// and the `fetch` + two `merge-base`/`rev-parse` calls in the ancestry
    /// check — were left on a bare `Command::output()`, which has no
    /// deadline anywhere in it.
    ///
    /// `ls-remote` and `fetch` talk to the NETWORK. A stalled transfer
    /// there wedges the tick with no receipt, no cooldown and no retry —
    /// the same permanent wedge `build_timeout_seconds` was added to
    /// prevent, arriving by the one path in the tick that had no bound.
    /// git's own `http.lowSpeedLimit` is unset by default, so nothing
    /// underneath was catching it either.
    ///
    /// `OnTimeout::KillGroup`: git mutates nothing we depend on here
    /// (`ls-remote` is a read; `fetch` writes only the throwaway mirror),
    /// so a hung one is killed outright — the opposite of a mid-activation
    /// switch, which is why that one is `Abandon`.
    ///
    /// Doctrine: theory/RECONCILER-LIVENESS.md (P1) · theory/BALIZA.md 0b.
    fn run_git(&self, cmd: Command, err: fn(String) -> EnvError) -> Result<Output, EnvError> {
        let capture = self.git_capture_path();
        // `separate_streams` is load-bearing, not a preference: tsunagu's
        // DEFAULT capture is merged, and it delivers the merged tail in
        // `Output::stderr` with `stdout` left EMPTY. `probe_head` parses
        // `out.stdout` for the ls-remote line, so the merged mode would have
        // silently broken head probing while every call still "succeeded" —
        // the reason tsunagu 0.1.5 added the mode at all ("the merged-only
        // contract excluded most of the fleet"). Hence the 0.1.4 -> 0.1.5
        // bump that ships with this change.
        let mut run = BoundedRun::new(&capture).separate_streams();
        if self.cfg.git_timeout_seconds > 0 {
            run = run
                .timeout(std::time::Duration::from_secs(self.cfg.git_timeout_seconds))
                .on_timeout(OnTimeout::KillGroup);
        }
        run.run(cmd).map_err(|e| exec_err("git", &e, err))
    }

    fn rebuild_capture_path(&self, verb: &str) -> PathBuf {
        Path::new(&self.cfg.state_dir).join(format!("rebuild-{verb}.out"))
    }

    /// The verb's error constructor — `switch` and `build` failures are
    /// distinct outcomes and must not be collapsed.
    fn rebuild_err(verb: &str, msg: String) -> EnvError {
        match verb {
            "switch" => EnvError::SwitchFailed(msg),
            _ => EnvError::BuildFailed(msg),
        }
    }
}

// ── ★ THE BOUNDED-SUBPROCESS PRIMITIVE NOW LIVES IN tsunagu ──────────
// `OnTimeout`, `run_captured`, the process-GROUP kill and the tail bound
// were authored here, but nothing about them is sentinela-specific: six
// pleme-io components shell out to something slow with no bound (forge,
// kindling, fleet, gen, sui, and this). They are now
// `tsunagu::exec::BoundedRun`, and this file is consumer #1 rather than
// the owner — so a fix reaches the fleet instead of one daemon.
//
// tsunagu was already the daemon-lifecycle library and already
// feature-gates axum so CLI consumers can take it, which is why the
// primitive went there rather than into a new repo.
//
// Doctrine: theory/RECONCILER-LIVENESS.md (P1).

impl GitopsEnv for RealEnv {
    fn probe_head(&self) -> Result<Option<Rev>, EnvError> {
        let url = self.probe_url();
        let refspec = ["refs/heads/", self.cfg.rev_probe.branch.as_str()].concat();
        let out = self.run_git({ let mut c = Command::new("git");
            c.arg("ls-remote")
            .arg(&url)
            .arg(&refspec);
            self.apply_git_auth(&mut c);c }, EnvError::ProbeFailed)?;
        if !out.status.success() {
            return Err(EnvError::ProbeFailed(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            ));
        }
        let stdout = String::from_utf8_lossy(&out.stdout);
        Ok(parse_ls_remote(&stdout))
    }

    fn is_ancestor(&self, ancestor: &Rev, descendant: &Rev) -> Result<bool, EnvError> {
        // ── ★ ANSWERED FROM A LOCAL MIRROR, FAIL-CLOSED THROUGHOUT ────────
        // `git ls-remote` cannot answer ancestry — it returns ref tips, not
        // history — so this keeps a bare mirror under the state dir and asks
        // `merge-base --is-ancestor` there. The mirror is a cache, never a
        // source of truth: it is re-fetched every call, because a stale
        // mirror answering "not an ancestor" merely defers (safe) while a
        // stale mirror answering "ancestor" would activate on a fact we did
        // not verify — so the failure directions are deliberately unequal.
        //
        // EVERY exit that is not a definite yes is a no. An unanswerable
        // question must read as "do not activate", never as "probably fine":
        // the whole point of the caller is that it is about to relax the
        // strictest safety rule the loop has.
        let mirror = self.sync_mirror()?;

        // `--is-ancestor` is exit-code-only: 0 = yes, 1 = no, anything else
        // (including a rev this mirror has never heard of) is an ERROR and
        // must not be read as either answer.
        let out = self.run_git({ let mut c = Command::new("git");
            c.arg("--git-dir")
            .arg(&mirror)
            .arg("merge-base")
            .arg("--is-ancestor")
            .arg(ancestor.as_str())
            .arg(descendant.as_str());
            // The mirror is a PROMISOR remote (`--filter=blob:none` sets
            // `promisor = true` — confirmed in ryn's mirror config), so a
            // walk here may lazily fetch a missing object. This was the one
            // git call without auth, and it used to work by accident: the
            // credential was embedded in the stored remote URL. Now that the
            // URL is clean, an unauthenticated lazy fetch against a private
            // repo would exit non-0/1 → AncestryFailed → both starvation
            // escapes down, silently.
            //
            // Tier-honest: I could not construct a case that actually
            // lazy-fetches (`--is-ancestor` walks commits, and blob:none
            // keeps every commit and tree), so this is a guard against an
            // INFERRED path, not an observed one. It costs one env var.
            self.apply_git_auth(&mut c);c }, EnvError::AncestryFailed)?;
        match out.status.code() {
            Some(0) => Ok(true),
            Some(1) => Ok(false),
            _ => Err(EnvError::AncestryFailed(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            )),
        }
    }

    fn build(&self, rev: &Rev) -> Result<(), EnvError> {
        // Through the driver seam, not `run_rebuild` directly: this is the
        // one axis an in-process sui driver replaces, and everything else in
        // this impl (probe, chain, generation read) stays shared.
        let driver = self.driver()?;
        let flake_ref = self.flake_ref(rev);
        if !driver.reports_progress() {
            return driver.build(&flake_ref);
        }
        // M3: republish the in-flight pulse as each derivation lands, so
        // "which drv is it on, and when did it last advance" is answerable
        // without waiting for the tick to resolve. Progress reporting is
        // best-effort by contract — a heartbeat write that fails costs a
        // progress update, never the build.
        let mut sink = |p: BuildProgress| {
            let beat = Heartbeat {
                at_unix_ms: p.at_unix_ms,
                outcome: "building".to_owned(),
                phase: sentinela_core::Phase::InFlight,
                head_rev: Some(rev.clone()),
                poll_seconds: self.cfg.poll_seconds,
                budget_seconds: None,
                in_flight: Some(p),
                verification: None,
            };
            let _ = self.write_heartbeat(&beat);
        };
        driver.build_streaming(&flake_ref, &mut sink)
    }

    fn switch(&self, rev: &Rev) -> Result<Generation, EnvError> {
        // ── ★ THE MACHINE-WIDE REBUILD LOCK, TAKEN ONLY FOR THE SWITCH ──
        // An operator `fleet rebuild` holds `/tmp/fleet-rebuild.lock` for
        // its whole build+switch, so a daemon switch and an operator switch
        // must serialize: two concurrent activations raced on sops-nix's
        // `/run/secrets.d/<generation>/` cleanup (the receipt fleet's lock
        // documents). Fail-fast on contention — the FSM defers the tick and
        // retries on its bounded cadence instead of this process blocking.
        //
        // HONEST RESIDUAL: the flock dies with us. If the launchd job is
        // killed mid-switch (its own plist changing, the one path where
        // `run_rebuild` detaches the child), the lock drops while the
        // detached activation is still running — a window an operator switch
        // could race. Rare (only on plist-changing generations), and the
        // next tick re-converges; documented rather than engineered around,
        // because fixing it would require holding the lock in a child we
        // deliberately orphan.
        let _lock = self.switch_guard()?;
        self.driver()?.switch(&self.flake_ref(rev))?;
        // Read the new generation from the system profile symlink; a
        // parse miss is non-fatal (the switch succeeded) — record 0.
        Ok(current_generation().unwrap_or(Generation(0)))
    }

    fn load_chain(&self) -> Result<ReceiptChain, EnvError> {
        // Canonical path first, then the legacy one. A node upgrading across
        // this change MUST keep its chain: an empty chain reads as "never
        // deployed" — the startup banner reports a freshly-enrolled node, and
        // the failure/deferral streaks the starvation escapes count on reset to
        // zero. Losing it would not merely lose history, it would change what
        // the daemon does next.
        for path in [self.receipts_path(), self.legacy_receipts_path()] {
            match std::fs::read_to_string(&path) {
                Ok(s) => {
                    return serde_yaml::from_str(&s)
                        .map_err(|e| EnvError::ReceiptIo(e.to_string()));
                }
                Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
                Err(e) => return Err(EnvError::ReceiptIo(e.to_string())),
            }
        }
        Ok(ReceiptChain::new())
    }

    fn persist_chain(&self, chain: &ReceiptChain) -> Result<(), EnvError> {
        let path = self.receipts_path();
        let body = serde_yaml::to_string(chain).map_err(|e| EnvError::ReceiptIo(e.to_string()))?;
        // Atomic: write a temp sibling then rename, so a crash never
        // leaves a half-written chain. (The heartbeat's own tmp below keeps
        // `.json.tmp` — that file genuinely IS JSON.)
        let tmp = path.with_extension("yaml.tmp");
        std::fs::write(&tmp, body.as_bytes()).map_err(|e| EnvError::ReceiptIo(e.to_string()))?;
        std::fs::rename(&tmp, &path).map_err(|e| EnvError::ReceiptIo(e.to_string()))?;
        Ok(())
    }

    fn now_unix_ms(&self) -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| u64::try_from(d.as_millis()).unwrap_or(u64::MAX))
            .unwrap_or(0)
    }

    fn write_heartbeat(&self, beat: &Heartbeat) -> Result<(), EnvError> {
        let path = self.heartbeat_path();
        let body =
            serde_json::to_string_pretty(beat).map_err(|e| EnvError::HeartbeatIo(e.to_string()))?;
        // Same atomic write-then-rename as the chain: a reader must never
        // catch a half-written pulse and conclude the loop is broken.
        let tmp = path.with_extension("json.tmp");
        std::fs::write(&tmp, body.as_bytes()).map_err(|e| EnvError::HeartbeatIo(e.to_string()))?;
        std::fs::rename(&tmp, &path).map_err(|e| EnvError::HeartbeatIo(e.to_string()))?;
        Ok(())
    }

    fn current_generation(&self) -> Option<Generation> {
        current_generation()
    }

    fn run_health_probe(&self, probe: &HealthProbe) -> Result<(), String> {
        match &probe.check {
            ProbeCheck::Command {
                argv,
                expect_exit,
                timeout_seconds,
            } => {
                let Some((program, args)) = argv.split_first() else {
                    return Err("empty argv".to_owned());
                };
                // argv, never a shell string — the config layer already
                // refused anything but an absolute program path.
                let mut cmd = Command::new(program);
                cmd.args(args).stdin(Stdio::null());
                // Its own group, so a timed-out probe is killed with every
                // child it spawned rather than leaving them behind.
                cmd.process_group(0);
                let capture = Path::new(&self.cfg.state_dir).join("probe.out");
                let run = BoundedRun::new(&capture)
                    .timeout(std::time::Duration::from_secs(*timeout_seconds))
                    .on_timeout(OnTimeout::KillGroup)
                    .tail_bytes(PROBE_TAIL_BYTES);
                match run.run(cmd) {
                    Ok(out) => {
                        let tail = String::from_utf8_lossy(&out.stderr);
                        match out.status.code() {
                            Some(c) if c == *expect_exit => Ok(()),
                            code => Err(probe_evidence(code, *expect_exit, tail.trim())),
                        }
                    }
                    // A probe that cannot start is a FAILING probe: its
                    // absence may be exactly what the new generation broke.
                    Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                        Err(["not found: ", program].concat())
                    }
                    Err(e) => Err(e.to_string()),
                }
            }
        }
    }

    fn rollback_to(&self, generation: Generation) -> Result<Generation, EnvError> {
        // Same machine-wide lock as a switch: an operator rebuild in flight
        // must not have its activation raced by ours, and a busy lock is a
        // deferral the FSM retries rather than a failure.
        let _lock = self.switch_guard()?;
        let link = generation_link(generation);
        if std::fs::symlink_metadata(&link).is_err() {
            return Err(EnvError::RollbackFailed(
                [&link, " no longer exists — was it garbage-collected?"].concat(),
            ));
        }
        for step in rollback_steps(ActivationPlatform::current(), generation) {
            let Some((program, args)) = step.argv.split_first() else {
                continue;
            };
            let mut cmd = Command::new(program);
            cmd.args(args);
            cmd.envs(step.env.iter().map(|(k, v)| (k.as_str(), v.as_str())));
            self.anchor_activation(&mut cmd);
            let capture = self.rebuild_capture_path("rollback");
            let (timeout, on_timeout) = self.activation_bound();
            let out = BoundedRun::new(&capture)
                .timeout(timeout)
                .on_timeout(on_timeout)
                .run(cmd)
                .map_err(|e| exec_err(program, &e, EnvError::RollbackFailed))?;
            if !out.status.success() {
                return Err(EnvError::RollbackFailed(
                    [program.as_str(), ": ", String::from_utf8_lossy(&out.stderr).trim()].concat(),
                ));
            }
        }
        // Every step exiting 0 is not the proof; the machine running the
        // restored generation is.
        match current_generation() {
            Some(g) if g == generation => Ok(g),
            found => Err(EnvError::RollbackFailed(
                [
                    "the rollback steps succeeded, but generation ",
                    &generation.to_string(),
                    " is not running (found: ",
                    &found.map_or_else(|| "none".to_owned(), |g| g.to_string()),
                    ")",
                ]
                .concat(),
            )),
        }
    }

    fn candidates(&self, since: Option<&Rev>, head: &Rev, limit: usize) -> Result<Vec<Rev>, EnvError> {
        let mirror = self.sync_mirror().map_err(|e| EnvError::HistoryFailed(e.to_string()))?;
        let mut c = Command::new("git");
        c.arg("--git-dir")
            .arg(&mirror)
            .arg("rev-list")
            .arg("--first-parent")
            .arg(["--max-count=", &limit.to_string()].concat());
        match since {
            // `--ancestry-path` keeps only descendants of `since`: nothing
            // older than what this node runs is ever offered, and a HEAD that
            // does not descend from it offers nothing at all.
            Some(since) => {
                c.arg("--ancestry-path")
                    .arg([since.as_str(), "..", head.as_str()].concat());
            }
            None => {
                c.arg(head.as_str());
            }
        }
        self.apply_git_auth(&mut c);
        let out = self.run_git(c, EnvError::HistoryFailed)?;
        if !out.status.success() {
            return Err(EnvError::HistoryFailed(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            ));
        }
        Ok(String::from_utf8_lossy(&out.stdout)
            .lines()
            .filter_map(|l| Rev::parse(l).ok())
            .collect())
    }

    fn check_results(&self, rev: &Rev) -> Result<Vec<CheckResult>, EnvError> {
        let Some((owner, repo)) = github_slug(&self.cfg.rev_probe.git_url) else {
            return Err(EnvError::ChecksUnavailable(
                ["not a github.com repository: ", &self.cfg.rev_probe.git_url].concat(),
            ));
        };
        let base = [
            "https://api.github.com/repos/",
            &owner,
            "/",
            &repo,
            "/commits/",
            rev.as_str(),
        ]
        .concat();
        let runs = self.github_get(&[base.as_str(), "/check-runs?per_page=100"].concat())?;
        let statuses = self.github_get(&[base.as_str(), "/status?per_page=100"].concat())?;
        let mut results = parse_check_runs(&runs);
        results.extend(parse_statuses(&statuses));
        Ok(results)
    }

    fn plan(&self, rev: &Rev) -> Result<PlanVerdict, EnvError> {
        if !self.cfg.planner.enabled {
            return Ok(PlanVerdict::Proceed { key: None });
        }
        let out = self.run_planner(rev, &["plan"], self.cfg.planner.timeout_seconds)?;
        if !out.status.success() {
            return Err(EnvError::PlannerBlind(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            ));
        }
        parse_plan(&String::from_utf8_lossy(&out.stdout))
    }

    fn planning_budget_seconds(&self) -> Option<u64> {
        self.cfg
            .planner
            .enabled
            .then(|| self.cfg.planner.timeout_seconds.max(1))
    }

    fn record_plan(&self, key: &str, outcome: PlanOutcome, why: &str) {
        if !self.cfg.planner.enabled {
            return;
        }
        let word = match outcome {
            PlanOutcome::Activated => "activated",
            PlanOutcome::Failed => "failed",
        };
        let why: String = why.chars().take(400).collect();
        match self.run_planner_with(&["record", key, word, &why], 120) {
            Ok(out) if out.status.success() => {}
            Ok(out) => tracing::warn!(
                stderr = %String::from_utf8_lossy(&out.stderr).trim(),
                "sentinela: kirikae could not record the outcome"
            ),
            Err(e) => tracing::warn!(error = %e, "sentinela: kirikae could not record the outcome"),
        }
    }
}

impl RealEnv {
    fn switch_guard(&self) -> Result<Option<File>, EnvError> {
        let path = Path::new(&self.cfg.switch_lock.path);
        if self.cfg.switch_lock.hold {
            acquire_switch_lock(path).map(Some)
        } else {
            probe_switch_lock(path).map(|()| None)
        }
    }

    fn planner_env(&self, rev: Option<&Rev>) -> Vec<(&'static str, String)> {
        let kind = match self.cfg.rebuild_tool {
            sentinela_config::RebuildTool::DarwinRebuild => "darwin",
            _ => "nixos",
        };
        let mut env = vec![
            ("KIRIKAE_HOST", self.cfg.hostname.clone()),
            ("KIRIKAE_KIND", kind.to_owned()),
            (
                "KIRIKAE_HISTORY",
                Path::new(&self.cfg.state_dir)
                    .join("kirikae.jsonl")
                    .to_string_lossy()
                    .into_owned(),
            ),
            (
                "KIRIKAE_BACKOFF_BASE_S",
                self.cfg.planner.backoff_base_seconds.to_string(),
            ),
            (
                "KIRIKAE_BACKOFF_CAP_S",
                self.cfg.planner.backoff_cap_seconds.to_string(),
            ),
        ];
        if let Some(rev) = rev {
            env.push((
                "KIRIKAE_FLAKE",
                [self.cfg.flake_url.as_str(), "/", rev.as_str()].concat(),
            ));
        }
        env
    }

    fn run_planner(&self, rev: &Rev, args: &[&str], timeout_seconds: u64) -> Result<Output, EnvError> {
        self.run_planner_env(self.planner_env(Some(rev)), args, timeout_seconds)
    }

    fn run_planner_with(&self, args: &[&str], timeout_seconds: u64) -> Result<Output, EnvError> {
        self.run_planner_env(self.planner_env(None), args, timeout_seconds)
    }

    fn run_planner_env(
        &self,
        env: Vec<(&'static str, String)>,
        args: &[&str],
        timeout_seconds: u64,
    ) -> Result<Output, EnvError> {
        let mut cmd = Command::new(&self.cfg.planner.command);
        cmd.args(args).current_dir(self.rebuild_cwd());
        for (k, v) in env {
            cmd.env(k, v);
        }
        let capture = Path::new(&self.cfg.state_dir).join("kirikae.out");
        let mut run = BoundedRun::new(&capture).separate_streams();
        if timeout_seconds > 0 {
            run = run
                .timeout(std::time::Duration::from_secs(timeout_seconds))
                .on_timeout(OnTimeout::KillGroup);
        }
        run.run(cmd)
            .map_err(|e| exec_err(&self.cfg.planner.command, &e, EnvError::PlannerBlind))
    }
}

fn parse_plan(stdout: &str) -> Result<PlanVerdict, EnvError> {
    let line = stdout
        .lines()
        .rev()
        .find(|l| l.trim_start().starts_with('{'))
        .ok_or_else(|| EnvError::PlannerBlind(["no plan in: ", stdout.trim()].concat()))?;
    let v: serde_json::Value =
        serde_json::from_str(line).map_err(|e| EnvError::PlannerBlind(e.to_string()))?;
    let key = v.get("key").and_then(serde_json::Value::as_str).map(str::to_owned);
    match v.get("action").and_then(serde_json::Value::as_str) {
        Some("hold") => Ok(PlanVerdict::Hold {
            why: v
                .get("why")
                .and_then(serde_json::Value::as_str)
                .unwrap_or("held")
                .to_owned(),
            until_unix_ms: v.get("until_ms").and_then(serde_json::Value::as_u64).unwrap_or(0),
        }),
        Some(_) => Ok(PlanVerdict::Proceed { key }),
        None => Err(EnvError::PlannerBlind(["a plan with no action: ", line].concat())),
    }
}

impl RealEnv {
    /// GET one GitHub REST resource as JSON.
    ///
    /// curl, no shell, and the token never in argv: the request's headers
    /// travel as a curl config on stdin (`--config -`). A non-200 answer is
    /// [`EnvError::ChecksUnavailable`] naming the status, so a rejected token
    /// (401) or a token without the Checks / Commit statuses read permission
    /// (403) reads as blind, never as "no checks".
    fn github_get(&self, url: &str) -> Result<serde_json::Value, EnvError> {
        let mut config = String::from("header = \"Accept: application/vnd.github+json\"\n");
        if let Some(token) = self.probe_token() {
            config.push_str("header = \"Authorization: Bearer ");
            config.push_str(&token);
            config.push_str("\"\n");
            scrub(token);
        }
        let mut child = Command::new("curl")
            .args(["-sS", "-m", "20", "--config", "-", "-w", "\n%{http_code}", url])
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| exec_err("curl", &e, EnvError::ChecksUnavailable))?;
        if let Some(mut stdin) = child.stdin.take() {
            let _ = stdin.write_all(config.as_bytes());
        }
        scrub(config);
        let out = child
            .wait_with_output()
            .map_err(|e| EnvError::ChecksUnavailable(e.to_string()))?;
        let text = String::from_utf8_lossy(&out.stdout);
        let (body, code) = text.rsplit_once('\n').unwrap_or(("", text.as_ref()));
        forge_answer(code.trim(), body, String::from_utf8_lossy(&out.stderr).trim())
    }
}

/// Turn one GitHub answer into JSON or the reason it is not one.
fn forge_answer(code: &str, body: &str, stderr: &str) -> Result<serde_json::Value, EnvError> {
    match code {
        "200" => serde_json::from_str(body).map_err(|e| {
            EnvError::ChecksUnavailable(["unreadable answer from GitHub: ", &e.to_string()].concat())
        }),
        "000" | "" => Err(EnvError::ChecksUnavailable(
            ["GitHub unreachable: ", stderr].concat(),
        )),
        "401" => Err(EnvError::ChecksUnavailable(
            "GitHub rejected the token (401)".to_owned(),
        )),
        "403" | "404" => Err(EnvError::ChecksUnavailable(
            [
                "GitHub answered ",
                code,
                ": the token cannot read this repository's checks (it needs Checks: read and Commit statuses: read)",
            ]
            .concat(),
        )),
        other => Err(EnvError::ChecksUnavailable(["GitHub answered ", other].concat())),
    }
}

/// `(owner, repo)` of a github.com git URL (`https://github.com/o/r(.git)`).
fn github_slug(git_url: &str) -> Option<(String, String)> {
    let u = Url::parse(git_url).ok()?;
    if u.host_str()? != "github.com" {
        return None;
    }
    let mut segs = u.path_segments()?;
    let owner = segs.next()?.to_owned();
    let repo = segs.next()?.trim_end_matches(".git").to_owned();
    (!owner.is_empty() && !repo.is_empty()).then_some((owner, repo))
}

/// Check runs, the newest run per name (a re-run supersedes the run it
/// repeats). Only a completed `success` is success.
fn parse_check_runs(v: &serde_json::Value) -> Vec<CheckResult> {
    let mut newest: Vec<(u64, CheckResult)> = Vec::new();
    for run in v.get("check_runs").and_then(|r| r.as_array()).into_iter().flatten() {
        let Some(name) = run.get("name").and_then(|n| n.as_str()) else {
            continue;
        };
        let id = run.get("id").and_then(serde_json::Value::as_u64).unwrap_or(0);
        let state = match (
            run.get("status").and_then(|s| s.as_str()),
            run.get("conclusion").and_then(|c| c.as_str()),
        ) {
            (Some("completed"), Some("success")) => CheckState::Success,
            (Some("completed"), _) => CheckState::Failed,
            _ => CheckState::Pending,
        };
        let result = CheckResult {
            name: name.to_owned(),
            state,
        };
        match newest.iter_mut().find(|(_, r)| r.name == name) {
            Some(slot) if slot.0 < id => *slot = (id, result),
            Some(_) => {}
            None => newest.push((id, result)),
        }
    }
    newest.into_iter().map(|(_, r)| r).collect()
}

/// Commit statuses (the combined view: the latest per context).
fn parse_statuses(v: &serde_json::Value) -> Vec<CheckResult> {
    v.get("statuses")
        .and_then(|s| s.as_array())
        .into_iter()
        .flatten()
        .filter_map(|st| {
            let name = st.get("context")?.as_str()?.to_owned();
            let state = match st.get("state")?.as_str()? {
                "success" => CheckState::Success,
                "pending" => CheckState::Pending,
                _ => CheckState::Failed,
            };
            Some(CheckResult { name, state })
        })
        .collect()
}

/// Which activation mechanics a rollback uses. The PLATFORM decides, not the
/// rebuild tool: re-activating a generation that already exists involves no
/// build, and a node driving sui still activates like its OS.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ActivationPlatform {
    Darwin,
    Nixos,
}

impl ActivationPlatform {
    fn current() -> Self {
        if cfg!(target_os = "macos") {
            Self::Darwin
        } else {
            Self::Nixos
        }
    }
}

/// `/nix/var/nix/profiles/system-<N>-link` — the generation's own root.
fn generation_link(generation: Generation) -> String {
    [SYSTEM_PROFILE, "-", &generation.0.to_string(), "-link"].concat()
}

/// The argv sequence that re-activates `generation`, run in order.
///
/// ── ★ EVERY BINARY COMES FROM THE GENERATION BEING RESTORED ─────────────
/// Not from `/run/current-system`: that is the generation that just failed
/// its probation, and whatever broke it may be the very tool a rollback would
/// call. The previous generation is the one known to have worked.
///
/// - **Darwin** — that generation's own `darwin-rebuild --switch-generation N`,
///   which is `darwin-rebuild --rollback` pinned to an exact generation:
///   `nix-env -p system --switch-generation N`, then `<gen>/activate` (with
///   the legacy `activate-user` handling the script already carries). Exact
///   rather than `--rollback`, which means "the generation before the current
///   one" and would be wrong if anything else switched in between.
/// - **NixOS** — what `nixos-rebuild switch --rollback` does, pinned the same
///   way: `nix-env -p system --switch-generation N`, then that generation's
///   `bin/switch-to-configuration switch`.
fn rollback_steps(platform: ActivationPlatform, generation: Generation) -> Vec<RollbackStep> {
    let link = generation_link(generation);
    let n = generation.0.to_string();
    let step = |argv: Vec<String>| RollbackStep { argv, env: Vec::new() };
    match platform {
        ActivationPlatform::Darwin => vec![step(vec![
            [&link, "/sw/bin/darwin-rebuild"].concat(),
            "--switch-generation".to_owned(),
            n,
        ])],
        ActivationPlatform::Nixos => vec![
            step(vec![
                [&link, "/sw/bin/nix-env"].concat(),
                "-p".to_owned(),
                SYSTEM_PROFILE.to_owned(),
                "--switch-generation".to_owned(),
                n,
            ]),
            // ★ NIXOS_NO_CHECK=1: skip `system.preSwitchChecks` for this
            // activation only. The generation being restored already ran here
            // and passed its checks on the way in; a check that guards FORWARD
            // moves (plo's engenho restart gate holds any switch that changes
            // engenho-daemon's unit) would otherwise refuse the one switch that
            // undoes a bad engenho bump, leaving the node on the broken
            // generation in `rollbackFailed`.
            RollbackStep {
                argv: vec![
                    [&link, "/bin/switch-to-configuration"].concat(),
                    "switch".to_owned(),
                ],
                env: vec![("NIXOS_NO_CHECK".to_owned(), "1".to_owned())],
            },
        ],
    }
}

/// One subprocess of a rollback: its argv and the environment it adds.
#[derive(Debug, Clone, PartialEq, Eq)]
struct RollbackStep {
    argv: Vec<String>,
    env: Vec<(String, String)>,
}

/// The generation whose closure RUNS: the profile's own generation when its
/// closure is the running one, else the newest generation that holds the
/// running closure, else `None` (a closure no generation holds is not
/// reported as one).
///
/// `target_of` resolves a generation link to its store path; `running` is
/// `/run/current-system` resolved the same way. Pure so the failed-rollback
/// case (profile flipped, activation failed) is provable without a machine.
fn running_generation(
    profile: Generation,
    running: &str,
    target_of: impl Fn(Generation) -> Option<String>,
    generations: &[Generation],
) -> Option<Generation> {
    if target_of(profile).as_deref() == Some(running) {
        return Some(profile);
    }
    generations
        .iter()
        .copied()
        .filter(|g| target_of(*g).as_deref() == Some(running))
        .max_by_key(|g| g.0)
}

/// A failing probe's evidence: what it exited with, what was expected, and
/// the tail of what it printed.
fn probe_evidence(code: Option<i32>, expected: i32, tail: &str) -> String {
    let status = match code {
        Some(c) => ["exit ", &c.to_string()].concat(),
        None => "killed by a signal".to_owned(),
    };
    let mut e = [&status, " (expected ", &expected.to_string(), ")"].concat();
    if !tail.is_empty() {
        e.push_str(": ");
        e.push_str(tail);
    }
    e
}

// ── pure decision helpers (unit-tested; the impure methods wrap these) ──

/// The full argv (everything after the binary) for one rebuild invocation.
///
/// ── ★ THE TOOL OWNS ITS SHAPE; THIS FUNCTION ONLY COMPOSES IT ───────────
/// `run_rebuild` used to hardcode `cmd.arg(verb)` as the first word, which
/// silently assumed every rebuild tool IS the rebuild command. That is true of
/// `darwin-rebuild` and `nixos-rebuild` and false of `sui`, whose verb lives at
/// `sui system rebuild <verb>`. Lifting the prefix onto
/// [`RebuildTool::argv_prefix`] means a tool with a different shape is
/// *expressible* rather than merely unimplemented — and pulling the whole argv
/// out as a pure function means it is observable, which a `Command`'s argv is
/// not (the same reason `rebuild_cwd`'s test is honest about its scope).
///
/// `extra_rebuild_args` stay LAST, exactly where the old code put them.
fn rebuild_argv(
    tool: sentinela_config::RebuildTool,
    verb: &str,
    flake_ref: &str,
    extra: &[String],
) -> Vec<String> {
    let mut argv: Vec<String> = tool.argv_prefix().iter().map(|w| (*w).to_owned()).collect();
    argv.push(verb.to_owned());
    argv.push("--flake".to_owned());
    argv.push(flake_ref.to_owned());
    argv.extend(extra.iter().cloned());
    argv
}

/// Acquire the machine-wide rebuild lock, fail-fast.
///
/// Returns the locked file — holding it serializes [`GitopsEnv::switch`]
/// against an operator `fleet rebuild` (both sides open the same
/// `/tmp/fleet-rebuild.lock`). Returns [`EnvError::SwitchBusy`] naming the
/// current holder when another process already owns it.
///
/// ── ★ FAIL-FAST ON PURPOSE, NEVER A BLOCKING `lock_exclusive` ──────────
/// Fleet blocks indefinitely here because the waiter is a human operator
/// who wants to know the other party will finish. The daemon is a LOOP: a
/// tick that blocks until an operator's multi-minute rebuild finishes would
/// publish no liveness pulse for the whole hold — the one failure shape
/// this codebase refuses to reintroduce (see `Phase`/`InFlight` in the core
/// and the gate's `STALE_AFTER_POLLS`). So the daemon takes the lock only
/// if it is free, and the FSM turns a busy lock into a bounded deferral
/// (`TickOutcome::SwitchDeferred`) that stands aside and retries.
///
/// The `build` verb deliberately does NOT take this lock: it is pure nix
/// store work (already serialized by the store's own locking), and holding
/// it across a half-hour build would block the operator for no safety gain.
/// Classify a failure to *launch* a subprocess.
///
/// ── ★ ONE CLASSIFIER, NOT A CONDITIONAL AT EVERY EXEC SITE ─────────────
/// `ErrorKind::NotFound` from `Command::output()` means the BINARY does not
/// exist — a structural fault that no retry can clear — while every other
/// `io::Error` is an ordinary runtime failure belonging to whichever variant
/// the caller already uses. Four call sites need that split (the head probe
/// and the three git invocations behind the ancestry check), so it is a
/// function rather than four copies of the same `if`.
///
/// The `fallback` is passed as the caller's own constructor so each site
/// keeps its existing semantics unchanged — only the ENOENT case is lifted
/// out. See [`EnvError::ToolMissing`] for the rio measurement that motivated
/// separating them at all.
fn exec_err(tool: &str, e: &std::io::Error, fallback: impl FnOnce(String) -> EnvError) -> EnvError {
    if e.kind() == std::io::ErrorKind::NotFound {
        EnvError::ToolMissing {
            tool: tool.to_owned(),
        }
    } else {
        fallback(e.to_string())
    }
}

fn acquire_switch_lock(lock_path: &Path) -> Result<File, EnvError> {
    use fs4::fs_std::FileExt;
    let mut file = File::options()
        .create(true)
        .write(true)
        .open(lock_path)
        .map_err(|e| {
            EnvError::SwitchBusy(format!(
                "cannot open rebuild lock at {}: {e}",
                lock_path.display()
            ))
        })?;
    // Cross-user reachability: whoever creates the file first owns it, and
    // the other party still has to open it for WRITE to take an exclusive
    // flock. A default 0644 would hand the first creator a permanent
    // monopoly — the root daemon creates it, the operator's rebuild then
    // dies on EACCES instead of waiting. Best-effort: a pre-existing file
    // owned by the other user cannot be chmod'd by us, and that is fine —
    // it is already 0666 from its own creation. Never fatal.
    let _ = std::fs::set_permissions(lock_path, std::fs::Permissions::from_mode(0o666));
    if FileExt::try_lock_exclusive(&file).is_err() {
        // Name the holder so a log line (and, on the operator side, fleet's
        // "Another rebuild is already in progress (…)" waiter) can tell a
        // live peer from a wedged one.
        let holder = std::fs::read_to_string(lock_path)
            .map(|h| h.trim().to_owned())
            .ok()
            .filter(|h| !h.is_empty())
            .unwrap_or_else(|| "unknown".to_owned());
        return Err(EnvError::SwitchBusy(holder));
    }
    // Stamp our identity for the next waiter — including a waiting
    // operator, who should read "the daemon owns the machine right now".
    let holder = format!("pid {} · sentinela", std::process::id());
    let _ = file.set_len(0);
    let _ = file.write_all(holder.as_bytes());
    Ok(file)
}

fn probe_switch_lock(lock_path: &Path) -> Result<(), EnvError> {
    use fs4::fs_std::FileExt;
    let file = match File::open(lock_path) {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),
        Err(e) => {
            return Err(EnvError::SwitchBusy(format!(
                "cannot read the activation lock at {}: {e}",
                lock_path.display()
            )));
        }
    };
    if FileExt::try_lock_exclusive(&file).is_err() {
        let holder = std::fs::read_to_string(lock_path)
            .map(|h| h.trim().to_owned())
            .ok()
            .filter(|h| !h.is_empty())
            .unwrap_or_else(|| ["an activation holds ", &lock_path.display().to_string()].concat());
        return Err(EnvError::SwitchBusy(holder));
    }
    let _ = FileExt::unlock(&file);
    Ok(())
}

/// Standard-alphabet base64, no line wrapping.
///
/// Hand-rolled rather than taking the `base64` crate: this is ~20 lines used
/// at exactly one call site, and a new dependency here costs a `gen build`
/// regeneration plus the D2 freshness tie on every consumer.
fn base64_std(input: &[u8]) -> String {
    const T: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
    for chunk in input.chunks(3) {
        let b0 = chunk[0] as u32;
        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
        let n = (b0 << 16) | (b1 << 8) | b2;
        out.push(T[(n >> 18) as usize & 63] as char);
        out.push(T[(n >> 12) as usize & 63] as char);
        out.push(if chunk.len() > 1 {
            T[(n >> 6) as usize & 63] as char
        } else {
            '='
        });
        out.push(if chunk.len() > 2 {
            T[n as usize & 63] as char
        } else {
            '='
        });
    }
    out
}

/// Best-effort overwrite of a `String`'s bytes before it is dropped.
///
/// Deliberately NOT called zeroization: without `zeroize`'s compiler fences
/// this can be optimised away, and the allocator may already have copied the
/// bytes. It is a cheap reduction in exposure window, and it is labelled as
/// such rather than as a guarantee.
fn scrub(mut s: String) {
    // SAFETY-free: operate on the String's own buffer through safe APIs.
    let len = s.len();
    s.clear();
    s.reserve(len);
    for _ in 0..len {
        s.push('\0');
    }
    drop(s);
}

/// The first sha of `git ls-remote` output — the resolved HEAD, or `None`
/// when the output is empty (fail-closed at the FSM).
fn parse_ls_remote(stdout: &str) -> Option<Rev> {
    let line = stdout.lines().next()?;
    let sha = line.split_whitespace().next()?;
    Rev::parse(sha).ok()
}

/// Parse a system-profile symlink filename (`system-<N>-link`) into a
/// generation number.
fn parse_generation(link_name: &str) -> Option<Generation> {
    link_name
        .strip_prefix("system-")?
        .strip_suffix("-link")?
        .parse::<u64>()
        .ok()
        .map(Generation)
}

/// The current darwin generation from the live system profile symlink.
fn current_generation() -> Option<Generation> {
    let target = std::fs::read_link(SYSTEM_PROFILE).ok()?;
    let name = target.file_name()?.to_str()?;
    let profile = parse_generation(name)?;
    match ActivationPlatform::current() {
        ActivationPlatform::Darwin => Some(profile),
        // ── ★ ON NIXOS, THE GENERATION THAT RUNS, NOT THE ONE THE PROFILE
        // NAMES. A rollback flips the profile before it activates, so after a
        // failed activation the profile names the previous generation while
        // the bad closure still runs; read from the profile, the next round
        // would attest a rollback that never happened.
        ActivationPlatform::Nixos => {
            let canon = |p: &str| {
                std::fs::canonicalize(p)
                    .ok()
                    .map(|t| t.to_string_lossy().into_owned())
            };
            let running = canon(RUNNING_SYSTEM)?;
            let dir = Path::new(SYSTEM_PROFILE).parent()?;
            let generations: Vec<Generation> = std::fs::read_dir(dir)
                .ok()?
                .filter_map(|e| e.ok()?.file_name().to_str().and_then(parse_generation))
                .collect();
            running_generation(
                profile,
                &running,
                |g| canon(&generation_link(g)),
                &generations,
            )
        }
    }
}

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

    /// A config whose probe points at the fleet's real repo, with `token`
    /// written to a scratch file when `Some`.
    ///
    /// The file is real rather than mocked because `probe_token` reads it,
    /// and a mock there would test the mock rather than the read.
    fn cfg_with_token(token: Option<&str>) -> SentinelaConfig {
        // ── ★ ONE SCRATCH FILE PER CALL, NOT PER (pid, token) ─────────────
        // The first version keyed the path on pid + token text, so the two
        // tests that both ask for "TKN" wrote the SAME file. `fs::write`
        // truncates before writing, so a concurrent reader saw a zero-length
        // file, `probe_token` read it as empty and returned None, and the
        // auth assertions failed — intermittently, only under parallelism,
        // and only once the test count grew enough to change scheduling.
        //
        // A shared mutable fixture path is the same defect class as the
        // production bug this file is full of; a per-call counter removes it
        // rather than serializing around it.
        static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
        let token_file = token.map(|t| {
            let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
            let p = std::env::temp_dir().join(
                [
                    "sentinela-test-token-",
                    &std::process::id().to_string(),
                    "-",
                    &n.to_string(),
                ]
                .concat(),
            );
            std::fs::write(&p, [t, "\n"].concat()).expect("write scratch token");
            p.to_string_lossy().into_owned()
        });
        SentinelaConfig {
            rev_probe: sentinela_config::RevProbeConfig {
                git_url: "https://github.com/pleme-io/nix.git".to_owned(),
                branch: "main".to_owned(),
                token_file,
            },
            ..SentinelaConfig::default()
        }
    }

    // ── ★ THE TWO TESTS THAT USED TO PIN THE LEAK AS CORRECT ─────────────
    // `inject_token_builds_basic_auth_url` asserted, as the expected value,
    // the exact string that ended up world-readable in the mirror's config:
    //
    //     "https://x-access-token:TKN@github.com/pleme-io/nix"
    //
    // A green test asserting the defect is worse than no test — it converts
    // the leak from an oversight into a specified behaviour, and any fix
    // reads as a regression. Both are replaced by their inverse.

    #[test]
    fn the_probe_url_never_carries_a_credential() {
        let cfg = cfg_with_token(Some("TKN"));
        let env = RealEnv::new(cfg);
        let url = env.probe_url();
        assert_eq!(
            url, "https://github.com/pleme-io/nix.git",
            "the URL must be byte-identical to the configured one"
        );
        assert!(!url.contains("x-access-token"), "no basic-auth userinfo");
        assert!(!url.contains("TKN"), "the token must not reach the URL");
        assert!(!url.contains('@'), "no userinfo separator at all");
    }

    #[test]
    fn auth_travels_by_env_not_argv_and_the_url_stays_clean() {
        let cfg = cfg_with_token(Some("TKN"));
        let env = RealEnv::new(cfg);
        let mut c = Command::new("git");
        c.arg("ls-remote").arg(env.probe_url());
        env.apply_git_auth(&mut c);

        // argv is world-readable via `ps` on every tick — nothing secret here.
        let argv: Vec<String> = std::iter::once(c.get_program())
            .chain(c.get_args())
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            !argv.iter().any(|a| a.contains("TKN")),
            "the token must never appear in argv, got {argv:?}"
        );

        // …and it must actually be applied, or this is a vacuous pass.
        let envs: Vec<(String, Option<String>)> = c
            .get_envs()
            .map(|(k, v)| {
                (
                    k.to_string_lossy().into_owned(),
                    v.map(|v| v.to_string_lossy().into_owned()),
                )
            })
            .collect();
        let get = |key: &str| {
            envs.iter()
                .find(|(k, _)| k == key)
                .and_then(|(_, v)| v.clone())
        };
        assert_eq!(get("GIT_CONFIG_COUNT").as_deref(), Some("1"));
        assert_eq!(
            get("GIT_CONFIG_KEY_0").as_deref(),
            Some("http.extraHeader")
        );
        // base64("x-access-token:TKN")
        assert_eq!(
            get("GIT_CONFIG_VALUE_0").as_deref(),
            Some("Authorization: Basic eC1hY2Nlc3MtdG9rZW46VEtO"),
            "Basic, not Bearer: github's git plane 401s on Bearer even with a \
             valid token (measured 2026-08-17)"
        );
    }

    #[test]
    fn no_token_configured_means_no_auth_env_at_all() {
        let env = RealEnv::new(cfg_with_token(None));
        let mut c = Command::new("git");
        env.apply_git_auth(&mut c);
        assert_eq!(
            c.get_envs().count(),
            0,
            "an unauthenticated probe must not set a half-formed auth config"
        );
    }

    #[test]
    fn base64_matches_known_vectors() {
        // RFC 4648 §10 plus the exact string this crate encodes.
        assert_eq!(base64_std(b""), "");
        assert_eq!(base64_std(b"f"), "Zg==");
        assert_eq!(base64_std(b"fo"), "Zm8=");
        assert_eq!(base64_std(b"foo"), "Zm9v");
        assert_eq!(base64_std(b"foob"), "Zm9vYg==");
        assert_eq!(base64_std(b"fooba"), "Zm9vYmE=");
        assert_eq!(base64_std(b"foobar"), "Zm9vYmFy");
        assert_eq!(base64_std(b"x-access-token:TKN"), "eC1hY2Nlc3MtdG9rZW46VEtO");
    }

    #[test]
    fn parse_ls_remote_takes_the_first_sha() {
        let out = "9f1423abcdef0123456789abcdef0123456789ab\trefs/heads/main\n";
        assert_eq!(
            parse_ls_remote(out).unwrap().as_str(),
            "9f1423abcdef0123456789abcdef0123456789ab"
        );
    }

    #[test]
    fn parse_ls_remote_empty_is_none() {
        assert!(parse_ls_remote("").is_none());
        assert!(parse_ls_remote("\n").is_none());
    }

    #[test]
    fn parse_ls_remote_rejects_garbage_sha() {
        assert!(parse_ls_remote("not-a-sha\trefs/heads/main\n").is_none());
    }

    #[test]
    fn parse_generation_reads_the_profile_name() {
        assert_eq!(parse_generation("system-42-link"), Some(Generation(42)));
        assert_eq!(parse_generation("system-1-link"), Some(Generation(1)));
    }

    #[test]
    fn parse_generation_rejects_non_profile_names() {
        assert_eq!(parse_generation("system-link"), None);
        assert_eq!(parse_generation("42"), None);
        assert_eq!(parse_generation("system-abc-link"), None);
    }

    #[test]
    fn a_probed_activation_lock_defers_while_held_and_is_never_kept() {
        use fs4::fs_std::FileExt;
        let dir = std::env::temp_dir().join(format!("sentinela-probe-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("activation.lock");
        assert_eq!(probe_switch_lock(&path), Ok(()));
        std::fs::write(&path, "").unwrap();
        let holder = File::options().write(true).open(&path).unwrap();
        FileExt::lock_exclusive(&holder).unwrap();
        assert!(matches!(probe_switch_lock(&path), Err(EnvError::SwitchBusy(_))));
        FileExt::unlock(&holder).unwrap();
        assert_eq!(probe_switch_lock(&path), Ok(()));
        let next = File::options().write(true).open(&path).unwrap();
        assert!(FileExt::try_lock_exclusive(&next).is_ok());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn the_switch_lock_holds_by_default_and_probes_when_configured() {
        let env = RealEnv::new(SentinelaConfig::default());
        assert!(env.cfg.switch_lock.hold);
        assert_eq!(env.cfg.switch_lock.path, REBUILD_LOCK_PATH);
        let dir = std::env::temp_dir().join(format!("sentinela-guard-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let probe = RealEnv::new(SentinelaConfig {
            switch_lock: sentinela_config::SwitchLockConfig {
                path: dir.join("absent.lock").to_string_lossy().into_owned(),
                hold: false,
            },
            ..SentinelaConfig::default()
        });
        assert!(probe.switch_guard().unwrap().is_none());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_plan_is_read_from_kirikaes_json() {
        let hold = parse_plan(
            "{\"action\":\"hold\",\"key\":\"/nix/store/a\",\"until_ms\":65000,\"why\":\"2 failed attempt(s)\"}\n",
        )
        .unwrap();
        assert_eq!(
            hold,
            PlanVerdict::Hold {
                why: "2 failed attempt(s)".to_owned(),
                until_unix_ms: 65_000
            }
        );
        assert_eq!(
            parse_plan("blue: noise\n{\"action\":\"switch\",\"key\":\"/nix/store/b\"}").unwrap(),
            PlanVerdict::Proceed {
                key: Some("/nix/store/b".to_owned())
            }
        );
        assert_eq!(
            parse_plan("{\"action\":\"refuse\",\"key\":null}").unwrap(),
            PlanVerdict::Proceed { key: None }
        );
        assert!(matches!(parse_plan(""), Err(EnvError::PlannerBlind(_))));
        assert!(matches!(parse_plan("{\"why\":\"x\"}"), Err(EnvError::PlannerBlind(_))));
    }

    #[test]
    fn the_planner_is_off_unless_configured_and_names_the_pinned_flake() {
        let env = RealEnv::new(SentinelaConfig::default());
        assert!(!env.cfg.planner.enabled);
        let r = Rev::parse(&"a".repeat(40)).unwrap();
        assert_eq!(env.plan(&r).unwrap(), PlanVerdict::Proceed { key: None });
        let on = RealEnv::new(SentinelaConfig {
            flake_url: "github:pleme-io/nix".to_owned(),
            hostname: "ryn".to_owned(),
            state_dir: "/var/log/pleme-gitops".to_owned(),
            ..SentinelaConfig::default()
        });
        let vars = on.planner_env(Some(&r));
        let get = |k: &str| vars.iter().find(|(n, _)| *n == k).map(|(_, v)| v.clone());
        assert_eq!(get("KIRIKAE_FLAKE"), Some(["github:pleme-io/nix/", &"a".repeat(40)].concat()));
        assert_eq!(get("KIRIKAE_HOST"), Some("ryn".to_owned()));
        assert_eq!(get("KIRIKAE_KIND"), Some("darwin".to_owned()));
        assert_eq!(get("KIRIKAE_HISTORY"), Some("/var/log/pleme-gitops/kirikae.jsonl".to_owned()));
        assert_eq!(get("KIRIKAE_BACKOFF_BASE_S"), Some("300".to_owned()));
        assert_eq!(on.planner_env(None).iter().find(|(n, _)| *n == "KIRIKAE_FLAKE"), None);
    }

    #[test]
    fn flake_ref_pins_the_rev() {
        let cfg = SentinelaConfig {
            flake_url: "github:pleme-io/nix".to_owned(),
            hostname: "ryn".to_owned(),
            ..SentinelaConfig::default()
        };
        let env = RealEnv::new(cfg);
        let rev = Rev::parse("0123456789abcdef0123456789abcdef01234567").unwrap();
        assert_eq!(
            env.flake_ref(&rev),
            "github:pleme-io/nix/0123456789abcdef0123456789abcdef01234567#ryn"
        );
    }

    #[test]
    fn rebuild_cwd_is_the_state_dir_never_the_inherited_root() {
        // `darwin-rebuild build` writes a `./result` symlink into its cwd,
        // and a launchd daemon inherits cwd `/`, which is read-only on
        // macOS. The rebuild therefore has to be anchored to a directory we
        // know is writable — the state dir we already own.
        //
        // HONEST SCOPE: this pins the helper, not the `Command` wiring.
        // Deleting the `cmd.current_dir(...)` call in `run_rebuild`
        // would still pass, because a `Command`'s cwd is not observable
        // without spawning `darwin-rebuild` for real. Tier: only-mitigated.
        let cfg = SentinelaConfig {
            state_dir: "/var/log/pleme-gitops".to_owned(),
            ..SentinelaConfig::default()
        };
        let env = RealEnv::new(cfg);
        assert_eq!(env.rebuild_cwd(), Path::new("/var/log/pleme-gitops"));
        assert_ne!(
            env.rebuild_cwd(),
            Path::new("/"),
            "cwd `/` is the read-only system volume — the bug this guards"
        );
    }

    // ── the machine-wide rebuild lock ────────────────────────────────

    #[test]
    fn the_rebuild_lock_path_is_the_same_absolute_path_fleet_uses() {
        // THE coordination contract. Sentinela's switch serializes against
        // an operator `fleet rebuild` ONLY if both open the same file.
        // Fleet's constant is `/tmp/fleet-rebuild.lock` — absolute and
        // machine-wide, because macOS's per-user `$TMPDIR` makes
        // `temp_dir()` serialize nothing (the ryn 2026-08-02 lesson). If
        // either side drifts from this string, the activation race the lock
        // exists to close silently returns. Pinned verbatim, not
        // constructed.
        assert_eq!(REBUILD_LOCK_PATH, "/tmp/fleet-rebuild.lock");
    }

    #[test]
    fn a_held_lock_reports_its_holder() {
        let _fork_free = fork_free();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        let _first = acquire_switch_lock(&path).expect("first acquisition");
        let err = acquire_switch_lock(&path).expect_err("a held lock must defer");
        let expected = format!("pid {} · sentinela", std::process::id());
        assert_eq!(
            err,
            EnvError::SwitchBusy(expected),
            "the holder stamp written by the first acquisition must be read back"
        );
    }

    #[test]
    fn an_uncontended_lock_is_acquired_and_released_on_drop() {
        let _fork_free = fork_free();
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        {
            let _g = acquire_switch_lock(&path).expect("first acquisition");
            assert!(
                acquire_switch_lock(&path).is_err(),
                "the lock must be held while the guard is alive"
            );
        }
        acquire_switch_lock(&path).expect("the lock must release when the guard drops");
    }

    #[test]
    fn the_lock_file_is_group_and_other_writable() {
        let _fork_free = fork_free();
        // Cross-user flock needs a 0666 file: the daemon (root) and the
        // operator both create it, and whoever comes second must still be
        // able to open it for WRITE to take the exclusive flock.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("lock");
        let _g = acquire_switch_lock(&path).expect("acquire");
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(
            mode, 0o666,
            "a default 0644 would hand the creator a monopoly"
        );
    }

    // ── exec_err: the structural/transient split ────────────────────────
    //
    // These are the regression tests for the rio 2026-08-05 measurement: a
    // missing binary and an unreachable remote were the SAME variant, so
    // the daemon retried an unsatisfiable condition forever while every
    // liveness surface read healthy.

    #[test]
    fn exec_err_maps_enoent_to_tool_missing() {
        let e = std::io::Error::from(std::io::ErrorKind::NotFound);
        let got = exec_err("git", &e, EnvError::ProbeFailed);
        assert_eq!(
            got,
            EnvError::ToolMissing {
                tool: "git".to_owned()
            },
            "ENOENT on exec means the BINARY is absent — a structural fault \
             no retry can clear. Collapsing it into ProbeFailed is what cost \
             a live diagnosis on rio."
        );
    }

    #[test]
    fn exec_err_keeps_the_callers_variant_for_every_other_io_error() {
        // A refused connection is transient and belongs to the caller's own
        // variant — the split must be narrow, or it would relabel ordinary
        // network failures as a broken installation.
        let e = std::io::Error::from(std::io::ErrorKind::ConnectionRefused);
        match exec_err("git", &e, EnvError::ProbeFailed) {
            EnvError::ProbeFailed(msg) => assert!(!msg.is_empty()),
            other => panic!("transient io error must stay ProbeFailed, got {other:?}"),
        }
    }

    #[test]
    fn exec_err_preserves_the_ancestry_variant_too() {
        // Same classifier, different caller: the fallback is the caller's,
        // so the ancestry sites keep failing closed as AncestryFailed.
        let e = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
        match exec_err("git", &e, EnvError::AncestryFailed) {
            EnvError::AncestryFailed(_) => {}
            other => panic!("expected AncestryFailed, got {other:?}"),
        }
        let enoent = std::io::Error::from(std::io::ErrorKind::NotFound);
        assert_eq!(
            exec_err("git", &enoent, EnvError::AncestryFailed),
            EnvError::ToolMissing {
                tool: "git".to_owned()
            },
            "ENOENT outranks the caller's variant at EVERY site"
        );
    }

    // ── the rebuild argv: the tool owns its own shape ───────────────────

    #[test]
    fn rebuild_argv_puts_the_verb_first_for_the_nix_tools() {
        use sentinela_config::RebuildTool;
        let argv = rebuild_argv(
            RebuildTool::DarwinRebuild,
            "switch",
            "github:o/r/abc#h",
            &[],
        );
        assert_eq!(argv, ["switch", "--flake", "github:o/r/abc#h"]);
        let argv = rebuild_argv(RebuildTool::NixosRebuild, "build", "github:o/r/abc#h", &[]);
        assert_eq!(argv, ["build", "--flake", "github:o/r/abc#h"]);
    }

    #[test]
    fn rebuild_argv_prefixes_suis_subcommand_path_before_the_verb() {
        // `sui` is a multi-command CLI: the verb is at `sui system rebuild
        // <verb>`, not argv[1]. If the prefix is dropped, sui parses `switch`
        // as a top-level subcommand and exits on an unknown command — which
        // this daemon would have recorded as a switch FAILURE, forever.
        use sentinela_config::RebuildTool;
        let argv = rebuild_argv(RebuildTool::Sui, "switch", "/srv/nix/abc#h", &[]);
        assert_eq!(
            argv,
            ["system", "rebuild", "switch", "--flake", "/srv/nix/abc#h"]
        );
    }

    #[test]
    fn rebuild_argv_keeps_extra_args_last_for_every_tool() {
        // Position is load-bearing: `extra_rebuild_args` are pass-through
        // flags for the underlying tool and must not land between the
        // subcommand path and the verb.
        use sentinela_config::RebuildTool;
        let extra = vec!["--option".to_owned(), "foo".to_owned()];
        assert_eq!(
            rebuild_argv(RebuildTool::DarwinRebuild, "build", "r#h", &extra),
            ["build", "--flake", "r#h", "--option", "foo"]
        );
        assert_eq!(
            rebuild_argv(RebuildTool::Sui, "build", "r#h", &extra),
            [
                "system", "rebuild", "build", "--flake", "r#h", "--option", "foo"
            ]
        );
    }

    // ── the rebuild site's structural/transient split ───────────────────

    // NOTE: the companion test proving tsunagu really surfaces a failed spawn
    // as `ErrorKind::NotFound` lives in `tests/bounded_run_enoent.rs`, NOT
    // here. It has to actually attempt a spawn, and a fork inside this test
    // binary transiently leaks the `flock` held by the lock tests above into
    // the child — measured 2026-08-05: 19 failures in 25 runs of
    // `an_uncontended_lock_is_acquired_and_released_on_drop`. Cargo runs test
    // binaries serially, so a separate integration binary removes the
    // interference without weakening either assertion.

    #[test]
    fn a_missing_rebuild_tool_is_tool_missing_not_a_build_failure() {
        // The regression test for the hole `exec_err` left open: it was
        // applied to the four `git` sites and not to the rebuild site, so an
        // absent `nixos-rebuild` was retried on the cooldown cadence forever
        // and read, in the receipt chain, exactly like a red HEAD.
        //
        // HONEST SCOPE (same tier as `rebuild_cwd_is_the_state_dir_…`): this
        // pins the CLASSIFIER, not the wiring. Deleting the `exec_err` call in
        // `run_rebuild` would still pass, because reaching it needs a real
        // spawn of an absent rebuild binary, and every `RebuildTool::binary()`
        // is an absolute path that either does not exist on this platform
        // (unstable to assert) or is a tool that must never be executed from a
        // test. Tier: only-mitigated.
        let enoent = std::io::Error::from(std::io::ErrorKind::NotFound);
        for verb in ["build", "switch"] {
            assert_eq!(
                exec_err("/run/current-system/sw/bin/nixos-rebuild", &enoent, |m| {
                    RealEnv::rebuild_err(verb, m)
                }),
                EnvError::ToolMissing {
                    tool: "/run/current-system/sw/bin/nixos-rebuild".to_owned()
                },
                "an absent rebuild tool is structural at EVERY verb"
            );
        }
    }

    #[test]
    fn a_rebuild_that_blew_its_deadline_stays_a_build_or_switch_failure() {
        // The split must be NARROW. `OnTimeout` returns `ErrorKind::TimedOut`
        // through the same `Result`, and a hang must keep feeding the cooldown
        // + `land_last_good_after_failures` machinery — relabelling it a broken
        // installation would disable both starvation escapes.
        let timed_out = std::io::Error::from(std::io::ErrorKind::TimedOut);
        match exec_err(
            "/run/current-system/sw/bin/darwin-rebuild",
            &timed_out,
            |m| RealEnv::rebuild_err("build", m),
        ) {
            EnvError::BuildFailed(_) => {}
            other => panic!("a timeout must stay BuildFailed, got {other:?}"),
        }
        match exec_err(
            "/run/current-system/sw/bin/darwin-rebuild",
            &timed_out,
            |m| RealEnv::rebuild_err("switch", m),
        ) {
            EnvError::SwitchFailed(_) => {}
            other => panic!("a timeout must stay SwitchFailed, got {other:?}"),
        }
    }

    #[test]
    fn tool_missing_names_the_binary_in_its_message() {
        // The whole point is legibility in a log; an opaque message would
        // reproduce the original defect with a new variant name.
        let msg = EnvError::ToolMissing {
            tool: "git".to_owned(),
        }
        .to_string();
        assert!(msg.contains("git"), "message must name the tool: {msg}");
    }

    // ── receipts.yaml migration: the edge is "an existing chain still loads"
    //
    // The chain is hash-linked and drives behaviour (streaks feed the
    // starvation escapes), so a rename that orphans it is worse than the
    // misleading filename it fixes.

    /// Serializes the tests that `flock` against the tests that `fork`.
    ///
    /// ── ★ THE MECHANISM, WHICH THIS REPO ALREADY KNEW ─────────────────────
    /// `flock(2)` is held by the OPEN FILE DESCRIPTION, and a forked child
    /// transiently inherits every descriptor between `fork` and `exec`. So a
    /// test that spawns a real subprocess keeps another test's lock alive past
    /// its guard's `Drop`, and the re-acquisition fails with `EWOULDBLOCK`.
    ///
    /// `tests/bounded_run_enoent.rs` exists as a separate binary for exactly
    /// this reason and documents it in its header (measured on cid
    /// 2026-08-05: 0 failures in 25 runs → 19 in 25 when that test lived
    /// here). Two spawning tests were added to this module afterwards and
    /// missed the lesson. Re-measured 2026-08-17, n=65: lock tests alone
    /// 0/15; lock tests + these two 9/15; everything except these two 0/15 —
    /// necessary and sufficient.
    ///
    /// TIER: this is a MITIGATION, not the isolation the header of
    /// `bounded_run_enoent.rs` calls genuine. The real fix is a `[lib]`
    /// target so these two can move into their own test binary, where cargo's
    /// serial execution isolates them for free. This crate is `[[bin]]`-only
    /// today, so that is a refactor rather than a move.
    /// `pending-fork-isolation: sentinela needs a lib target`
    static FORK_FREE: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Take [`FORK_FREE`], surviving a poisoned mutex — a panic in one test
    /// must not cascade into unrelated failures in the others.
    fn fork_free() -> std::sync::MutexGuard<'static, ()> {
        FORK_FREE
            .lock()
            .unwrap_or_else(std::sync::PoisonError::into_inner)
    }

    #[test]
    fn the_sui_mode_selects_the_driver() {
        let with = |tool: sentinela_config::RebuildTool, mode: sentinela_config::SuiMode| {
            RealEnv::new(SentinelaConfig {
                rebuild_tool: tool,
                sui: sentinela_config::SuiConfig {
                    mode,
                    ..sentinela_config::SuiConfig::default()
                },
                ..SentinelaConfig::default()
            })
        };
        let sub = with(sentinela_config::RebuildTool::Sui, sentinela_config::SuiMode::Subprocess);
        assert_eq!(sub.driver().map(|d| d.name()).ok(), Some("shell"));
        let nix = with(sentinela_config::RebuildTool::NixosRebuild, sentinela_config::SuiMode::Embedded);
        assert_eq!(nix.driver().map(|d| d.name()).ok(), Some("shell"));
        let emb = with(sentinela_config::RebuildTool::Sui, sentinela_config::SuiMode::Embedded);
        if cfg!(feature = "sui-driver") {
            assert_eq!(emb.driver().map(|d| d.name()).ok(), Some("sui"));
        } else {
            assert!(matches!(emb.driver().map(|d| d.name()), Err(EnvError::ToolMissing { .. })));
        }
    }

    fn env_with_state(dir: &std::path::Path) -> RealEnv {
        RealEnv::new(SentinelaConfig {
            state_dir: dir.to_string_lossy().into_owned(),
            ..SentinelaConfig::default()
        })
    }

    /// The regression this bounding pass nearly SHIPPED.
    ///
    /// `run_git` routes every git call through `BoundedRun`, whose DEFAULT
    /// capture is merged — it returns the merged tail in `Output::stderr`
    /// and leaves `stdout` **empty**. `probe_head` parses `out.stdout` for
    /// the `ls-remote` line, so the default mode would have made every
    /// probe return "no head" while every call still reported success: a
    /// silent, total loss of convergence with a green build.
    ///
    /// So `separate_streams()` is load-bearing, and this test pins it by
    /// running a real command with known stdout.
    ///
    /// RED-RUN RECEIPT (2026-08-07): dropping `.separate_streams()` from
    /// `run_git` turns this red with an empty stdout, which is exactly the
    /// silent breakage described above, made loud.
    #[test]
    fn run_git_keeps_stdout_separate_or_probe_head_reads_nothing() {
        let _fork_free = fork_free();
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());

        // `git --version` is the cheapest git invocation that writes a
        // known, non-empty line to stdout and nothing to stderr.
        let out = env
            .run_git(
                {
                    let mut c = std::process::Command::new("git");
                    c.arg("--version");
                    c
                },
                EnvError::ProbeFailed,
            )
            .expect("git --version must run");

        let stdout = String::from_utf8_lossy(&out.stdout);
        assert!(
            stdout.contains("git version"),
            "stdout must survive the bound — probe_head parses it. got stdout={stdout:?}, \
             stderr={:?}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// `0` disables the git bound, matching `build_timeout_seconds` /
    /// `switch_timeout_seconds`, so an operator can restore the
    /// pre-bound behaviour without editing code (★★ MODULARIZE, DON'T
    /// DELETE). Proven by running with the bound off rather than by
    /// reading the branch.
    #[test]
    fn git_timeout_zero_disables_the_bound() {
        let _fork_free = fork_free();
        let d = tempfile::tempdir().unwrap();
        let env = RealEnv::new(SentinelaConfig {
            state_dir: d.path().to_string_lossy().into_owned(),
            git_timeout_seconds: 0,
            ..SentinelaConfig::default()
        });
        let out = env
            .run_git(
                {
                    let mut c = std::process::Command::new("git");
                    c.arg("--version");
                    c
                },
                EnvError::ProbeFailed,
            )
            .expect("the unbounded path must still run the command");
        assert!(String::from_utf8_lossy(&out.stdout).contains("git version"));
    }

    #[test]
    fn the_canonical_receipt_path_is_yaml_because_the_bytes_are_yaml() {
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        assert!(
            env.receipts_path().ends_with("receipts.yaml"),
            "persist_chain serialises with serde_yaml; the name must say so"
        );
    }

    #[test]
    fn a_legacy_receipts_json_chain_still_loads() {
        // THE regression: a node upgrading across the rename keeps its chain.
        // The fixture is the real on-disk shape measured on cid 2026-08-05.
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        std::fs::write(
            env.legacy_receipts_path(),
            "- seq: 0\n  rev: cd136f04e14ea67bae9b53491099c63b88a1d3f6\n  \
             outcome:\n    kind: deferred\n    newer: \
             a891200b72fdef64117de281a232bca0105789c3\n  at_unix_ms: \
             1785645747419\n  prev_hash: null\n",
        )
        .unwrap();
        let chain = env.load_chain().expect("legacy chain must parse");
        assert!(
            !chain.is_empty(),
            "an orphaned chain reads as `never deployed`, which resets the \
             failure/deferral streaks the escapes count on — behaviour, not \
             just history"
        );
    }

    #[test]
    fn the_canonical_path_wins_when_both_exist() {
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        std::fs::write(env.legacy_receipts_path(), "[]\n").unwrap();
        std::fs::write(
            env.receipts_path(),
            "- seq: 7\n  rev: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n  \
             outcome:\n    kind: deferred\n    newer: \
             bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n  at_unix_ms: 1\n  \
             prev_hash: null\n",
        )
        .unwrap();
        let chain = env.load_chain().expect("parses");
        assert!(
            !chain.is_empty(),
            "the migrated file is authoritative once written; the legacy copy \
             is left on disk for the operator, never re-read over the new one"
        );
    }

    /// The rollback re-activates from the RESTORED generation's own tools,
    /// pinned to its exact number — never `/run/current-system`, which is
    /// the generation that just failed.
    #[test]
    fn rollback_steps_use_the_restored_generations_own_tools() {
        let argvs = |p, g| -> Vec<Vec<String>> {
            rollback_steps(p, g).into_iter().map(|s| s.argv).collect()
        };
        assert_eq!(
            argvs(ActivationPlatform::Darwin, Generation(1710)),
            vec![vec![
                "/nix/var/nix/profiles/system-1710-link/sw/bin/darwin-rebuild".to_owned(),
                "--switch-generation".to_owned(),
                "1710".to_owned(),
            ]]
        );
        assert_eq!(
            argvs(ActivationPlatform::Nixos, Generation(88)),
            vec![
                vec![
                    "/nix/var/nix/profiles/system-88-link/sw/bin/nix-env".to_owned(),
                    "-p".to_owned(),
                    "/nix/var/nix/profiles/system".to_owned(),
                    "--switch-generation".to_owned(),
                    "88".to_owned(),
                ],
                vec![
                    "/nix/var/nix/profiles/system-88-link/bin/switch-to-configuration".to_owned(),
                    "switch".to_owned(),
                ],
            ]
        );
        for argvs in [
            argvs(ActivationPlatform::Darwin, Generation(3)),
            argvs(ActivationPlatform::Nixos, Generation(3)),
        ] {
            for argv in argvs {
                assert!(!argv[0].starts_with("/run/current-system"), "{argv:?}");
            }
        }
    }

    /// A NixOS rollback's activation skips the pre-switch checks.
    ///
    /// Measured on plo, 2026-09-30: `system.preSwitchChecks` carries an
    /// engenho restart gate that HOLDS any switch changing engenho-daemon's
    /// unit. A rollback out of a bad engenho bump changes that unit back, so
    /// the gate would refuse the one switch that restores the house, and the
    /// loop would sit in `rollbackFailed` on the broken generation. The
    /// generation being restored already ran on this machine; its checks
    /// guarded the forward move that installed it.
    #[test]
    fn a_nixos_rollback_skips_the_pre_switch_checks_and_only_that_step() {
        let steps = rollback_steps(ActivationPlatform::Nixos, Generation(88));
        let activation = steps.last().expect("an activation step");
        assert_eq!(
            activation.env,
            vec![("NIXOS_NO_CHECK".to_owned(), "1".to_owned())],
            "the switch-to-configuration step must carry NIXOS_NO_CHECK=1"
        );
        assert!(steps[0].env.is_empty(), "the profile flip needs no override");
        for s in rollback_steps(ActivationPlatform::Darwin, Generation(3)) {
            assert!(s.env.is_empty(), "darwin has no pre-switch checks: {s:?}");
        }
    }

    /// Which generation RUNS, not which one the profile names.
    ///
    /// A rollback flips the profile first and activates second. When the
    /// activation fails, the profile already names the previous generation
    /// while the machine still runs the bad one — and a profile-only read then
    /// attests a rollback that never happened.
    #[test]
    fn the_running_generation_is_the_one_whose_closure_runs() {
        let links = |g: Generation| match g.0 {
            87 => Some("/nix/store/aaa-system".to_owned()),
            88 => Some("/nix/store/bbb-system".to_owned()),
            89 => Some("/nix/store/ccc-system".to_owned()),
            _ => None,
        };
        let all = [Generation(87), Generation(88), Generation(89)];
        // The normal case: the profile's generation is what runs.
        assert_eq!(
            running_generation(Generation(89), "/nix/store/ccc-system", links, &all),
            Some(Generation(89))
        );
        // The failed-rollback case: the profile says 88, 89 still runs.
        assert_eq!(
            running_generation(Generation(88), "/nix/store/ccc-system", links, &all),
            Some(Generation(89)),
            "a profile flipped ahead of a failed activation must not read as rolled back"
        );
        // A closure no generation holds (`switch-to-configuration test` of an
        // unregistered build): not measured, so not reported.
        assert_eq!(
            running_generation(Generation(89), "/nix/store/zzz-system", links, &all),
            None
        );
    }

    #[test]
    fn github_slug_reads_owner_and_repo() {
        assert_eq!(
            github_slug("https://github.com/pleme-io/nix"),
            Some(("pleme-io".to_owned(), "nix".to_owned()))
        );
        assert_eq!(
            github_slug("https://github.com/pleme-io/nix.git"),
            Some(("pleme-io".to_owned(), "nix".to_owned()))
        );
        assert_eq!(github_slug("https://gitlab.com/o/r"), None);
    }

    #[test]
    fn check_runs_take_the_newest_run_and_only_success_is_success() {
        let v: serde_json::Value = serde_json::from_str(
            r#"{"check_runs":[
                {"id":1,"name":"gate","status":"completed","conclusion":"failure"},
                {"id":2,"name":"gate","status":"completed","conclusion":"success"},
                {"id":3,"name":"blue","status":"in_progress","conclusion":null},
                {"id":4,"name":"lint","status":"completed","conclusion":"neutral"}
            ]}"#,
        )
        .unwrap();
        let r = parse_check_runs(&v);
        let state = |n: &str| r.iter().find(|c| c.name == n).map(|c| c.state);
        assert_eq!(state("gate"), Some(CheckState::Success), "the re-run supersedes");
        assert_eq!(state("blue"), Some(CheckState::Pending));
        assert_eq!(state("lint"), Some(CheckState::Failed), "neutral is not success");
    }

    #[test]
    fn statuses_map_by_context() {
        let v: serde_json::Value = serde_json::from_str(
            r#"{"statuses":[{"context":"ci/a","state":"success"},{"context":"ci/b","state":"pending"},{"context":"ci/c","state":"error"}]}"#,
        )
        .unwrap();
        let r = parse_statuses(&v);
        assert_eq!(r.len(), 3);
        assert_eq!(r[2].state, CheckState::Failed);
    }

    /// Measured 2026-09-30: the fleet's fine-grained tokens answer 403 for
    /// both endpoints. That must read as blind, naming what is missing.
    #[test]
    fn a_rejected_or_underpowered_token_is_blind_and_says_which() {
        let e = forge_answer("403", "", "").unwrap_err().to_string();
        assert!(e.contains("403") && e.contains("Checks: read"), "{e}");
        let e = forge_answer("401", "", "").unwrap_err().to_string();
        assert!(e.contains("rejected the token"), "{e}");
        let e = forge_answer("000", "", "Could not resolve host").unwrap_err().to_string();
        assert!(e.contains("unreachable") && e.contains("resolve"), "{e}");
        assert!(forge_answer("200", "{}", "").is_ok());
    }

    #[test]
    fn probe_evidence_names_the_status_the_expectation_and_the_output() {
        assert_eq!(
            probe_evidence(Some(1), 0, "tailscaled not running"),
            "exit 1 (expected 0): tailscaled not running"
        );
        assert_eq!(probe_evidence(None, 0, ""), "killed by a signal (expected 0)");
    }

    /// A real probe run: the verdict is the exit status against
    /// `expect_exit`, the evidence carries the output, and a missing binary
    /// is a FAILING probe rather than a skipped one.
    #[test]
    fn a_command_probe_judges_the_exit_status_and_keeps_the_output() {
        let _fork_free = fork_free();
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        let probe = |argv: &[&str], expect_exit| HealthProbe {
            name: "p".to_owned(),
            check: ProbeCheck::Command {
                argv: argv.iter().map(|a| (*a).to_owned()).collect(),
                expect_exit,
                timeout_seconds: 10,
            },
        };
        assert_eq!(env.run_health_probe(&probe(&["/usr/bin/true"], 0)), Ok(()));
        assert_eq!(env.run_health_probe(&probe(&["/usr/bin/false"], 1)), Ok(()), "expect_exit is honoured");
        let e = env
            .run_health_probe(&probe(&["/bin/sh", "-c", "echo no route to host; exit 3"], 0))
            .unwrap_err();
        assert!(e.starts_with("exit 3 (expected 0)"), "{e}");
        assert!(e.contains("no route to host"), "the output tail is the evidence: {e}");
        assert_eq!(
            env.run_health_probe(&probe(&["/nonexistent/probe"], 0)),
            Err("not found: /nonexistent/probe".to_owned())
        );
    }

    /// The timeout is a hard bound, and a timed-out probe fails.
    #[test]
    fn a_probe_that_outlives_its_timeout_fails() {
        let _fork_free = fork_free();
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        let started = std::time::Instant::now();
        let r = env.run_health_probe(&HealthProbe {
            name: "slow".to_owned(),
            check: ProbeCheck::Command {
                argv: vec!["/bin/sleep".to_owned(), "30".to_owned()],
                expect_exit: 0,
                timeout_seconds: 1,
            },
        });
        assert!(r.is_err(), "a hung probe must not pass");
        assert!(started.elapsed() < std::time::Duration::from_secs(10), "and must not wedge the tick");
    }

    #[test]
    fn no_chain_at_either_path_is_an_empty_chain_not_an_error() {
        let d = tempfile::tempdir().unwrap();
        let env = env_with_state(d.path());
        assert!(env.load_chain().expect("absent is not an error").is_empty());
    }
}


/// The subprocess driver — `darwin-rebuild` / `nixos-rebuild` under
/// [`tsunagu::exec::BoundedRun`]. Today's behaviour, unchanged, now behind
/// [`RebuildDriver`] so an in-process sui driver can take its place without
/// touching the probe or the receipt chain.
///
/// ── ★ ITS IRREDUCIBLE HAZARD, STATED WHERE IT LIVES ────────────────────
/// The bounds this driver applies stop at the process it spawns. The rebuild
/// tool then builds `nix build --json … | jq -r` internally, and a wedge in
/// THAT pipeline is invisible to any deadline we set on the outer command —
/// measured on cid 2026-08-11 as four ticks of 5400s each with the tree
/// completely idle. `build_error_quiet_seconds` and `build_silence_seconds`
/// detect it; only removing the subprocess removes it.
pub struct ShellDriver<'a> {
    env: &'a RealEnv,
}

impl RebuildDriver for ShellDriver<'_> {
    fn build(&self, flake_ref: &str) -> Result<(), EnvError> {
        let out = self.env.run_rebuild_ref("build", flake_ref)?;
        if out.status.success() {
            Ok(())
        } else {
            Err(EnvError::BuildFailed(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            ))
        }
    }

    fn switch(&self, flake_ref: &str) -> Result<(), EnvError> {
        let out = self.env.run_rebuild_ref("switch", flake_ref)?;
        if out.status.success() {
            Ok(())
        } else {
            Err(EnvError::SwitchFailed(
                String::from_utf8_lossy(&out.stderr).trim().to_owned(),
            ))
        }
    }

    fn name(&self) -> &'static str {
        "shell"
    }
}

/// The in-process sui driver — M2 of the sui plan.
///
/// ── ★ WHY THIS EXISTS: IT REMOVES THE CLASS, NOT THE SYMPTOM ───────────
/// [`ShellDriver`] spawns a rebuild tool which internally builds
/// `nix build --json … | jq -r '.[0].outputs.out'`. That command substitution
/// is where cid wedged on 2026-08-11: nix errored and exited, a descendant
/// kept the pipe's write end open, and `jq` waited 89 minutes for an EOF that
/// was never coming — a level below anything `BoundedRun` can bound. The two
/// guards added that day (`build_error_quiet_seconds`,
/// `build_silence_seconds`) DETECT it, and detection is all a subprocess
/// driver can ever offer.
///
/// Calling `sui-orchestrate` as a library removes every ingredient: no
/// subprocess, so no pipe, no EOF contract, no `jq`. "Did it error" stops
/// being a scan of captured bytes and becomes a `Result`.
///
/// ── ★ ACTIVATION REMAINS ATOMIC ────────────────────────────────────────
/// `rebuild_native` evaluates, realises the closure, and sets the profile
/// ONCE. sui can realise derivation by derivation internally — that is the
/// per-drv streaming M3 builds on — but the profile flip stays single and
/// total, because that flip is the rollback boundary.
#[cfg(feature = "sui-driver")]
pub struct SuiDriver;

#[cfg(feature = "sui-driver")]
impl SuiDriver {
    /// Run one async orchestrate call to completion.
    ///
    /// A fresh current-thread runtime per call rather than a shared one: a
    /// rebuild is a single long await, so there is no concurrency to schedule,
    /// and a runtime that outlives the call would be state this daemon has to
    /// reason about across ticks.
    fn block_on<F: std::future::Future>(fut: F) -> Result<F::Output, EnvError> {
        tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .map_err(|e| EnvError::BuildFailed(["sui runtime: ", &e.to_string()].concat()))
            .map(|rt| rt.block_on(fut))
    }

    fn orchestrator() -> Result<sui_orchestrate::system::SystemOrchestrator, EnvError> {
        sui_orchestrate::system::SystemOrchestrator::new()
            .map_err(|e| EnvError::BuildFailed(["sui orchestrator: ", &e.to_string()].concat()))
    }
}

#[cfg(feature = "sui-driver")]
impl RebuildDriver for SuiDriver {
    fn build(&self, flake_ref: &str) -> Result<(), EnvError> {
        let orch = Self::orchestrator()?;
        Self::block_on(orch.build_toplevel(flake_ref))?
            .map(|_out_path| ())
            .map_err(|e| EnvError::BuildFailed(e.to_string()))
    }

    fn switch(&self, flake_ref: &str) -> Result<(), EnvError> {
        let orch = Self::orchestrator()?;
        Self::block_on(orch.rebuild_native(flake_ref, sui_orchestrate::system::RebuildAction::Switch))?
            .map(|_result| ())
            .map_err(|e| EnvError::SwitchFailed(e.to_string()))
    }

    fn name(&self) -> &'static str {
        "sui"
    }
}