symforge 11.3.9

SymForge — in-memory code intelligence MCP server for Claude Code, Codex, and Gemini CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
//! Feature 020 V11, T066 — the activation mode machine.
//!
//! `LegacyOpen -> LegacyClosing -> PreventiveV1Open`, monotonic (no reverse
//! edge exists as API), process-wide (one machine per process behind
//! [`ActivationCut::process`]), and non-configurable (no environment or
//! config read can select a mode; the only way a mode changes is the typed
//! transition evidence below). The frozen lane list is T066's own: every
//! tool/resource/prompt query, cache/CCR/retrieval, sidecar/hook, and
//! finalization lane registers before the legacy gate may begin closing.
//!
//! `LegacyClosing` is the drain window from the 028 data model: the legacy
//! gate drains, cache/CCR invalidate, responses finalize. The machine cannot
//! observe a lane's internals, so drain evidence is the CONSUMPTION of that
//! lane's non-Clone [`LaneRegistration`] token by its owner — the one party
//! that can observe its own drain. A premature confirmation (before the
//! drain window opens) consumes the token and refuses, deliberately
//! stranding the machine short of `PreventiveV1Open`: a mis-sequenced
//! bootstrap fails loudly at the cut, never silently half-open.
//!
//! Two claims, recorded separately because they are not the same construction.
//!
//! Mode occupancy is enforced by [`ActivationMode`] (one `u8` behind
//! [`ActivationCut::process`]) and the typed transitions below: the process
//! is in exactly one of `LegacyOpen`, `LegacyClosing`, `PreventiveV1Open`.
//! No reverse edge. `LegacyClosing` is drain-only for the mode machine —
//! [`LaneRegistration`] tokens, not publication.
//!
//! Publication exclusivity is not enforced here. Ingress still answers
//! through [`ProjectRuntimeHandle::data_plane`] → [`crate::live_index::store::SharedIndex`].
//! That leftover door is the D1 mid-cut already recorded at the
//! `ObservationLane` doc and at the `ProjectRuntimeHandle` mid-cut claim.
//! Retiring it is not this pass.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock};

use super::adapters::{AdapterRefusal, execute_plan_with_outcome, plan_admission};
use super::authority::{
    AuthorityRefusal, BindingAuthority, CurrentPublication, MutationGrantInput, ObserverToken,
    SourceRuntime,
};
use super::candidate::{
    CandidateSource, IsolatedCandidate, ProjectArtifactRoot, SourceContentToken, SourceId,
    SourceObservation,
};
use super::capacity::{OwnerIdentity, ProcessCapacityPool};
use super::mutation::{PermitDrainSignal, RefreshTicket, SourceMutationPermit};
use super::observer::{CoalescingAccumulator, ObservationCut, ObserverId, ObserverSlot};
use super::physical_root::{
    PhysicalRootAnchor, PhysicalRootIdentity, PhysicalRootLease, WriteReceipt,
};
use super::process_runtime::{ProcessIndexRuntime, SurfaceKind};
use super::registry::{
    LiveProjectSlot, ProjectKey, ProjectRegistry, RegistryRefusal, RootProtection,
    StatePlacement as AdmissionStatePlacement,
};
use super::supervisor::SourceSupervisor;
use super::transition::{self, TransitionKind};
use crate::domain::index::CatalogPath;
use crate::lifecycle_identity::PublicationIdentity;

/// The closed three-mode machine (frozen T066). Monotonic: the enum has no
/// reverse edge and the type exposes no API that revisits an earlier mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ActivationMode {
    /// Legacy authority serves; V11 lanes register.
    LegacyOpen,
    /// The drain window: nothing new enters the legacy gate, registered
    /// lanes confirm their drains, caches/CCR invalidate, responses finalize.
    LegacyClosing,
    /// The preventive lifecycle is the only live mode.
    PreventiveV1Open,
}

/// The closed lane set from the frozen T066 text: "every tool/resource/prompt
/// query, cache/CCR/retrieval, sidecar/hook, and finalization lane".
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum RegisteredLane {
    ToolQuery,
    ResourceQuery,
    PromptQuery,
    Cache,
    Ccr,
    Retrieval,
    Sidecar,
    Hook,
    Finalization,
}

impl RegisteredLane {
    /// Every lane the cut registers; `begin_closing` refuses while any is
    /// missing, because an unregistered lane is exactly the unmatched
    /// ingress SC-001 forbids.
    pub const ALL: [RegisteredLane; 9] = [
        RegisteredLane::ToolQuery,
        RegisteredLane::ResourceQuery,
        RegisteredLane::PromptQuery,
        RegisteredLane::Cache,
        RegisteredLane::Ccr,
        RegisteredLane::Retrieval,
        RegisteredLane::Sidecar,
        RegisteredLane::Hook,
        RegisteredLane::Finalization,
    ];
}

/// Typed refusals. Every variant is producible by a caller of this module;
/// none is speculative.
#[derive(Debug, PartialEq, Eq)]
pub enum ActivationRefusal {
    /// The lane already holds a registration on this machine.
    LaneAlreadyRegistered(RegisteredLane),
    /// `begin_closing` found lanes that never registered.
    LanesUnregistered(Vec<RegisteredLane>),
    /// `open_preventive` found registered lanes that never confirmed drain.
    LanesUndrained(Vec<RegisteredLane>),
    /// The operation is legal only in `expected`; the machine is in `actual`.
    WrongMode {
        expected: ActivationMode,
        actual: ActivationMode,
    },
    /// The registration token was minted by a different machine instance.
    ForeignRegistration,
}

/// One lane's registration on one machine. Non-Clone: consuming it in
/// [`ActivationCut::confirm_drained`] is the drain evidence, and evidence
/// that could be duplicated would let one drain vouch twice.
#[derive(Debug)]
pub struct LaneRegistration {
    machine: u64,
    lane: RegisteredLane,
}

impl LaneRegistration {
    /// Which lane this registration binds.
    pub fn lane(&self) -> RegisteredLane {
        self.lane
    }
}

#[derive(Debug, Default)]
struct LaneTable {
    registered: BTreeSet<RegisteredLane>,
    drained: BTreeSet<RegisteredLane>,
}

/// The process-wide activation machine. Contract seam
/// `src/index_lifecycle/activation.rs::ActivationCut` in the frozen
/// retirement inventory (hooks, compatibility_aliases categories).
#[derive(Debug)]
pub struct ActivationCut {
    identity: u64,
    mode: AtomicU8,
    lanes: Mutex<LaneTable>,
}

static NEXT_MACHINE_IDENTITY: AtomicU64 = AtomicU64::new(1);
static PROCESS_MACHINE: OnceLock<ActivationCut> = OnceLock::new();

const MODE_LEGACY_OPEN: u8 = 0;
const MODE_LEGACY_CLOSING: u8 = 1;
const MODE_PREVENTIVE_V1_OPEN: u8 = 2;

fn mode_of(raw: u8) -> ActivationMode {
    match raw {
        MODE_LEGACY_OPEN => ActivationMode::LegacyOpen,
        MODE_LEGACY_CLOSING => ActivationMode::LegacyClosing,
        _ => ActivationMode::PreventiveV1Open,
    }
}

impl ActivationCut {
    fn new() -> Self {
        ActivationCut {
            identity: NEXT_MACHINE_IDENTITY.fetch_add(1, Ordering::Relaxed),
            mode: AtomicU8::new(MODE_LEGACY_OPEN),
            lanes: Mutex::new(LaneTable::default()),
        }
    }

    /// The one process-wide machine. Mode selection is non-configurable:
    /// this accessor reads no environment and takes no parameters, and no
    /// other constructor is reachable from production code.
    pub fn process() -> &'static ActivationCut {
        PROCESS_MACHINE.get_or_init(ActivationCut::new)
    }

    /// A fresh machine for in-crate oracles only, so scenario isolation
    /// never leaks through the process singleton.
    #[cfg(all(test, feature = "server"))]
    pub(crate) fn fresh_for_oracles() -> Self {
        ActivationCut::new()
    }

    /// The current mode. Lock-free; safe from any lane.
    pub fn mode(&self) -> ActivationMode {
        mode_of(self.mode.load(Ordering::Acquire))
    }

    /// Register one lane while the legacy gate is still open.
    pub fn register_lane(
        &self,
        lane: RegisteredLane,
    ) -> Result<LaneRegistration, ActivationRefusal> {
        // Mode is checked under the lane lock so `begin_closing` can never
        // race past a registration it did not count.
        let mut table = self.lanes.lock().expect("activation lane lock");
        let actual = self.mode();
        if actual != ActivationMode::LegacyOpen {
            return Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyOpen,
                actual,
            });
        }
        if !table.registered.insert(lane) {
            return Err(ActivationRefusal::LaneAlreadyRegistered(lane));
        }
        Ok(LaneRegistration {
            machine: self.identity,
            lane,
        })
    }

    /// Close the legacy gate and open the drain window. Refuses while any
    /// lane of the closed set has not registered.
    pub fn begin_closing(&self) -> Result<(), ActivationRefusal> {
        let table = self.lanes.lock().expect("activation lane lock");
        let actual = self.mode();
        if actual != ActivationMode::LegacyOpen {
            return Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyOpen,
                actual,
            });
        }
        let missing: Vec<RegisteredLane> = RegisteredLane::ALL
            .iter()
            .copied()
            .filter(|lane| !table.registered.contains(lane))
            .collect();
        if !missing.is_empty() {
            return Err(ActivationRefusal::LanesUnregistered(missing));
        }
        self.mode.store(MODE_LEGACY_CLOSING, Ordering::Release);
        Ok(())
    }

    /// One lane's owner confirms its drain by consuming its registration.
    /// Consumption is unconditional: a refused confirmation (wrong window,
    /// foreign token) deliberately strands the machine short of
    /// `PreventiveV1Open` — see the module doc.
    pub fn confirm_drained(&self, registration: LaneRegistration) -> Result<(), ActivationRefusal> {
        let mut table = self.lanes.lock().expect("activation lane lock");
        // A foreign token is refused before the window check: it says
        // nothing about THIS machine's lanes in any mode.
        if registration.machine != self.identity {
            return Err(ActivationRefusal::ForeignRegistration);
        }
        let actual = self.mode();
        if actual != ActivationMode::LegacyClosing {
            return Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyClosing,
                actual,
            });
        }
        table.drained.insert(registration.lane);
        Ok(())
    }

    /// Open the preventive mode. Refuses while any registered lane has not
    /// confirmed its drain.
    pub fn open_preventive(&self) -> Result<(), ActivationRefusal> {
        let table = self.lanes.lock().expect("activation lane lock");
        let actual = self.mode();
        if actual != ActivationMode::LegacyClosing {
            return Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyClosing,
                actual,
            });
        }
        let undrained: Vec<RegisteredLane> = table
            .registered
            .iter()
            .copied()
            .filter(|lane| !table.drained.contains(lane))
            .collect();
        if !undrained.is_empty() {
            return Err(ActivationRefusal::LanesUndrained(undrained));
        }
        self.mode.store(MODE_PREVENTIVE_V1_OPEN, Ordering::Release);
        Ok(())
    }
}

// ── The write-lane bridge (T064, C2) and observation lane (T029, C3) ───────

/// One project root's live source authority: the bridge the cut's writer
/// lanes acquire mutation permits from, and the observation lane the
/// watcher/facade admissions and background callbacks report through.
///
/// MID-CUT BRIDGING CLAIM, recorded: construction seeds the runtime
/// `Current` on a fresh publication because the V10 data plane it stands
/// beside serves queries today; C4 ties construction to observed bootstrap
/// state. Since C3 every publication carries the ACTIVE observer
/// incarnation's token (the `ObserverId`/`ObserverToken` unification the
/// observer module recorded as T064 work), and every permit return consumes
/// the accumulated observation cut. Neither remaining simplification
/// weakens the write path itself: every write still requires a granted
/// permit, publishes non-`Current` first, and returns to `Current` only
/// through a fresh publication (FR-043).
#[derive(Debug)]
pub struct ProjectSourceAuthority {
    root: PathBuf,
    /// The identity of this root's FIRST lease, presented for project
    /// admission (C4b). Replaced only when the directory object at this
    /// canonical path changes — same path, different physical root mints a
    /// fresh identity via [`project_source_authority`]'s ABA fence.
    admission_root: PhysicalRootIdentity,
    /// Observed physical object when this authority was installed. Compared
    /// on every registry lookup to detect same-path replacement without
    /// rekeying the path convergence map.
    physical_anchor: Option<PhysicalRootAnchor>,
    /// Set when the canonical path vanishes while this authority is cached.
    /// Vanish keep-on-match (Ada A): reappeared anchor == cached → clear
    /// vanish and keep authority. Remint only when observed dev+ino ≠ cached;
    /// path still absent records absent without remint.
    path_absent_pending: AtomicBool,
    inner: Mutex<AuthorityInner>,
    // Separate mutex, strict ordering: lane state is always taken and
    // RELEASED before `inner` is locked (see `reconcile_returned`), so the
    // watcher thread's observations never deadlock against a writer.
    lane: Mutex<ObservationLane>,
}

#[derive(Debug)]
struct AuthorityInner {
    runtime: SourceRuntime,
    lease: Arc<PhysicalRootLease>,
    outstanding: Arc<PermitDrainSignal>,
}

/// The C3 observation lane: one active observer incarnation (watcher or
/// embed facade), the bounded coalescing accumulator, and the per-source
/// supervisor + isolated-candidate pipeline every admission drives —
/// PERMIT-FREE, per the frozen contract (observation never mutates source
/// bytes; it has no business in the mutation lane).
///
/// D1 applies: this is the AUTHORITY plane (`ObservationLane`). The
/// LiveIndex data plane (`ProjectRuntimeHandle::data_plane` → `SharedIndex`)
/// still serves admissions. C5 landed (the `ProjectSourceAuthority` residual).
/// It did not make this lane, nor `ProjectPublicationRoot`,
/// query-visible. The leftover door is this `data_plane` path — the same
/// D1 mid-cut recorded on `ProjectRuntimeHandle`'s `data_plane` naming comment.
/// Retiring it is not this pass.
#[derive(Debug)]
struct ObservationLane {
    slot: ObserverSlot,
    /// The authority-side token paired with the active `ObserverId`.
    active_token: ObserverToken,
    accumulator: CoalescingAccumulator,
    supervisors: BTreeMap<u64, SourceSupervisor>,
    artifact_root: ProjectArtifactRoot,
    pool: Arc<ProcessCapacityPool>,
    owner: OwnerIdentity,
    next_observer: u64,
    next_stamp: u64,
    /// Probe for the wiring oracles: the cut the most recent permit return
    /// consumed.
    last_reconcile_cut: Option<ObservationCut>,
}

/// Bounded distinct pending sources before the accumulator latches the
/// capacity-exhausted full baseline.
const OBSERVATION_ACCUMULATOR_BOUND: usize = 4096;

/// Dark capacity budget for the observation lane's candidate builds. Real
/// derivation payloads (and the C8 conservation oracle) replace this.
/// The dark per-surface observation budget (C7/C8 replace it with a
/// measured value); public so the benchmark receipt records the exact
/// pre-granted capacity vector it ran under.
pub const OBSERVATION_CAPACITY_BYTES: u64 = 1 << 30;

fn observation_source_id(relative: &str) -> u64 {
    use std::hash::{Hash, Hasher};
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    relative.hash(&mut hasher);
    hasher.finish()
}

/// A granted, in-progress write on one project source. Non-Clone; ends by
/// [`WriteAuthority::finish_committed`], [`WriteAuthority::finish_no_side_effect`],
/// or drop — since C3 a drop RECOVERS: the permit drains, the scope latches
/// dirty (the write's outcome is unobserved), and the source returns to
/// `Current` under a full-baseline observation instead of stranding.
#[derive(Debug)]
pub struct WriteAuthority {
    authority: Arc<ProjectSourceAuthority>,
    /// `None` only after a finish path has taken it; `Drop` treats that as
    /// "already terminal, nothing to recover".
    permit: Option<SourceMutationPermit>,
    frozen_publication: PublicationIdentity,
}

impl ProjectSourceAuthority {
    /// The bridge for one project root. See the type doc for the recorded
    /// mid-cut construction claim.
    pub fn for_root(root: &Path) -> Arc<Self> {
        // Dormant while idle: the OS directory handle exists only during a
        // permit cycle (see `PhysicalRootLease::parked`), so an idle root
        // stays user-movable.
        let lease = Arc::new(PhysicalRootLease::take(root).parked());
        let admission_root = lease.identity();
        let binding = BindingAuthority::bind(lease.identity());
        // The seed publication carries the SEED observer incarnation's
        // token — the same identity `active_token` starts on — so even the
        // first publication names a real registration, not an anonymous
        // mint.
        let seed_token = ObserverToken::fresh();
        let publication = CurrentPublication::promote(binding, seed_token);
        let pool = ProcessCapacityPool::new();
        let owner = pool.root(OBSERVATION_CAPACITY_BYTES);
        Arc::new(Self {
            root: root.to_path_buf(),
            admission_root,
            physical_anchor: PhysicalRootAnchor::observe(root),
            path_absent_pending: AtomicBool::new(false),
            inner: Mutex::new(AuthorityInner {
                runtime: SourceRuntime::current(publication),
                lease,
                // Unarmed: reports ended until a permit arms it, which is
                // what lets the first transition treat "no permit ever" as
                // drained rather than as an optional check.
                outstanding: Arc::new(PermitDrainSignal::new()),
            }),
            lane: Mutex::new(ObservationLane {
                slot: ObserverSlot::new(ObserverId(1)),
                active_token: seed_token,
                accumulator: CoalescingAccumulator::new(OBSERVATION_ACCUMULATOR_BOUND),
                supervisors: BTreeMap::new(),
                artifact_root: ProjectArtifactRoot::empty(),
                pool,
                owner,
                next_observer: 1,
                next_stamp: 0,
                last_reconcile_cut: None,
            }),
        })
    }

    /// Register a fresh observer incarnation (watcher (re)start, facade
    /// attach): a drain-before-successor handoff on the slot, a fresh
    /// authority-side token, and the successor's post-barrier full-baseline
    /// obligation latched into the cut stream. Late callbacks holding the
    /// predecessor's id are refused by every observation entry point below.
    pub fn register_observer(&self) -> ObserverId {
        let mut lane = self.lane.lock().expect("observation lane lock");
        lane.next_observer += 1;
        let successor = ObserverId(lane.next_observer);
        lane.slot
            .begin_handoff(successor)
            .expect("registration completes each handoff before returning");
        // The lane consumes cuts at reconcile, so the predecessor never
        // holds undelivered cuts here; deliver anyway so the refusal path
        // stays unreachable by construction, not by luck.
        let _ = lane.slot.deliver_pending();
        let kind = lane
            .slot
            .complete_handoff()
            .expect("predecessor delivered above");
        debug_assert_eq!(
            kind,
            super::observer::CutKind::FullBaseline {
                cause: super::observer::LatchCause::HandoffBarrier
            }
        );
        // Thread the returned obligation into the cut stream (T064).
        lane.accumulator.latch_handoff_barrier();
        lane.active_token = ObserverToken::fresh();
        successor
    }

    /// The observer incarnation currently holding the slot.
    pub fn active_observer(&self) -> ObserverId {
        self.lane
            .lock()
            .expect("observation lane lock")
            .slot
            .active()
    }

    /// Observe one admitted source through the isolated candidate pipeline,
    /// permit-free: supervisor attempt -> delta candidate -> the single
    /// commit point -> accumulator. A stale incarnation is refused — the
    /// late-callback unreachability the frozen contract demands.
    pub fn observe_admission(
        &self,
        observer: ObserverId,
        relative: &str,
    ) -> Result<(), ObserverId> {
        let mut lane = self.lane.lock().expect("observation lane lock");
        if lane.slot.active() != observer {
            return Err(lane.slot.active());
        }
        lane.observe_admission_locked(relative);
        Ok(())
    }

    /// Observe one removal. The dark candidate pipeline carries no removal
    /// payload (recorded bridging simplification): the removal lands as an
    /// accumulator invalidation only.
    pub fn observe_removal(&self, observer: ObserverId, relative: &str) -> Result<(), ObserverId> {
        let mut lane = self.lane.lock().expect("observation lane lock");
        if lane.slot.active() != observer {
            return Err(lane.slot.active());
        }
        lane.next_stamp += 1;
        let stamp = lane.next_stamp;
        lane.accumulator
            .observe(observation_source_id(relative), || stamp);
        Ok(())
    }

    /// Report a lost/overflowed observation stream (watcher overflow):
    /// latches the gap so the next cut is a full baseline.
    pub fn report_gap(&self, observer: ObserverId) -> Result<(), ObserverId> {
        let mut lane = self.lane.lock().expect("observation lane lock");
        if lane.slot.active() != observer {
            return Err(lane.slot.active());
        }
        lane.accumulator.report_gap();
        Ok(())
    }

    /// [`Self::observe_admission`] attributed to the CURRENT incarnation —
    /// the synchronous facade entry (embed `update_file_from_disk`), which
    /// holds no id across time and so cannot be a late callback.
    pub fn observe_admission_active(&self, relative: &str) {
        let mut lane = self.lane.lock().expect("observation lane lock");
        lane.observe_admission_locked(relative);
    }

    /// [`Self::observe_removal`] attributed to the current incarnation.
    pub fn observe_removal_active(&self, relative: &str) {
        let mut lane = self.lane.lock().expect("observation lane lock");
        lane.next_stamp += 1;
        let stamp = lane.next_stamp;
        lane.accumulator
            .observe(observation_source_id(relative), || stamp);
    }

    /// Measurement probe (C8, T069): the observation lane's capacity ledger
    /// as `(charged now, pre-granted, outstanding charges, unknown refunds)`.
    /// Reads the pool's own counters — the probe reports the ledger, never a
    /// cached belief.
    pub fn observation_capacity_ledger(&self) -> (u64, u64, usize, u64) {
        let lane = self.lane.lock().expect("observation lane lock");
        (
            lane.pool.charged(lane.owner),
            OBSERVATION_CAPACITY_BYTES,
            lane.pool.outstanding_charges(lane.owner),
            lane.pool.unknown_refunds(),
        )
    }

    /// Measurement probe (C8, T069): retained observation artifacts as
    /// `(sources, dark retained bytes)`. The dark payload weight is the same
    /// one the candidate pipeline reserves with (one byte per observed
    /// source), so `retained + candidate <= pregranted` is measured in the
    /// pipeline's own units; the sealed artifact machinery replaces the
    /// weight with real bytes when it lands.
    pub fn retained_observation_artifacts(&self) -> (usize, u64) {
        let lane = self.lane.lock().expect("observation lane lock");
        let publication = lane.artifact_root.load();
        (publication.sources.len(), publication.sources.len() as u64)
    }

    /// Wiring-oracle probe: how many observation candidates for `relative`
    /// have reached the single commit point.
    pub fn committed_observations(&self, relative: &str) -> u64 {
        let lane = self.lane.lock().expect("observation lane lock");
        lane.supervisors
            .get(&observation_source_id(relative))
            .map(|supervisor| supervisor.committed_generations())
            .unwrap_or(0)
    }

    /// Wiring-oracle probe: the cut the most recent permit return consumed.
    pub fn last_reconcile_cut(&self) -> Option<ObservationCut> {
        self.lane
            .lock()
            .expect("observation lane lock")
            .last_reconcile_cut
            .clone()
    }

    /// Whether the source is live `Current` (queryable, grantable).
    pub fn is_current(&self) -> bool {
        self.inner
            .lock()
            .expect("project source authority lock")
            .runtime
            .live_publication()
            .is_some()
    }

    /// The live publication identity, when `Current`.
    pub fn current_publication(&self) -> Option<PublicationIdentity> {
        self.inner
            .lock()
            .expect("project source authority lock")
            .runtime
            .live_publication()
            .map(|publication| publication.publication())
    }

    /// The stable admission-root identity this authority presents.
    pub fn admission_root(&self) -> PhysicalRootIdentity {
        self.admission_root
    }

    /// The binding this authority presents for project admission: a fresh
    /// binding identity over the STABLE admission-root identity (see the
    /// field doc), so every open of one canonicalized root can join one
    /// registry occupancy.
    pub fn admission_binding(&self) -> BindingAuthority {
        BindingAuthority::bind(self.admission_root)
    }

    /// Revoke the outgoing lease when the directory object at this path was
    /// physically replaced. Called only from the registry ABA fence.
    fn revoke_for_replacement(&self) {
        let inner = self.inner.lock().expect("project source authority lock");
        inner.lease.revoke();
    }

    /// Record that the canonical path was absent on a registry lookup.
    fn mark_path_absent(&self) {
        self.path_absent_pending.store(true, Ordering::Release);
    }

    /// How many mutation grants this source has ever issued. The wiring
    /// oracles pin routing on this: a write that went through the permit
    /// lane moved the counter; one that bypassed it did not.
    pub fn grants_issued(&self) -> u64 {
        self.inner
            .lock()
            .expect("project source authority lock")
            .runtime
            .grants_issued()
    }

    /// Acquire the single write authority for this source: grant against the
    /// live `Current` publication (which publishes non-`Current` before the
    /// permit exists), then mint the permit pinned to this root's lease.
    pub fn acquire_write(self: &Arc<Self>) -> Result<WriteAuthority, AuthorityRefusal> {
        let mut inner = self.inner.lock().expect("project source authority lock");
        let presented = match inner.runtime.live_publication() {
            Some(publication) => publication.publication(),
            None => {
                return Err(AuthorityRefusal::PhaseNotCurrent {
                    phase: inner.runtime.phase(),
                });
            }
        };
        let grant = inner
            .runtime
            .request_mutation_grant(MutationGrantInput::LiveCurrent(presented))?;
        let frozen_publication = grant.published_non_current().publication();
        let drain = Arc::new(PermitDrainSignal::new());
        // Unpark the dormant lease for exactly this permit cycle. Stored only
        // on a successful grant: a refused grant drops the reopened handle
        // and the authority stays dormant.
        let live_lease = Arc::new(inner.lease.reopened());
        let permit = SourceMutationPermit::grant(grant, live_lease.clone(), drain.clone())?;
        inner.lease = live_lease;
        inner.outstanding = drain;
        Ok(WriteAuthority {
            authority: self.clone(),
            permit: Some(permit),
            frozen_publication,
        })
    }

    /// [`Self::acquire_write`] with bounded patience for a sibling writer:
    /// retries `PhaseNotCurrent` (~2s at 25ms steps) before surfacing the
    /// refusal honestly. C4 replaces cross-lane patience with structural
    /// serialization at bootstrap; until then every writer lane shares this
    /// policy (protocol/edit.rs carries its own identical C2 loop).
    pub fn acquire_write_serialized(self: &Arc<Self>) -> Result<WriteAuthority, AuthorityRefusal> {
        let mut attempts = 0u32;
        loop {
            match self.acquire_write() {
                Ok(write) => return Ok(write),
                Err(refusal @ AuthorityRefusal::PhaseNotCurrent { .. }) => {
                    attempts += 1;
                    if attempts >= 80 {
                        return Err(refusal);
                    }
                    std::thread::sleep(std::time::Duration::from_millis(25));
                }
                Err(refusal) => return Err(refusal),
            }
        }
    }

    /// Return the source to `Current` through a fresh publication after its
    /// permit reached a terminal path: retire the permit, then the sealed
    /// Freeze -> Drain -> Install transition under a fresh lease and binding.
    fn reconcile_returned(
        &self,
        frozen_publication: PublicationIdentity,
        ticket: RefreshTicket,
    ) -> Result<RefreshTicket, AuthorityRefusal> {
        self.return_to_current(frozen_publication)?;
        Ok(ticket)
    }

    /// The shared return path: consume the accumulated observation cut
    /// (lane lock, released before `inner` is taken — the documented lock
    /// order), then retire the permit and apply the sealed transition. The
    /// returning publication carries the ACTIVE observer incarnation's
    /// token.
    fn return_to_current(
        &self,
        frozen_publication: PublicationIdentity,
    ) -> Result<(), AuthorityRefusal> {
        let observer_cut = {
            let mut lane = self.lane.lock().expect("observation lane lock");
            let cut = lane.accumulator.cut();
            lane.last_reconcile_cut = Some(cut);
            lane.active_token
        };
        let mut guard = self.inner.lock().expect("project source authority lock");
        let inner = &mut *guard;
        inner.runtime.retire_permit(frozen_publication);
        let outstanding = inner.outstanding.clone();
        // The incoming lease is stored DORMANT: its capability opens at the
        // next permit cycle's acquire, so the returned-to-`Current` root is
        // immediately user-movable again.
        let new_lease = Arc::new(PhysicalRootLease::take(self.root.as_path()).parked());
        let incoming = BindingAuthority::bind(new_lease.identity());
        let old_lease = inner.lease.clone();
        transition::apply(
            &mut inner.runtime,
            TransitionKind::Reload,
            &old_lease,
            incoming,
            observer_cut,
            &outstanding,
        )?;
        inner.lease = new_lease;
        Ok(())
    }

    /// The C3 re-scout recovery lane: a write authority dropped without a
    /// finish path leaves a write of UNOBSERVED outcome behind. Latch the
    /// scope dirty (the next cut is a full baseline over the possibly
    /// half-written scope), then return the source to `Current` exactly
    /// like a terminal return. Failure here leaves the source non-`Current`
    /// and observable as such — recovery is attempted, never asserted.
    fn recover_stranded(
        &self,
        frozen_publication: PublicationIdentity,
    ) -> Result<(), AuthorityRefusal> {
        self.lane
            .lock()
            .expect("observation lane lock")
            .accumulator
            .latch_scope_dirty();
        self.return_to_current(frozen_publication)
    }
}

impl ObservationLane {
    /// One admitted source through the pipeline: supervisor attempt ->
    /// isolated delta candidate (dark stamp payload) -> the single commit
    /// point -> accumulator. A refused candidate (capacity, drift,
    /// supersession) latches a gap: the CHANGE is retained as a
    /// full-baseline obligation, never dropped.
    fn observe_admission_locked(&mut self, relative: &str) {
        let source_raw = observation_source_id(relative);
        self.next_stamp += 1;
        let stamp = self.next_stamp;
        let supervisor = self.supervisors.entry(source_raw).or_default();
        let attempt = supervisor.begin_attempt();
        let source = SourceId(source_raw);
        let expected = self
            .artifact_root
            .load()
            .sources
            .get(&source)
            .map(|artifacts| artifacts.token);
        let candidate = IsolatedCandidate::prepare_delta(
            &self.pool,
            self.owner,
            &attempt,
            CandidateSource {
                id: source,
                observation: SourceObservation::Content {
                    path: CatalogPath {
                        public_id: relative.to_string(),
                        normalized_utf8: Some(relative.to_string()),
                    },
                    token: SourceContentToken(stamp),
                    bytes: 1,
                },
            },
            expected,
            |_| stamp,
        );
        let committed = match candidate {
            Ok(candidate) => candidate.commit(&self.artifact_root).is_ok(),
            Err(_) => false,
        };
        if committed {
            self.accumulator.observe(source_raw, || stamp);
        } else {
            self.accumulator.report_gap();
        }
    }
}

impl WriteAuthority {
    /// Write one path beneath the authorized root. The first write begins the
    /// permit's side effect; later writes continue it (a batch is one
    /// authority, many receipts).
    pub fn write(
        &mut self,
        relative: &Path,
        contents: &[u8],
    ) -> Result<WriteReceipt, AuthorityRefusal> {
        let permit = self
            .permit
            .as_mut()
            .expect("permit lives until a finish path");
        match permit.start_side_effect() {
            Ok(()) => {}
            // Continuing the batch: the side effect is already in flight.
            Err(AuthorityRefusal::SideEffectAlreadyInFlight) => {}
            Err(refusal) => return Err(refusal),
        }
        permit.replace_beneath(relative, contents)
    }

    /// Begin a DELEGATED side effect: the caller is about to run its own
    /// contract-pinned durability protocol (curation policy lane) beneath
    /// this authority's root. The permit goes in flight FIRST, so a protocol
    /// failure drops through the re-scout recovery lane as a write of
    /// unobserved outcome, never as a claimed no-op.
    pub fn begin_delegated(&mut self) -> Result<(), AuthorityRefusal> {
        let permit = self
            .permit
            .as_mut()
            .expect("permit lives until a finish path");
        match permit.start_side_effect() {
            Ok(()) | Err(AuthorityRefusal::SideEffectAlreadyInFlight) => Ok(()),
            Err(refusal) => Err(refusal),
        }
    }

    /// Attest the delegated protocol's outcome: the pinned lease re-reads
    /// `relative` and mints a receipt only if it observes exactly the
    /// authorized post-image. `Ok(None)` is a mismatch — no receipt exists,
    /// and dropping this authority is the caller's honest terminal (the
    /// recovery lane returns the source to `Current` scope-dirty).
    pub fn attest_delegated(
        &mut self,
        relative: &Path,
        expected: &[u8],
    ) -> Result<Option<WriteReceipt>, AuthorityRefusal> {
        self.permit
            .as_mut()
            .expect("permit lives until a finish path")
            .attest_delegated_beneath(relative, expected)
    }

    /// Commit the observed side effect and return the source to `Current`
    /// through a fresh publication: retire the permit, then apply the sealed
    /// Freeze -> Drain -> Install transition under a fresh root lease and
    /// binding. A commit REFUSAL leaves the permit in place, so the drop
    /// recovery below still returns the source to `Current`.
    pub fn finish_committed(
        mut self,
        receipt: WriteReceipt,
    ) -> Result<RefreshTicket, AuthorityRefusal> {
        let ticket = self
            .permit
            .as_mut()
            .expect("permit lives until a finish path")
            .commit(receipt)?;
        drop(self.permit.take());
        self.authority
            .clone()
            .reconcile_returned(self.frozen_publication, ticket)
    }

    /// Terminate with the permit's own observation that nothing was written
    /// through its lease (the permit never began a side effect), and return
    /// the source to `Current` through a fresh publication — FR-043 applies
    /// to no-ops too. Refuses once a side effect has begun (the drop
    /// recovery then owns the return).
    pub fn finish_no_side_effect(mut self) -> Result<RefreshTicket, AuthorityRefusal> {
        let ticket = self
            .permit
            .as_mut()
            .expect("permit lives until a finish path")
            .no_side_effect()?;
        drop(self.permit.take());
        self.authority
            .clone()
            .reconcile_returned(self.frozen_publication, ticket)
    }
}

impl Drop for WriteAuthority {
    /// The re-scout recovery lane (C3): a write authority dropped while its
    /// permit is still live drains the permit and returns the source to
    /// `Current` under a scope-dirty full-baseline observation. A finish
    /// path already took the permit, so its drop is a no-op here.
    fn drop(&mut self) {
        if let Some(permit) = self.permit.take() {
            drop(permit);
            let _ = self.authority.recover_stranded(self.frozen_publication);
        }
    }
}

static PROJECT_AUTHORITIES: OnceLock<Mutex<HashMap<PathBuf, Arc<ProjectSourceAuthority>>>> =
    OnceLock::new();

/// The process registry of per-root write authorities. C2's self-provisioning
/// seam for the writer lanes; C4 moves ownership into runtime bootstrap.
pub fn project_source_authority(root: &Path) -> Arc<ProjectSourceAuthority> {
    // One authority per PHYSICAL root: spelling variants (canonical, \\?\
    // extended, relative) must converge on one lease and one serialization
    // point, or two writer lanes on the same repository would not contend.
    // Canonicalization failure (root vanished mid-call) falls back to the
    // literal key rather than refusing here: the acquire path surfaces the
    // real I/O failure with its own evidence.
    let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let registry = PROJECT_AUTHORITIES.get_or_init(|| Mutex::new(HashMap::new()));
    let mut map = registry.lock().expect("project authority registry lock");
    if let Some(existing) = map.get(&key) {
        match PhysicalRootAnchor::observe(&key) {
            None => existing.mark_path_absent(),
            Some(observed) if existing.physical_anchor == Some(observed) => {
                existing.path_absent_pending.store(false, Ordering::Release);
            }
            Some(_) => {
                existing.revoke_for_replacement();
                map.remove(&key);
            }
        }
    }
    map.entry(key.clone())
        .or_insert_with(|| ProjectSourceAuthority::for_root(&key))
        .clone()
}

/// Whether the registry recorded a path-vanish since the authority was installed.
/// Read before [`project_source_authority`] clears the bit on anchor match.
pub(crate) fn project_source_authority_path_vanish_pending(root: &Path) -> bool {
    let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let registry = PROJECT_AUTHORITIES.get_or_init(|| Mutex::new(HashMap::new()));
    let map = registry.lock().expect("project authority registry lock");
    map.get(&key)
        .is_some_and(|existing| existing.path_absent_pending.load(Ordering::Acquire))
}

/// Evict a cached authority when the physical root anchor changed. Called
/// only from index reload so child-file writes do not false-positive.
pub(crate) fn evict_project_source_authority_if_anchor_changed(
    root: &Path,
    admitted: Option<PhysicalRootAnchor>,
) {
    let current = PhysicalRootAnchor::observe(root);
    if admitted.is_some() && admitted != current {
        let key = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
        let registry = PROJECT_AUTHORITIES.get_or_init(|| Mutex::new(HashMap::new()));
        let mut map = registry.lock().expect("project authority registry lock");
        if let Some(existing) = map.get(&key) {
            existing.revoke_for_replacement();
        }
        map.remove(&key);
    }
}

// ── The per-project runtime handle (D1, C4) ────────────────────────────────

/// D1 (Feature 020 Slice 4, T030, C4): the per-project runtime handle — the
/// ONLY holder of a project's `SharedIndex` data plane in daemon, protocol,
/// server, sidecar, or embed state. The frozen publication_roots census
/// retires every bare `index: SharedIndex` field; replacing those field
/// types with this handle drives the compiler over every touch site, and
/// the two accessors below are the ENUMERABLE door the C4 neck
/// acquisitions progressively narrow — a `data_plane()` call site is a
/// member of the rerouting set by construction, not by grep luck.
///
/// Recorded ownership claim: the accessors expose the V10 data plane
/// unchanged, so moving a field onto this handle is behavior-preserving.
///
/// `acquire` is the typed branch -- it refuses when the carried admission
/// slot is no longer the live occupancy of its key. It is NOT how the
/// dispatch necks acquire in general: only a surface that binds WITH a slot
/// can be gated at all, and the untyped `data_plane` / `shared` doors carry
/// the rest. That is the state of the call sites, enumerable through the two
/// accessors above; nothing here promises it changes.
// No Debug derive: `SharedIndexHandle` itself carries none.
#[derive(Clone)]
pub struct ProjectRuntimeHandle {
    // Named `data_plane`, not `index`: the frozen census derivation counts
    // every `index: SharedIndex(Handle)` field as a V10 publication root,
    // and this — the sole authorized holder — is the replacement, not a root.
    data_plane: crate::live_index::store::SharedIndex,
    // The admission slot this runtime serves under (C4c). Carried ONLY where
    // a surface can retire slots — the daemon, whose eviction/retarget stop
    // path revokes them. Stdio/serve admissions are process-lifetime with no
    // stop path, so a carried slot there would feed a refusal branch nothing
    // can emit; those handles stay `None` until C5's typed bootstrap.
    admission: Option<Arc<super::registry::LiveProjectSlot>>,
}

impl ProjectRuntimeHandle {
    /// Bind a handle over the data plane it owns, outside any admission
    /// (stdio/serve/standalone-sidecar surfaces, transient test indexes).
    pub fn bind(index: crate::live_index::store::SharedIndex) -> Self {
        Self {
            data_plane: index,
            admission: None,
        }
    }

    /// Bind a handle over the data plane it owns, under the admission slot
    /// the surface's [`admit_project`] call installed for it.
    pub fn bind_admitted(
        index: crate::live_index::store::SharedIndex,
        admission: Arc<super::registry::LiveProjectSlot>,
    ) -> Self {
        Self {
            data_plane: index,
            admission: Some(admission),
        }
    }

    /// The typed acquisition branch for a dispatch neck (C4c): the data
    /// plane is handed out only while the carried admission slot is still
    /// the live occupancy of its key. The evidence is the registry's own
    /// shared revocation flag — the slot the stop path revokes IS the slot
    /// this handle asks — so a project retired between map lookup and
    /// dispatch refuses instead of serving a retired index.
    pub fn acquire(
        &self,
    ) -> Result<&crate::live_index::store::SharedIndex, super::registry::RegistryRefusal> {
        if let Some(slot) = &self.admission
            && !slot.is_live()
        {
            return Err(super::registry::RegistryRefusal::Tombstoned { slot: slot.slot() });
        }
        Ok(&self.data_plane)
    }

    /// The owned V10 data plane, borrowed.
    pub fn data_plane(&self) -> &crate::live_index::store::SharedIndex {
        &self.data_plane
    }

    /// A clone of the owned data plane for spawn captures.
    pub fn shared(&self) -> crate::live_index::store::SharedIndex {
        Arc::clone(&self.data_plane)
    }

    #[cfg(feature = "__test-internals")]
    pub fn revoke_admission_for_test(&self) {
        if let Some(slot) = &self.admission {
            slot.revoke_for_test();
        }
    }

    /// The source authority for the handle's currently bound root, when one
    /// is bound — the same per-root instance every writer and observation
    /// lane converges on through the canonicalized registry.
    pub fn authority(&self) -> Option<Arc<ProjectSourceAuthority>> {
        let root = self.data_plane.read().indexed_root.clone()?;
        Some(project_source_authority(&root))
    }
}

// ── Process bootstrap: ceremony, surfaces, admission (T030, C4b) ───────────

/// Dark process capacity budget: every surface can attach at the observation
/// lane's dark budget. C7/C8 replace the dark constants with measured ones.
const PROCESS_CAPACITY_BYTES: u64 = (SurfaceKind::ALL.len() as u64) * OBSERVATION_CAPACITY_BYTES;

static PROCESS_INDEX_RUNTIME: OnceLock<Arc<ProcessIndexRuntime>> = OnceLock::new();
static PROCESS_PROJECT_REGISTRY: OnceLock<Arc<ProjectRegistry>> = OnceLock::new();
/// Serializes the one-time ceremony and surface attaches so concurrent
/// surface starts cannot race either.
static PROCESS_BOOTSTRAP: Mutex<()> = Mutex::new(());

/// The one process capacity runtime every surface attaches to.
pub fn process_index_runtime() -> Arc<ProcessIndexRuntime> {
    PROCESS_INDEX_RUNTIME
        .get_or_init(|| ProcessIndexRuntime::incarnate(PROCESS_CAPACITY_BYTES))
        .clone()
}

/// The process project registry — the admission table bootstrap owns. The
/// C4b registry-ownership move: projects enter through [`admit_project`],
/// never by a lane minting its own slot.
pub fn process_project_registry() -> Arc<ProjectRegistry> {
    PROCESS_PROJECT_REGISTRY
        .get_or_init(ProjectRegistry::new)
        .clone()
}

/// Drive the process activation machine through its startup ceremony and
/// attach `surface` to the capacity runtime. Idempotent per process and per
/// surface.
///
/// The ceremony runs BEFORE the surface serves its first request, which is
/// what makes each drain confirmation truthful: at that moment the
/// bootstrapper IS every lane's owner, and it can observe that nothing has
/// entered the legacy gate because serving has not begun. After
/// [`ActivationCut::open_preventive`], [`ActivationMode`] is
/// `PreventiveV1Open` and the `LegacyOpen` gate admits no further
/// [`LaneRegistration`]. That is the observation the ceremony records as
/// typed evidence. Query traffic is a different door: it still goes through
/// [`ProjectRuntimeHandle::data_plane`] → `SharedIndex` (the D1 mid-cut
/// recorded at `ObservationLane` and at `ProjectRuntimeHandle`). Retiring
/// that door is not this pass.
pub fn activate_surface(surface: SurfaceKind) {
    let _bootstrap = PROCESS_BOOTSTRAP.lock().expect("process bootstrap lock");
    let machine = ActivationCut::process();
    if machine.mode() == ActivationMode::LegacyOpen {
        let registrations: Vec<LaneRegistration> = RegisteredLane::ALL
            .iter()
            .map(|lane| {
                machine
                    .register_lane(*lane)
                    .expect("the bootstrap lock is held and the machine is LegacyOpen")
            })
            .collect();
        machine
            .begin_closing()
            .expect("every lane registered above");
        for registration in registrations {
            machine
                .confirm_drained(registration)
                .expect("the drain window opened above");
        }
        machine
            .open_preventive()
            .expect("every registered lane confirmed above");
    }
    let runtime = process_index_runtime();
    if runtime.owner_for(surface).is_none() {
        runtime
            .attach(surface, OBSERVATION_CAPACITY_BYTES)
            .expect("all surfaces fit the process budget by construction");
    }
}

/// One admitted project bootstrap (C4b): plan against the process runtime
/// and admit through the process registry — single-flight per key, and a
/// live occupancy joins when root and placement agree — then install as
/// live. Self-activating: the surface's ceremony and capacity attach run
/// first, so a bare test constructing a project without a daemon still
/// admits honestly. The per-root authority is created (or joined) through
/// the same canonicalized registry every writer lane converges on, and the
/// admission presents its stable admission-root identity so every open of
/// one root names the same physical root.
pub fn admit_project(
    surface: SurfaceKind,
    canonical_root: &Path,
    project_id: &str,
    access_mode: crate::domain::index::SourceAccessMode,
    placement: &crate::domain::StatePlacement,
) -> Result<Arc<LiveProjectSlot>, AdapterRefusal> {
    admit_project_with_outcome(surface, canonical_root, project_id, access_mode, placement)
        .map(ProjectAdmission::into_slot)
}

/// A project admission plus the ownership evidence needed to clean up a failed
/// bootstrap without retiring another opener's already-live slot.
#[derive(Debug, Clone)]
pub struct ProjectAdmission {
    slot: Arc<LiveProjectSlot>,
    cleanup_candidate: bool,
}

impl ProjectAdmission {
    /// The admitted live slot.
    pub fn slot(&self) -> &Arc<LiveProjectSlot> {
        &self.slot
    }

    /// Consume the outcome and return the live slot.
    pub fn into_slot(self) -> Arc<LiveProjectSlot> {
        self.slot
    }

    /// True when this admission came from a pending group this bootstrap may
    /// retire on failure if no other holder won.
    pub fn cleanup_candidate(&self) -> bool {
        self.cleanup_candidate
    }
}

pub fn admit_project_with_outcome(
    surface: SurfaceKind,
    canonical_root: &Path,
    project_id: &str,
    access_mode: crate::domain::index::SourceAccessMode,
    placement: &crate::domain::StatePlacement,
) -> Result<ProjectAdmission, AdapterRefusal> {
    use crate::domain::index::SourceAccessMode as Mode;

    activate_surface(surface);
    let runtime = process_index_runtime();
    let registry = process_project_registry();
    let key = ProjectKey::new(project_id);
    let protection = match access_mode {
        Mode::NormalProject => RootProtection::Normal,
        // A protected root binds only when the operator asked for it
        // explicitly; the explicitness IS the authorization.
        Mode::ExplicitProtected => RootProtection::Protected,
    };
    let authorized = matches!(access_mode, Mode::ExplicitProtected);
    let requested = match placement {
        crate::domain::StatePlacement::ProjectLocal { .. } => AdmissionStatePlacement::ProjectLocal,
        crate::domain::StatePlacement::UserLocal { .. } => AdmissionStatePlacement::UserLocal,
        crate::domain::StatePlacement::MemoryOnly { .. } => AdmissionStatePlacement::MemoryOnly,
    };
    // D17 is fail-never under contention, and the install/live pair below has
    // THREE outcomes rather than the two its original comment named. An admit
    // that JOINS an already-live occupancy holds no pending claim of its own.
    // So when the last session closes and `ProjectRegistry::stop` removes that
    // live occupancy in the window between our admit and our install, `install`
    // refuses `NotAdmitted` because nothing is pending AND `live` refuses
    // `NotAdmitted` because nothing is live. Propagating that is what broke
    // `open_project_session` under contention.
    //
    // A torn-down occupancy is a lost race, not a refusal, so re-admit into a
    // fresh occupancy or join the pending opener that appeared after our failed
    // install. Retrying is side-effect free: `plan_admission`
    // only resolves an owner and validates placement, and
    // `execute_plan_with_outcome` takes no capacity permit, so a discarded pass
    // leaves nothing behind. Bounded, because an unbounded retry would turn a
    // genuinely persistent refusal into a spin.
    //
    // Note `stop` cannot produce this against a PENDING occupancy: it
    // re-inserts what it refused to remove, precisely so a joiner's claim
    // survives. Only the joined-live shape reaches here.
    const TORN_DOWN_ADMIT_ATTEMPTS: u32 = 4;
    let mut torn_down_retries = 0u32;
    loop {
        let plan = plan_admission(
            &runtime,
            surface,
            key.clone(),
            protection,
            authorized,
            requested,
        )?;
        let binding = project_source_authority(canonical_root).admission_binding();
        let (attempt, owner) = execute_plan_with_outcome(&registry, &plan, binding)?;
        let cleanup_candidate = attempt.cleanup_candidate();
        // The window a concurrent `stop` uses to strand this joiner.
        #[cfg(all(test, feature = "server"))]
        admit_before_install::fire();
        match registry.install(&key, Some(owner)) {
            Ok(live) => {
                return Ok(ProjectAdmission {
                    slot: live,
                    cleanup_candidate,
                });
            }
            // Not pending any more: either a concurrent opener installed between
            // our admit and install, or the admit above JOINED an occupancy that
            // is already live. Both resolve to the same live slot.
            Err(RegistryRefusal::NotAdmitted) => match registry.live(&key) {
                Ok(live) => {
                    return Ok(ProjectAdmission {
                        slot: live,
                        cleanup_candidate,
                    });
                }
                // Stopped mid-flight. If another opener has already recreated
                // Pending, re-admit joins that single-flight instead.
                Err(RegistryRefusal::NotAdmitted | RegistryRefusal::StillPending)
                    if torn_down_retries + 1 < TORN_DOWN_ADMIT_ATTEMPTS =>
                {
                    torn_down_retries += 1;
                    continue;
                }
                Err(refusal) => return Err(AdapterRefusal::Registry(refusal)),
            },
            Err(refusal) => return Err(AdapterRefusal::Registry(refusal)),
        }
    }
}

/// Feature 020 V11, T066 — activation machine oracles (in-crate per the
/// discharged fixture-door precondition; see `runtime.rs`).
/// Deterministic observation point inside [`admit_project_with_outcome`],
/// fired after a successful admit and BEFORE its `install`. That is exactly
/// the window a concurrent `stop` uses to strand a joiner, so a test can
/// occupy it on purpose instead of hoping a stress run trips the race.
///
/// Unlike `store.rs`'s mid-commit hook this is deliberately NOT consumed on
/// fire. The property under test is how many times the bounded retry re-enters
/// the window, so the observation must land on EVERY pass; a consume-once hook
/// would silently measure one.
///
/// Gated on `server` as well as `test` for the reason recorded in `store.rs`:
/// under `--no-default-features --features embed` the lib tests still compile,
/// and a bare `#[cfg(test)]` module whose only consumer is server-only is an
/// unused item there, which `-D warnings` rejects.
#[cfg(all(test, feature = "server"))]
pub(crate) mod admit_before_install {
    use std::cell::RefCell;

    type Hook = Box<dyn Fn()>;

    thread_local! {
        static HOOK: RefCell<Option<Hook>> = const { RefCell::new(None) };
    }

    /// RAII guard so a hook cannot leak across the thread-local into a sibling
    /// test sharing this thread.
    pub(crate) struct BeforeInstallGuard;

    impl Drop for BeforeInstallGuard {
        fn drop(&mut self) {
            HOOK.with(|h| *h.borrow_mut() = None);
        }
    }

    pub(crate) fn install(hook: impl Fn() + 'static) -> BeforeInstallGuard {
        HOOK.with(|h| *h.borrow_mut() = Some(Box::new(hook)));
        BeforeInstallGuard
    }

    /// Take the hook out for the duration of the call, then re-arm it. Taking
    /// it first means a hook that re-enters this window cannot double-borrow
    /// the `RefCell`; re-arming only when the slot is still empty means a hook
    /// that deliberately uninstalls itself stays uninstalled.
    pub(crate) fn fire() {
        let Some(hook) = HOOK.with(|h| h.borrow_mut().take()) else {
            return;
        };
        hook();
        HOOK.with(|h| {
            let mut slot = h.borrow_mut();
            if slot.is_none() {
                *slot = Some(hook);
            }
        });
    }
}

/// Coverage for the bounded re-admit loop itself.
///
/// The window control in `tests/project_registry_lifecycle_v11.rs` pins that
/// the empty occupancy is reachable and that a fresh admit clears it. It never
/// enters the loop, so neither the retry nor its bound was exercised. These do
/// both, deterministically, by occupying the admit/install window on purpose.
#[cfg(all(test, feature = "server"))]
mod admit_retry_loop {
    use super::{
        SurfaceKind, admit_before_install, admit_project_with_outcome, process_project_registry,
    };
    use crate::domain::index::SourceAccessMode;
    use crate::domain::{ProjectStateDir, StatePlacement};
    use crate::live_index::index_lifecycle::registry::ProjectKey;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn placement(root: &std::path::Path) -> StatePlacement {
        StatePlacement::ProjectLocal {
            directory: ProjectStateDir::new(root.join(".symforge")),
        }
    }

    /// The retry fires: a joiner stranded ONCE re-admits and still returns a
    /// live slot, instead of surfacing the D17 refusal.
    ///
    /// The first admission must install, because the race needs an admit that
    /// JOINS a live occupancy and therefore holds no pending claim of its own.
    /// A pending occupancy cannot be stranded this way at all: `stop`
    /// re-inserts what it refused to remove.
    #[test]
    fn a_joiner_stranded_once_is_re_admitted() {
        let root = tempfile::tempdir().expect("root");
        let id = "d17-loop-retry-once";
        let key = ProjectKey::new(id);
        let registry = process_project_registry();

        admit_project_with_outcome(
            SurfaceKind::Stdio,
            root.path(),
            id,
            SourceAccessMode::NormalProject,
            &placement(root.path()),
        )
        .expect("the first admission installs and goes live");

        let fired = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&fired);
        let strand = Arc::clone(&registry);
        let stranded_key = key.clone();
        let _hook = admit_before_install::install(move || {
            // Strand the FIRST pass only, so the retry has something to prove.
            if counter.fetch_add(1, Ordering::SeqCst) == 0 {
                let _ = strand.stop(&stranded_key);
            }
        });

        admit_project_with_outcome(
            SurfaceKind::Stdio,
            root.path(),
            id,
            SourceAccessMode::NormalProject,
            &placement(root.path()),
        )
        .expect("a joiner stranded mid-flight must re-admit, not refuse");

        assert_eq!(
            fired.load(Ordering::SeqCst),
            2,
            "the window must be entered twice: the stranded pass and its retry"
        );
    }

    /// The bound terminates: a key held torn-down on every pass propagates
    /// after exactly `TORN_DOWN_ADMIT_ATTEMPTS` entries rather than spinning.
    ///
    /// `stop` clears a live occupancy and `cancel` clears a pending one, so
    /// firing both keeps the key empty whichever shape each pass produced.
    #[test]
    fn a_permanently_torn_down_key_propagates_after_the_bound() {
        let root = tempfile::tempdir().expect("root");
        let id = "d17-loop-bound-exhausts";
        let key = ProjectKey::new(id);
        let registry = process_project_registry();

        let fired = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&fired);
        let strand = Arc::clone(&registry);
        let stranded_key = key.clone();
        let _hook = admit_before_install::install(move || {
            counter.fetch_add(1, Ordering::SeqCst);
            let _ = strand.stop(&stranded_key);
            let _ = strand.cancel(&stranded_key);
        });

        let refused = admit_project_with_outcome(
            SurfaceKind::Stdio,
            root.path(),
            id,
            SourceAccessMode::NormalProject,
            &placement(root.path()),
        );

        assert!(
            refused.is_err(),
            "a key that is torn down on every pass must eventually refuse, not spin"
        );
        assert_eq!(
            fired.load(Ordering::SeqCst),
            4,
            "the bound is four attempts; a change here is a deliberate change to              TORN_DOWN_ADMIT_ATTEMPTS, not an incidental one"
        );
    }
}

#[cfg(all(test, feature = "server"))]
mod activation_oracles {
    use super::{ActivationCut, ActivationMode, ActivationRefusal, RegisteredLane};

    fn register_all(machine: &ActivationCut) -> Vec<super::LaneRegistration> {
        RegisteredLane::ALL
            .iter()
            .map(|lane| machine.register_lane(*lane).expect("fresh lane registers"))
            .collect()
    }

    #[test]
    fn starts_legacy_open_and_advances_only_forward() {
        let machine = ActivationCut::fresh_for_oracles();
        assert_eq!(machine.mode(), ActivationMode::LegacyOpen);

        let registrations = register_all(&machine);
        machine.begin_closing().expect("all lanes registered");
        assert_eq!(machine.mode(), ActivationMode::LegacyClosing);

        for registration in registrations {
            machine
                .confirm_drained(registration)
                .expect("drain confirms in the drain window");
        }
        machine.open_preventive().expect("all lanes drained");
        assert_eq!(machine.mode(), ActivationMode::PreventiveV1Open);

        // Monotonic: nothing re-enters an earlier mode. Registration and a
        // second closing both refuse with the mode they found.
        let refusal = machine
            .register_lane(RegisteredLane::Hook)
            .expect_err("registration after the cut refuses");
        assert_eq!(
            refusal,
            ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyOpen,
                actual: ActivationMode::PreventiveV1Open,
            }
        );
        assert_eq!(
            machine.begin_closing(),
            Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyOpen,
                actual: ActivationMode::PreventiveV1Open,
            })
        );
        assert_eq!(
            machine.open_preventive(),
            Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyClosing,
                actual: ActivationMode::PreventiveV1Open,
            })
        );
    }

    #[test]
    fn closing_refuses_until_every_lane_is_registered() {
        let machine = ActivationCut::fresh_for_oracles();
        for lane in &RegisteredLane::ALL[..8] {
            machine.register_lane(*lane).expect("register");
        }
        // The refusal NAMES the missing lane — an unregistered lane is the
        // unmatched ingress SC-001 forbids, not a count.
        assert_eq!(
            machine.begin_closing(),
            Err(ActivationRefusal::LanesUnregistered(vec![
                RegisteredLane::Finalization
            ]))
        );
        assert_eq!(machine.mode(), ActivationMode::LegacyOpen);

        // Positive control: registering the ninth lane makes the same call
        // succeed, so the refusal above was about the gap, not the gate.
        machine
            .register_lane(RegisteredLane::Finalization)
            .expect("register the ninth");
        machine.begin_closing().expect("now complete");
        assert_eq!(machine.mode(), ActivationMode::LegacyClosing);
    }

    #[test]
    fn preventive_refuses_until_every_lane_confirms_drain() {
        let machine = ActivationCut::fresh_for_oracles();
        let mut registrations = register_all(&machine);
        machine.begin_closing().expect("registered");

        let held_back = registrations.pop().expect("nine registrations");
        let held_lane = held_back.lane();
        for registration in registrations {
            machine.confirm_drained(registration).expect("drain");
        }
        assert_eq!(
            machine.open_preventive(),
            Err(ActivationRefusal::LanesUndrained(vec![held_lane]))
        );
        assert_eq!(machine.mode(), ActivationMode::LegacyClosing);

        // Positive control: the last confirmation opens the door.
        machine.confirm_drained(held_back).expect("last drain");
        machine.open_preventive().expect("all drained");
        assert_eq!(machine.mode(), ActivationMode::PreventiveV1Open);
    }

    #[test]
    fn registration_is_once_and_machine_bound() {
        let machine_a = ActivationCut::fresh_for_oracles();
        let machine_b = ActivationCut::fresh_for_oracles();

        let token = machine_a
            .register_lane(RegisteredLane::Cache)
            .expect("first registration");
        let refusal = machine_a
            .register_lane(RegisteredLane::Cache)
            .expect_err("a second registration of the same lane refuses");
        assert_eq!(
            refusal,
            ActivationRefusal::LaneAlreadyRegistered(RegisteredLane::Cache)
        );

        // A token minted by machine A carries A's identity; machine B
        // refuses it even in the right window.
        for lane in RegisteredLane::ALL {
            machine_b.register_lane(lane).expect("register on b");
        }
        machine_b.begin_closing().expect("b closes");
        assert_eq!(
            machine_b.confirm_drained(token),
            Err(ActivationRefusal::ForeignRegistration)
        );
    }

    #[test]
    fn premature_drain_confirmation_refuses_and_strands() {
        let machine = ActivationCut::fresh_for_oracles();
        let token = machine
            .register_lane(RegisteredLane::Sidecar)
            .expect("register");
        // Confirming before the drain window consumes the token and refuses.
        assert_eq!(
            machine.confirm_drained(token),
            Err(ActivationRefusal::WrongMode {
                expected: ActivationMode::LegacyClosing,
                actual: ActivationMode::LegacyOpen,
            })
        );
        // The strand is deliberate: the machine can now never open, because
        // the sidecar lane's only token is spent. Every OTHER lane registers
        // and drains normally, so the final refusal names exactly the
        // stranded lane. A mis-sequenced bootstrap fails loudly here rather
        // than half-opening.
        let others: Vec<super::LaneRegistration> = RegisteredLane::ALL
            .iter()
            .copied()
            .filter(|lane| *lane != RegisteredLane::Sidecar)
            .map(|lane| machine.register_lane(lane).expect("register"))
            .collect();
        machine.begin_closing().expect("registration is complete");
        for registration in others {
            machine.confirm_drained(registration).expect("drain");
        }
        assert_eq!(
            machine.open_preventive(),
            Err(ActivationRefusal::LanesUndrained(vec![
                RegisteredLane::Sidecar
            ]))
        );
    }

    #[test]
    fn process_machine_is_one_per_process_and_never_precedes_legacy_open() {
        let first = ActivationCut::process();
        let second = ActivationCut::process();
        assert!(
            std::ptr::eq(first, second),
            "process() returns the one process-wide machine"
        );
        // Since C4b the production bootstrap (`activate_surface`) drives the
        // process machine to `PreventiveV1Open`, and any daemon/serve test
        // that ran earlier in this serial binary has legitimately done so.
        // The START mode is pinned on a fresh machine by
        // `starts_legacy_open_and_advances_only_forward`; the singleton claim
        // left to pin here is monotonicity's floor: the machine is never in a
        // state outside the closed three-mode set, and if the ceremony ran it
        // is exactly `PreventiveV1Open`, never half-open.
        assert!(
            matches!(
                first.mode(),
                ActivationMode::LegacyOpen | ActivationMode::PreventiveV1Open
            ),
            "the process machine is never observed mid-drain outside the ceremony"
        );
    }
}

/// Feature 020 V11, T064 — write-lane bridge oracles.
#[cfg(all(test, feature = "server"))]
mod write_authority_oracles {
    use super::ProjectSourceAuthority;
    use crate::live_index::index_lifecycle::authority::AuthorityRefusal;
    use crate::live_index::index_lifecycle::observer::{CutKind, LatchCause};

    fn a_temp_root(tag: &str) -> std::path::PathBuf {
        let root = std::env::temp_dir().join(format!(
            "symforge-write-authority-{tag}-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&root).expect("create oracle root");
        root
    }

    #[test]
    fn write_cycle_publishes_non_current_then_returns_current_fresh() {
        let root = a_temp_root("cycle");
        let authority = ProjectSourceAuthority::for_root(&root);
        assert!(authority.is_current(), "the bridge seeds Current");
        let before = authority
            .current_publication()
            .expect("Current has a publication");

        let mut write = authority.acquire_write().expect("grant on Current");
        assert!(
            !authority.is_current(),
            "the grant itself published non-Current before any byte moved"
        );

        let receipt = write
            .write(std::path::Path::new("oracle.txt"), b"written under permit")
            .expect("confined write beneath the leased root");
        write.finish_committed(receipt).expect("commit and return");

        assert!(authority.is_current(), "the source returned to Current");
        let after = authority
            .current_publication()
            .expect("Current has a publication");
        assert_ne!(
            before, after,
            "return is through a FRESH publication, never a restore"
        );
        assert_eq!(
            std::fs::read(root.join("oracle.txt")).expect("the write landed"),
            b"written under permit",
            "the permit's lease wrote the actual bytes"
        );
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn one_outstanding_write_authority_at_a_time() {
        let root = a_temp_root("single");
        let authority = ProjectSourceAuthority::for_root(&root);

        let write = authority.acquire_write().expect("first grant");
        let refusal = authority
            .acquire_write()
            .expect_err("a second grant while one is outstanding refuses");
        assert!(
            matches!(refusal, AuthorityRefusal::PhaseNotCurrent { .. }),
            "the refusal names the non-Current phase, got {refusal:?}"
        );

        // Positive control: finishing the first restores grantability.
        write
            .finish_no_side_effect()
            .expect("an unstarted permit attests no side effect");
        authority
            .acquire_write()
            .expect("after the return to Current a fresh grant succeeds");
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn no_side_effect_refuses_once_a_side_effect_began() {
        let root = a_temp_root("nse");
        let authority = ProjectSourceAuthority::for_root(&root);

        let mut write = authority.acquire_write().expect("grant");
        write
            .write(std::path::Path::new("touched.txt"), b"bytes")
            .expect("write");
        let refusal = write
            .finish_no_side_effect()
            .expect_err("a begun side effect cannot be attested away");
        assert!(
            matches!(refusal, AuthorityRefusal::SideEffectAlreadyInFlight),
            "the refusal names the in-flight side effect, got {refusal:?}"
        );
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn no_side_effect_return_is_also_a_fresh_publication() {
        let root = a_temp_root("nse-fresh");
        let authority = ProjectSourceAuthority::for_root(&root);
        let before = authority.current_publication().expect("publication");

        let write = authority.acquire_write().expect("grant");
        write
            .finish_no_side_effect()
            .expect("unstarted permit attests");
        let after = authority.current_publication().expect("publication");
        assert_ne!(
            before, after,
            "FR-043: even a proven no-op returns through a fresh publication"
        );
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn dropped_write_authority_recovers_current_through_a_scope_dirty_baseline() {
        let root = a_temp_root("dropped");
        let authority = ProjectSourceAuthority::for_root(&root);
        let before = authority.current_publication().expect("publication");

        let write = authority.acquire_write().expect("grant");
        drop(write);

        // The C3 re-scout recovery lane: the drained permit's write state is
        // unobserved, so the return is through a FRESH publication whose
        // consumed observation cut is a FULL baseline latched ScopeDirty —
        // never a silent restore, and no longer a strand.
        assert!(
            authority.is_current(),
            "recovery returns the source to Current"
        );
        let after = authority.current_publication().expect("publication");
        assert_ne!(
            before, after,
            "recovery is a fresh publication, never a restore"
        );
        match authority
            .last_reconcile_cut()
            .expect("recovery consumed a cut")
            .kind
        {
            CutKind::FullBaseline {
                cause: LatchCause::ScopeDirty,
            } => {}
            other => panic!("recovery must consume a scope-dirty full baseline, got {other:?}"),
        }
        authority
            .acquire_write()
            .expect("a recovered source grants again");
        std::fs::remove_dir_all(&root).ok();
    }
}

/// Feature 020 V11, T029 — observation-lane oracles (C3). The drop-recovery
/// inversion above is this commit's observed RED (the C2 stranding oracle
/// failed against the new expectation before the recovery lane existed);
/// these pin the lane's admission, incarnation, and gap semantics.
#[cfg(all(test, feature = "server"))]
mod observation_lane_oracles {
    use super::ProjectSourceAuthority;
    use crate::live_index::index_lifecycle::observer::{CutKind, LatchCause};

    fn a_temp_root(tag: &str) -> std::path::PathBuf {
        let root = std::env::temp_dir().join(format!(
            "symforge-observation-lane-{tag}-{}",
            std::process::id()
        ));
        std::fs::create_dir_all(&root).expect("create oracle root");
        root
    }

    fn consume_cut(authority: &std::sync::Arc<ProjectSourceAuthority>) -> CutKind {
        let write = authority.acquire_write().expect("grant");
        write.finish_no_side_effect().expect("no-op return");
        authority
            .last_reconcile_cut()
            .expect("the return consumed a cut")
            .kind
    }

    #[test]
    fn admissions_drive_the_candidate_pipeline_and_coalesce_into_one_cut() {
        let root = a_temp_root("admission");
        let authority = ProjectSourceAuthority::for_root(&root);
        assert_eq!(authority.committed_observations("src/a.rs"), 0);

        authority.observe_admission_active("src/a.rs");
        authority.observe_admission_active("src/a.rs");

        assert_eq!(
            authority.committed_observations("src/a.rs"),
            2,
            "each admission reaches the single commit point (new membership, \
             then an exact-validated delta over it)"
        );
        match consume_cut(&authority) {
            CutKind::Incremental { invalidations } => {
                assert_eq!(
                    invalidations.len(),
                    1,
                    "repeated observations of one source coalesce"
                );
            }
            other => panic!("clean admissions produce an incremental cut, got {other:?}"),
        }
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn a_new_incarnation_refuses_late_callbacks_and_forces_the_barrier_baseline() {
        let root = a_temp_root("incarnation");
        let authority = ProjectSourceAuthority::for_root(&root);
        let stale = authority.active_observer();

        let fresh = authority.register_observer();
        assert_ne!(stale, fresh);

        // The predecessor's late callback is unreachable: every observation
        // entry refuses the stale id and names the active incarnation.
        assert_eq!(authority.observe_admission(stale, "src/a.rs"), Err(fresh));
        assert_eq!(authority.observe_removal(stale, "src/a.rs"), Err(fresh));
        assert_eq!(authority.report_gap(stale), Err(fresh));
        assert_eq!(
            authority.committed_observations("src/a.rs"),
            0,
            "a refused observation commits nothing"
        );

        // The successor's first consumed cut is the post-barrier baseline.
        match consume_cut(&authority) {
            CutKind::FullBaseline {
                cause: LatchCause::HandoffBarrier,
            } => {}
            other => panic!("the handoff obligation is a full baseline, got {other:?}"),
        }
        std::fs::remove_dir_all(&root).ok();
    }

    #[test]
    fn a_reported_gap_forces_the_full_baseline_over_later_admissions() {
        let root = a_temp_root("gap");
        let authority = ProjectSourceAuthority::for_root(&root);
        let observer = authority.active_observer();

        authority.report_gap(observer).expect("active incarnation");
        authority
            .observe_admission(observer, "src/a.rs")
            .expect("active incarnation");

        match consume_cut(&authority) {
            CutKind::FullBaseline {
                cause: LatchCause::Gap,
            } => {}
            other => panic!("the first latch cause wins the baseline, got {other:?}"),
        }
        std::fs::remove_dir_all(&root).ok();
    }
}