rustclamp-kernel 1.0.0

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

#![forbid(unsafe_code)]
#![deny(missing_docs)]

use std::collections::{BTreeMap, BTreeSet, VecDeque};
use std::error::Error;
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;

use rustclamp_core::{
    ApplicationId, Capability, CapabilityId, Contribution, ContributionId, ContributionTarget,
    ContributionTargetId, ExecutionId, Module, ModuleId, ProcessId, Provides, Qualifier,
    QualifierId, Requires,
};

/// A caller-owned application blueprint containing process roots and module relations.
///
/// The blueprint describes declarations only. [`ApplicationBlueprint::project`]
/// derives the reachable module set for one process without constructing modules.
pub struct ApplicationBlueprint {
    application: ApplicationId,
    modules: BTreeSet<ModuleId>,
    executions: BTreeMap<ExecutionId, ModuleId>,
    processes: BTreeMap<ProcessId, Vec<ExecutionId>>,
    providers: Vec<(ModuleId, CapabilityId, Option<QualifierId>)>,
    requirements: Vec<(ModuleId, CapabilityId, Option<QualifierId>, bool)>,
    selections: Vec<(ModuleId, CapabilityId, Option<QualifierId>, ModuleId)>,
    defaults: Vec<(ModuleId, CapabilityId, Option<QualifierId>, ModuleId)>,
    replacements: Vec<(CapabilityId, Option<QualifierId>, ModuleId, ModuleId)>,
    exclusions: BTreeSet<ModuleId>,
    target_consumptions: Vec<(ModuleId, ContributionTargetId, QualifierId)>,
    contributions: Vec<(
        ModuleId,
        ContributionTargetId,
        QualifierId,
        ContributionId,
        bool,
    )>,
}

impl ApplicationBlueprint {
    /// Creates an empty architecture blueprint with a stable identity.
    pub fn new(application: ApplicationId) -> Self {
        Self {
            application,
            modules: BTreeSet::new(),
            executions: BTreeMap::new(),
            processes: BTreeMap::new(),
            providers: Vec::new(),
            requirements: Vec::new(),
            selections: Vec::new(),
            defaults: Vec::new(),
            replacements: Vec::new(),
            exclusions: BTreeSet::new(),
            target_consumptions: Vec::new(),
            contributions: Vec::new(),
        }
    }

    /// Declares a module that may be included in one or more process projections.
    pub fn add_module(&mut self, module: ModuleId) -> &mut Self {
        self.modules.insert(module);
        self
    }

    /// Declares an execution root implemented by a module.
    pub fn add_execution(&mut self, execution: ExecutionId, module: ModuleId) -> &mut Self {
        self.executions.insert(execution, module);
        self
    }

    /// Declares one or more execution roots for a runnable process projection.
    pub fn add_process(&mut self, process: ProcessId, roots: Vec<ExecutionId>) -> &mut Self {
        self.processes.insert(process, roots);
        self
    }

    /// Declares a process with one execution root: the module, its execution, and
    /// the process that runs only that execution.
    pub fn add_root(
        &mut self,
        process: ProcessId,
        execution: ExecutionId,
        module: ModuleId,
    ) -> &mut Self {
        self.add_module(module)
            .add_execution(execution, module)
            .add_process(process, vec![execution])
    }

    /// Connects a module requirement to its already selected capability provider.
    pub fn require_provider(
        &mut self,
        consumer: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        provider: ModuleId,
    ) -> &mut Self {
        self.provide_capability(provider, capability, qualifier)
            .require_capability(consumer, capability, qualifier, false)
            .select_provider(consumer, capability, qualifier, provider);
        self
    }

    /// Declares that a module provides a capability for an optional qualifier.
    pub fn provide_capability(
        &mut self,
        module: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
    ) -> &mut Self {
        self.providers.push((module, capability, qualifier));
        self
    }

    /// Declares a capability requirement. Optional requirements do not activate a provider.
    pub fn require_capability(
        &mut self,
        consumer: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        optional: bool,
    ) -> &mut Self {
        self.requirements
            .push((consumer, capability, qualifier, optional));
        self
    }

    /// Selects a provider for one module requirement.
    pub fn select_provider(
        &mut self,
        consumer: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        provider: ModuleId,
    ) -> &mut Self {
        self.selections
            .push((consumer, capability, qualifier, provider));
        self
    }

    /// Declares a default provider for one module requirement.
    pub fn default_provider(
        &mut self,
        consumer: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        provider: ModuleId,
    ) -> &mut Self {
        self.defaults
            .push((consumer, capability, qualifier, provider));
        self
    }

    /// Replaces one provider with another for a capability and qualifier.
    pub fn replace_provider(
        &mut self,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        replaced: ModuleId,
        replacement: ModuleId,
    ) -> &mut Self {
        self.replacements
            .push((capability, qualifier, replaced, replacement));
        self
    }

    /// Excludes a module from provider selection and process reachability.
    pub fn exclude_module(&mut self, module: ModuleId) -> &mut Self {
        self.exclusions.insert(module);
        self
    }

    /// Declares that a module consumes a qualified contribution target.
    pub fn consume_target(
        &mut self,
        consumer: ModuleId,
        target: ContributionTargetId,
        qualifier: QualifierId,
    ) -> &mut Self {
        self.target_consumptions.push((consumer, target, qualifier));
        self
    }

    /// Declares that a module contributes to a qualified target.
    pub fn add_contribution(
        &mut self,
        contributor: ModuleId,
        target: ContributionTargetId,
        qualifier: QualifierId,
        contribution: ContributionId,
    ) -> &mut Self {
        self.contributions
            .push((contributor, target, qualifier, contribution, true));
        self
    }

    /// Declares an optional contribution that may be discarded without a target.
    pub fn add_optional_contribution(
        &mut self,
        contributor: ModuleId,
        target: ContributionTargetId,
        qualifier: QualifierId,
        contribution: ContributionId,
    ) -> &mut Self {
        self.contributions
            .push((contributor, target, qualifier, contribution, false));
        self
    }

    /// Derives the reachable module projection from a process's execution roots.
    pub fn project(&self, process: ProcessId) -> Result<ProcessProjection, ProjectionError> {
        let application = self.application;
        let mut providers_by_capability =
            BTreeMap::<(CapabilityId, Option<QualifierId>), Vec<ModuleId>>::new();
        for (module, capability, qualifier) in &self.providers {
            providers_by_capability
                .entry((*capability, *qualifier))
                .or_default()
                .push(*module);
        }
        for providers in providers_by_capability.values_mut() {
            providers.sort_unstable();
            providers.dedup();
        }
        let mut requirements_by_owner =
            BTreeMap::<ModuleId, Vec<(CapabilityId, Option<QualifierId>, bool)>>::new();
        for (consumer, capability, qualifier, optional) in &self.requirements {
            requirements_by_owner.entry(*consumer).or_default().push((
                *capability,
                *qualifier,
                *optional,
            ));
        }
        let mut selections = BTreeMap::new();
        for (consumer, capability, qualifier, provider) in &self.selections {
            selections
                .entry((*consumer, *capability, *qualifier))
                .or_insert(*provider);
        }
        let mut defaults =
            BTreeMap::<(ModuleId, CapabilityId, Option<QualifierId>), Vec<ModuleId>>::new();
        for (consumer, capability, qualifier, provider) in &self.defaults {
            defaults
                .entry((*consumer, *capability, *qualifier))
                .or_default()
                .push(*provider);
        }
        for providers in defaults.values_mut() {
            providers.sort_unstable();
            providers.dedup();
        }
        let mut targets_by_owner =
            BTreeMap::<ModuleId, Vec<(ContributionTargetId, QualifierId)>>::new();
        let mut consumers_by_target =
            BTreeMap::<(ContributionTargetId, QualifierId), Vec<ModuleId>>::new();
        for (consumer, target, qualifier) in &self.target_consumptions {
            targets_by_owner
                .entry(*consumer)
                .or_default()
                .push((*target, *qualifier));
            consumers_by_target
                .entry((*target, *qualifier))
                .or_default()
                .push(*consumer);
        }
        let mut contributions_by_target =
            BTreeMap::<(ContributionTargetId, QualifierId), Vec<(ModuleId, ContributionId)>>::new();
        for (contributor, target, qualifier, contribution, _) in &self.contributions {
            contributions_by_target
                .entry((*target, *qualifier))
                .or_default()
                .push((*contributor, *contribution));
        }
        let replacements = self
            .replacements
            .iter()
            .map(|(capability, qualifier, old, new)| ((*capability, *qualifier, *old), *new))
            .collect::<BTreeMap<_, _>>();
        let replacement_sources = self
            .replacements
            .iter()
            .map(|(capability, qualifier, old, new)| ((*capability, *qualifier, *new), *old))
            .collect::<BTreeMap<_, _>>();
        let roots = self
            .processes
            .get(&process)
            .ok_or(ProjectionError::MissingProcess {
                application,
                process,
            })?;
        if roots.is_empty() {
            return Err(ProjectionError::EmptyProcessRoots {
                application,
                process,
            });
        }
        let mut roots = roots.clone();
        roots.sort_unstable();

        let mut pending = VecDeque::new();
        let mut reached = BTreeMap::<ModuleId, IncludedModule>::new();
        let mut edges = Vec::<(ModuleId, ModuleId)>::new();
        let mut resolved_requirements = Vec::new();
        let mut resolved_contributions = Vec::new();
        for execution in &roots {
            let module = self.executions.get(execution).copied().ok_or(
                ProjectionError::MissingExecution {
                    application,
                    process,
                    execution: *execution,
                },
            )?;
            self.ensure_module(application, process, module)?;
            if self.exclusions.contains(&module) {
                return Err(ProjectionError::ExcludedRoot {
                    application,
                    process,
                    module,
                });
            }
            if let std::collections::btree_map::Entry::Vacant(entry) = reached.entry(module) {
                entry.insert(IncludedModule {
                    module,
                    path: vec![module],
                    reason: InclusionReason::ExecutionRoot {
                        execution: *execution,
                    },
                });
                pending.push_back(module);
            }
        }

        while let Some(consumer) = pending.pop_front() {
            let mut next = Vec::<(ModuleId, InclusionReason)>::new();
            for (capability, qualifier, optional) in
                requirements_by_owner.get(&consumer).into_iter().flatten()
            {
                let requirement_key = (consumer, *capability, *qualifier);
                let explicit = selections.get(&requirement_key).copied();
                let defaults = defaults.get(&requirement_key).cloned().unwrap_or_default();
                if explicit.is_none() && defaults.len() > 1 {
                    return Err(ProjectionError::AmbiguousProvider {
                        application,
                        process,
                        required_by: consumer,
                        capability: *capability,
                        qualifier: *qualifier,
                        candidates: defaults,
                    });
                }
                let selection = if explicit.is_some() {
                    ProviderSelection::Explicit
                } else if !defaults.is_empty() {
                    ProviderSelection::Default
                } else {
                    ProviderSelection::Unique
                };
                let selected = explicit.or_else(|| defaults.first().copied());
                let mut candidates = providers_by_capability
                    .get(&(*capability, *qualifier))
                    .cloned()
                    .unwrap_or_default();
                if let Some(chosen) = selected {
                    let provider = replacements
                        .get(&(*capability, *qualifier, chosen))
                        .copied()
                        .unwrap_or(chosen);
                    if self.exclusions.contains(&provider) {
                        return Err(ProjectionError::ExcludedProvider {
                            application,
                            process,
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            provider,
                        });
                    }
                    if (!candidates.contains(&chosen) && !candidates.contains(&provider))
                        || !providers_by_capability
                            .get(&(*capability, *qualifier))
                            .is_some_and(|providers| providers.contains(&provider))
                    {
                        return Err(ProjectionError::UnavailableProvider {
                            application,
                            process,
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            provider,
                        });
                    }
                    next.push((
                        provider,
                        InclusionReason::CapabilityProvider {
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            selection,
                            replaced: (provider != chosen).then_some(chosen),
                        },
                    ));
                    resolved_requirements.push(ResolvedRequirement {
                        consumer,
                        capability: *capability,
                        qualifier: *qualifier,
                        provider: Some(provider),
                        optional: *optional,
                        selection,
                        replaced: (provider != chosen).then_some(chosen),
                    });
                    continue;
                }
                if *optional {
                    resolved_requirements.push(ResolvedRequirement {
                        consumer,
                        capability: *capability,
                        qualifier: *qualifier,
                        provider: None,
                        optional: true,
                        selection: ProviderSelection::OptionalAbsent,
                        replaced: None,
                    });
                    continue;
                }
                for candidate in &mut candidates {
                    *candidate = replacements
                        .get(&(*capability, *qualifier, *candidate))
                        .copied()
                        .unwrap_or(*candidate);
                }
                if let Some(provider) = candidates.iter().find(|candidate| {
                    !providers_by_capability
                        .get(&(*capability, *qualifier))
                        .is_some_and(|providers| providers.contains(candidate))
                }) {
                    return Err(ProjectionError::UnavailableProvider {
                        application,
                        process,
                        required_by: consumer,
                        capability: *capability,
                        qualifier: *qualifier,
                        provider: *provider,
                    });
                }
                candidates.retain(|module| {
                    providers_by_capability
                        .get(&(*capability, *qualifier))
                        .is_some_and(|providers| providers.contains(module))
                });
                candidates.retain(|module| !self.exclusions.contains(module));
                candidates.sort_unstable();
                candidates.dedup();
                match candidates.as_slice() {
                    [] if providers_by_capability.contains_key(&(*capability, *qualifier)) => {
                        let provider = providers_by_capability[&(*capability, *qualifier)][0];
                        return Err(ProjectionError::ExcludedProvider {
                            application,
                            process,
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            provider,
                        });
                    }
                    [] => {
                        return Err(ProjectionError::MissingProvider {
                            application,
                            process,
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                        });
                    }
                    [provider] => {
                        let replaced = replacement_sources
                            .get(&(*capability, *qualifier, *provider))
                            .copied();
                        next.push((
                            *provider,
                            InclusionReason::CapabilityProvider {
                                required_by: consumer,
                                capability: *capability,
                                qualifier: *qualifier,
                                selection: ProviderSelection::Unique,
                                replaced,
                            },
                        ));
                        resolved_requirements.push(ResolvedRequirement {
                            consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            provider: Some(*provider),
                            optional: false,
                            selection: ProviderSelection::Unique,
                            replaced,
                        });
                    }
                    _ => {
                        return Err(ProjectionError::AmbiguousProvider {
                            application,
                            process,
                            required_by: consumer,
                            capability: *capability,
                            qualifier: *qualifier,
                            candidates,
                        });
                    }
                }
            }
            for (target, qualifier) in targets_by_owner.get(&consumer).into_iter().flatten() {
                for (contributor, contribution) in contributions_by_target
                    .get(&(*target, *qualifier))
                    .into_iter()
                    .flatten()
                {
                    resolved_contributions.push(ResolvedContribution {
                        consumer,
                        contributor: *contributor,
                        target: *target,
                        qualifier: *qualifier,
                        contribution: *contribution,
                    });
                    next.push((
                        *contributor,
                        InclusionReason::Contribution {
                            consumed_by: consumer,
                            target: *target,
                            qualifier: *qualifier,
                            contribution: *contribution,
                        },
                    ));
                }
            }
            next.sort_unstable();

            for (module, reason) in next {
                if self.exclusions.contains(&module) {
                    continue;
                }
                self.ensure_module(application, process, module)?;
                edges.push((consumer, module));
                if reached.contains_key(&module) {
                    continue;
                }
                let mut path = reached[&consumer].path.clone();
                path.push(module);
                reached.insert(
                    module,
                    IncludedModule {
                        module,
                        path,
                        reason,
                    },
                );
                pending.push_back(module);
            }
        }

        if let Some(path) = find_cycle(&edges) {
            return Err(ProjectionError::DependencyCycle {
                application,
                process,
                path,
            });
        }

        let included_set = reached.keys().copied().collect::<BTreeSet<_>>();
        for (contributor, target, qualifier, contribution, required) in &self.contributions {
            if *required && included_set.contains(contributor) {
                let consumed =
                    consumers_by_target
                        .get(&(*target, *qualifier))
                        .is_some_and(|consumers| {
                            consumers
                                .iter()
                                .any(|consumer| included_set.contains(consumer))
                        });
                if !consumed {
                    return Err(ProjectionError::OrphanContribution {
                        application,
                        process,
                        contributor: *contributor,
                        target: *target,
                        qualifier: *qualifier,
                        contribution: *contribution,
                    });
                }
            }
        }

        let included_modules = reached.into_values().collect::<Vec<_>>();
        let included_set = included_modules
            .iter()
            .map(|entry| entry.module)
            .collect::<BTreeSet<_>>();
        let excluded_modules = self.modules.difference(&included_set).copied().collect();
        let exclusions = self
            .modules
            .difference(&included_set)
            .map(|module| ExcludedModule {
                module: *module,
                reason: if self.exclusions.contains(module) {
                    ExclusionReason::Explicit
                } else {
                    ExclusionReason::Unreachable
                },
            })
            .collect();

        resolved_requirements.sort_unstable();
        resolved_contributions.sort_unstable();

        Ok(ProcessProjection {
            application,
            process,
            roots,
            included_modules,
            excluded_modules,
            exclusions,
            requirements: resolved_requirements,
            contributions: resolved_contributions,
        })
    }

    /// Resolves one process and consumes the mutable blueprint at the freeze boundary.
    pub fn freeze(self, process: ProcessId) -> Result<FrozenProcess, ProjectionError> {
        Ok(self.freeze_processes(&[process])?.remove(0))
    }

    /// Resolves selected processes from one blueprint and consumes it at freeze.
    pub fn freeze_processes(
        self,
        processes: &[ProcessId],
    ) -> Result<Vec<FrozenProcess>, ProjectionError> {
        processes
            .iter()
            .map(|process| self.project(*process).map(FrozenProcess::new))
            .collect()
    }

    fn ensure_module(
        &self,
        application: ApplicationId,
        process: ProcessId,
        module: ModuleId,
    ) -> Result<(), ProjectionError> {
        if self.modules.contains(&module) {
            Ok(())
        } else {
            Err(ProjectionError::MissingModule {
                application,
                process,
                module,
            })
        }
    }
}

fn find_cycle(edges: &[(ModuleId, ModuleId)]) -> Option<Vec<ModuleId>> {
    fn visit(
        node: ModuleId,
        graph: &BTreeMap<ModuleId, Vec<ModuleId>>,
        active: &mut Vec<ModuleId>,
        complete: &mut BTreeSet<ModuleId>,
    ) -> Option<Vec<ModuleId>> {
        if let Some(start) = active.iter().position(|candidate| *candidate == node) {
            let mut cycle = active[start..].to_vec();
            cycle.push(node);
            return Some(cycle);
        }
        if !complete.insert(node) {
            return None;
        }
        active.push(node);
        for next in graph.get(&node).into_iter().flatten() {
            if let Some(cycle) = visit(*next, graph, active, complete) {
                return Some(cycle);
            }
        }
        active.pop();
        None
    }

    let mut graph = BTreeMap::<ModuleId, Vec<ModuleId>>::new();
    for (from, to) in edges {
        graph.entry(*from).or_default().push(*to);
    }
    for neighbors in graph.values_mut() {
        neighbors.sort_unstable();
        neighbors.dedup();
    }
    let mut complete = BTreeSet::new();
    let mut active = Vec::new();
    for node in graph.keys().copied() {
        if let Some(cycle) = visit(node, &graph, &mut active, &mut complete) {
            return Some(cycle);
        }
    }
    None
}

/// Why a module is included in a process projection.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum InclusionReason {
    /// The module provides an execution root of the process.
    ExecutionRoot {
        /// The execution represented by the root.
        execution: ExecutionId,
    },
    /// The module provides a capability required by an included consumer.
    CapabilityProvider {
        /// The module requiring this provider.
        required_by: ModuleId,
        /// The required capability identity.
        capability: CapabilityId,
        /// The capability qualifier, if present.
        qualifier: Option<QualifierId>,
        /// How this provider was selected.
        selection: ProviderSelection,
        /// The original provider when this one replaced it.
        replaced: Option<ModuleId>,
    },
    /// The module contributes to a target consumed by an included module.
    Contribution {
        /// The module consuming the target.
        consumed_by: ModuleId,
        /// The consumed target identity.
        target: ContributionTargetId,
        /// The target qualifier.
        qualifier: QualifierId,
        /// The contribution kind identity.
        contribution: ContributionId,
    },
}

/// How a resolved provider was selected for a requirement.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum ProviderSelection {
    /// One provider uniquely matched the requirement.
    Unique,
    /// A declared default selected the provider.
    Default,
    /// An explicit selection overrode defaults or automatic choice.
    Explicit,
    /// The optional requirement was not activated.
    OptionalAbsent,
}

/// Why a declared module is absent from a process projection.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ExclusionReason {
    /// The blueprint explicitly excluded the module.
    Explicit,
    /// No selected root or relation reached the module.
    Unreachable,
}

/// An omitted module and its projection-specific exclusion reason.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ExcludedModule {
    module: ModuleId,
    reason: ExclusionReason,
}

impl ExcludedModule {
    /// Returns the omitted module identity.
    pub const fn module(&self) -> ModuleId {
        self.module
    }

    /// Returns why the module is absent.
    pub const fn reason(&self) -> ExclusionReason {
        self.reason
    }
}

/// A capability requirement and its selected provider in a process projection.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ResolvedRequirement {
    consumer: ModuleId,
    capability: CapabilityId,
    qualifier: Option<QualifierId>,
    provider: Option<ModuleId>,
    optional: bool,
    selection: ProviderSelection,
    replaced: Option<ModuleId>,
}

impl ResolvedRequirement {
    /// Returns the module that owns the requirement.
    pub const fn consumer(&self) -> ModuleId {
        self.consumer
    }
    /// Returns the required capability identity.
    pub const fn capability(&self) -> CapabilityId {
        self.capability
    }
    /// Returns the required qualifier, if any.
    pub const fn qualifier(&self) -> Option<QualifierId> {
        self.qualifier
    }
    /// Returns the selected provider, or `None` for an inactive optional requirement.
    pub const fn provider(&self) -> Option<ModuleId> {
        self.provider
    }
    /// Returns whether the declared requirement is optional.
    pub const fn optional(&self) -> bool {
        self.optional
    }
    /// Returns how the provider was selected.
    pub const fn selection(&self) -> ProviderSelection {
        self.selection
    }
    /// Returns the provider identity replaced by the selected provider, if any.
    pub const fn replaced_provider(&self) -> Option<ModuleId> {
        self.replaced
    }
}

/// A matching target contribution in the selected process projection.
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub struct ResolvedContribution {
    consumer: ModuleId,
    contributor: ModuleId,
    target: ContributionTargetId,
    qualifier: QualifierId,
    contribution: ContributionId,
}

impl ResolvedContribution {
    /// Returns the module consuming the target.
    pub const fn consumer(&self) -> ModuleId {
        self.consumer
    }
    /// Returns the contributing module.
    pub const fn contributor(&self) -> ModuleId {
        self.contributor
    }
    /// Returns the target identity.
    pub const fn target(&self) -> ContributionTargetId {
        self.target
    }
    /// Returns the target qualifier.
    pub const fn qualifier(&self) -> QualifierId {
        self.qualifier
    }
    /// Returns the contribution kind identity.
    pub const fn contribution(&self) -> ContributionId {
        self.contribution
    }
}

/// One reachable module and the deterministic path that made it reachable.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct IncludedModule {
    module: ModuleId,
    path: Vec<ModuleId>,
    reason: InclusionReason,
}

impl IncludedModule {
    /// Returns the included module identity.
    pub const fn module(&self) -> ModuleId {
        self.module
    }

    /// Returns the root-to-module inclusion path.
    pub fn path(&self) -> &[ModuleId] {
        &self.path
    }

    /// Returns the edge that included this module or the root execution.
    pub const fn reason(&self) -> InclusionReason {
        self.reason
    }
}

/// A derived process projection. Its private structure cannot be mutated.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ProcessProjection {
    application: ApplicationId,
    process: ProcessId,
    roots: Vec<ExecutionId>,
    included_modules: Vec<IncludedModule>,
    excluded_modules: Vec<ModuleId>,
    exclusions: Vec<ExcludedModule>,
    requirements: Vec<ResolvedRequirement>,
    contributions: Vec<ResolvedContribution>,
}

impl ProcessProjection {
    /// Returns the application blueprint identity.
    pub const fn application(&self) -> ApplicationId {
        self.application
    }

    /// Returns the selected process identity.
    pub const fn process(&self) -> ProcessId {
        self.process
    }

    /// Returns the process's execution roots.
    pub fn roots(&self) -> &[ExecutionId] {
        &self.roots
    }

    /// Returns reachable modules with provenance paths.
    pub fn included_modules(&self) -> &[IncludedModule] {
        &self.included_modules
    }

    /// Returns declared modules excluded from this process projection.
    pub fn excluded_modules(&self) -> &[ModuleId] {
        &self.excluded_modules
    }

    /// Returns omitted modules with their exclusion reasons.
    pub fn exclusions(&self) -> &[ExcludedModule] {
        &self.exclusions
    }

    /// Returns requirements resolved for included modules.
    pub fn requirements(&self) -> &[ResolvedRequirement] {
        &self.requirements
    }

    /// Returns consumed contributions in this process projection.
    pub fn contributions(&self) -> &[ResolvedContribution] {
        &self.contributions
    }

    /// Returns whether a module is reachable in this projection.
    pub fn includes(&self, module: ModuleId) -> bool {
        self.included_modules
            .iter()
            .any(|entry| entry.module == module)
    }
}

/// Compact structural input for initializing a selected runtime.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RuntimeProjection {
    modules: Vec<ModuleId>,
    contributions: Vec<ResolvedContribution>,
}

impl RuntimeProjection {
    /// Returns the selected module identities in deterministic order.
    pub fn modules(&self) -> &[ModuleId] {
        &self.modules
    }

    /// Returns target contribution work assigned to the consuming modules.
    pub fn contributions(&self) -> &[ResolvedContribution] {
        &self.contributions
    }
}

/// A structurally immutable projection produced at the composition freeze boundary.
///
/// ```compile_fail
/// use rustclamp_core::ModuleId;
/// use rustclamp_kernel::FrozenProcess;
/// fn mutate(frozen: &mut FrozenProcess) {
///     frozen.add_module(ModuleId::new("late.module"));
/// }
/// ```
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FrozenProcess {
    runtime: RuntimeProjection,
    inspection: ProcessProjection,
}

impl FrozenProcess {
    fn new(inspection: ProcessProjection) -> Self {
        let runtime = RuntimeProjection {
            modules: inspection
                .included_modules()
                .iter()
                .map(IncludedModule::module)
                .collect(),
            contributions: inspection.contributions.clone(),
        };
        Self {
            runtime,
            inspection,
        }
    }

    /// Returns the compact runtime projection derived from the resolved model.
    pub const fn runtime(&self) -> &RuntimeProjection {
        &self.runtime
    }

    /// Returns immutable resolution metadata for inspection.
    pub const fn inspection(&self) -> &ProcessProjection {
        &self.inspection
    }

    /// Resolves `consumer`'s unqualified requirement for `C` to the value of the
    /// provider this process selected at freeze time.
    ///
    /// The blueprint stays the single declaration of the edge: the caller supplies
    /// only the constructed values. An undeclared or inactive optional requirement
    /// fails with [`CompositionErrorKind::UndeclaredRequirement`]; a selected provider
    /// missing from `provisions` fails with
    /// [`CompositionErrorKind::ProviderSelectionUnavailable`].
    pub fn resolve<'value, C: Capability>(
        &self,
        consumer: ModuleId,
        provisions: &[Provision<'value, C>],
    ) -> Result<&'value C::Value, CompositionError> {
        self.resolve_frozen(
            consumer,
            C::ID,
            provisions
                .iter()
                .map(|provision| (provision.module, provision.value)),
            provisions.len(),
        )
    }

    /// Like [`FrozenProcess::resolve`], but returns an owned [`Arc`] handle.
    ///
    /// The value can outlive the provisions slice and be moved into `'static`
    /// state (a server, a spawned task) without `Box::leak`.
    pub fn resolve_shared<C: Capability>(
        &self,
        consumer: ModuleId,
        provisions: &[SharedProvision<C>],
    ) -> Result<Arc<C::Value>, CompositionError> {
        self.resolve_frozen(
            consumer,
            C::ID,
            provisions
                .iter()
                .map(|provision| (provision.module, &provision.value)),
            provisions.len(),
        )
        .map(Arc::clone)
    }

    /// Builds the value of the provider this process selected, after freeze.
    ///
    /// Only the selected provider's factory runs, so a provider whose
    /// construction can fail (opening a database) is built once, and only when
    /// the frozen process actually uses it. A factory failure is returned as
    /// [`FactoryError::Build`].
    pub fn resolve_with<C: Capability, E>(
        &self,
        consumer: ModuleId,
        provisions: Vec<FactoryProvision<C, E>>,
    ) -> Result<Arc<C::Value>, FactoryError<E>> {
        let selected = self
            .resolve_frozen(
                consumer,
                C::ID,
                provisions
                    .iter()
                    .map(|provision| (provision.module, provision)),
                provisions.len(),
            )
            .map_err(FactoryError::Composition)?
            .module;
        let provision = provisions
            .into_iter()
            .find(|provision| provision.module == selected)
            .expect("selected provision is among the candidates");
        (provision.factory)().map_err(FactoryError::Build)
    }

    fn resolve_frozen<'value, V: ?Sized + 'value>(
        &self,
        consumer: ModuleId,
        capability: CapabilityId,
        provisions: impl Iterator<Item = (ModuleId, &'value V)> + Clone,
        count: usize,
    ) -> Result<&'value V, CompositionError> {
        // ponytail: unqualified only; add resolve_qualified when a process needs it.
        let provider = self
            .inspection
            .requirements()
            .iter()
            .find(|requirement| {
                requirement.consumer == consumer
                    && requirement.capability == capability
                    && requirement.qualifier.is_none()
            })
            .and_then(|requirement| requirement.provider);
        match provider {
            Some(provider) => Resolver::resolve_candidates(
                consumer,
                capability,
                None,
                provisions,
                count,
                Some(provider),
            ),
            None => Err(Resolver::error(
                CompositionErrorKind::UndeclaredRequirement,
                consumer,
                capability,
                None,
                provisions,
            )),
        }
    }

    /// Builds target `T` (qualifier `Q`) from the contributions this process selected.
    ///
    /// The blueprint's `add_contribution` edges stay the single declaration:
    /// contributions from modules outside this process are dropped, and the rest
    /// must match the frozen edges exactly — an included module supplying an
    /// undeclared contribution, or a declared contributor supplying none, fails.
    pub fn compose<T: ContributionTarget, Q: Qualifier>(
        &self,
        target: &T,
        contributions: Vec<(ModuleId, T::Contribution)>,
    ) -> Result<T::Runtime, ComposeError<T::Error>> {
        self.compose_qualified(target, Q::ID, contributions)
    }

    /// [`compose`](Self::compose), with the qualifier read from the blueprint's
    /// `add_contribution` edges for `T` instead of named again by the caller.
    ///
    /// Fails with [`ComposeError::AmbiguousQualifier`] when this process has
    /// edges into `T` under more than one qualifier, or none: name it with
    /// `compose::<T, Q>` then.
    pub fn compose_inferred<T: ContributionTarget>(
        &self,
        target: &T,
        contributions: Vec<(ModuleId, T::Contribution)>,
    ) -> Result<T::Runtime, ComposeError<T::Error>> {
        let qualifiers = self
            .inspection
            .contributions()
            .iter()
            .filter(|edge| edge.target == T::ID && edge.contribution == T::Contribution::ID)
            .map(|edge| edge.qualifier)
            .collect::<BTreeSet<_>>();
        match qualifiers.len() {
            1 => {
                let qualifier = *qualifiers.first().expect("one qualifier");
                self.compose_qualified(target, qualifier, contributions)
            }
            _ => Err(ComposeError::AmbiguousQualifier {
                target: T::ID,
                qualifiers: qualifiers.into_iter().collect(),
            }),
        }
    }

    fn compose_qualified<T: ContributionTarget>(
        &self,
        target: &T,
        qualifier: QualifierId,
        contributions: Vec<(ModuleId, T::Contribution)>,
    ) -> Result<T::Runtime, ComposeError<T::Error>> {
        let declared = self
            .inspection
            .contributions()
            .iter()
            .filter(|edge| {
                edge.target == T::ID
                    && edge.qualifier == qualifier
                    && edge.contribution == T::Contribution::ID
            })
            .map(|edge| edge.contributor)
            .collect::<BTreeSet<_>>();
        let selected = contributions
            .into_iter()
            .filter(|(module, _)| self.inspection.includes(*module))
            .collect::<Vec<_>>();
        if let Some((module, _)) = selected
            .iter()
            .find(|(module, _)| !declared.contains(module))
        {
            return Err(ComposeError::UndeclaredContribution {
                target: T::ID,
                qualifier,
                contributor: *module,
            });
        }
        if let Some(module) = declared
            .iter()
            .find(|declared| !selected.iter().any(|(module, _)| module == *declared))
        {
            return Err(ComposeError::MissingContribution {
                target: T::ID,
                qualifier,
                contributor: *module,
            });
        }
        target.build(&selected).map_err(ComposeError::Target)
    }
}

/// A structured failure while deriving a selected process projection.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ProjectionError {
    /// The application has no declaration for the requested process.
    MissingProcess {
        /// The application identity.
        application: ApplicationId,
        /// The requested process identity.
        process: ProcessId,
    },
    /// The process is declared without an execution root.
    EmptyProcessRoots {
        /// The application identity.
        application: ApplicationId,
        /// The process identity with no roots.
        process: ProcessId,
    },
    /// A process root refers to an undeclared execution.
    MissingExecution {
        /// The application identity.
        application: ApplicationId,
        /// The selected process identity.
        process: ProcessId,
        /// The undeclared root execution.
        execution: ExecutionId,
    },
    /// A root or reachable edge refers to an undeclared module.
    MissingModule {
        /// The application identity.
        application: ApplicationId,
        /// The selected process identity.
        process: ProcessId,
        /// The undeclared module identity.
        module: ModuleId,
    },
    /// An included required capability has no provider.
    MissingProvider {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Requiring module.
        required_by: ModuleId,
        /// Required capability.
        capability: CapabilityId,
        /// Required qualifier, if any.
        qualifier: Option<QualifierId>,
    },
    /// An included requirement has multiple providers without an explicit selection.
    AmbiguousProvider {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Requiring module.
        required_by: ModuleId,
        /// Required capability.
        capability: CapabilityId,
        /// Required qualifier, if any.
        qualifier: Option<QualifierId>,
        /// Sorted matching provider modules.
        candidates: Vec<ModuleId>,
    },
    /// A selected provider is not declared for the requirement.
    UnavailableProvider {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Requiring module.
        required_by: ModuleId,
        /// Required capability.
        capability: CapabilityId,
        /// Required qualifier, if any.
        qualifier: Option<QualifierId>,
        /// Selected provider module.
        provider: ModuleId,
    },
    /// An included requirement selected an excluded provider.
    ExcludedProvider {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Requiring module.
        required_by: ModuleId,
        /// Required capability.
        capability: CapabilityId,
        /// Required qualifier, if any.
        qualifier: Option<QualifierId>,
        /// Excluded provider module.
        provider: ModuleId,
    },
    /// An execution root was explicitly excluded.
    ExcludedRoot {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Excluded root module.
        module: ModuleId,
    },
    /// A cycle exists in the selected process dependency graph.
    DependencyCycle {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Closed cycle path, with the first module repeated at the end.
        path: Vec<ModuleId>,
    },
    /// A reachable module declares a required contribution without a consumer.
    OrphanContribution {
        /// Application identity.
        application: ApplicationId,
        /// Projected process identity.
        process: ProcessId,
        /// Module declaring the contribution.
        contributor: ModuleId,
        /// Contribution target identity.
        target: ContributionTargetId,
        /// Contribution target qualifier.
        qualifier: QualifierId,
        /// Contribution kind identity.
        contribution: ContributionId,
    },
}

impl fmt::Display for ProjectionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let (application, process) = match self {
            Self::MissingProcess {
                application,
                process,
                ..
            }
            | Self::EmptyProcessRoots {
                application,
                process,
                ..
            }
            | Self::MissingExecution {
                application,
                process,
                ..
            }
            | Self::MissingModule {
                application,
                process,
                ..
            }
            | Self::MissingProvider {
                application,
                process,
                ..
            }
            | Self::AmbiguousProvider {
                application,
                process,
                ..
            }
            | Self::UnavailableProvider {
                application,
                process,
                ..
            }
            | Self::ExcludedProvider {
                application,
                process,
                ..
            }
            | Self::ExcludedRoot {
                application,
                process,
                ..
            }
            | Self::DependencyCycle {
                application,
                process,
                ..
            }
            | Self::OrphanContribution {
                application,
                process,
                ..
            } => (application.as_str(), process.as_str()),
        };
        write!(formatter, "process '{application}/{process}': ")?;
        match self {
            Self::MissingProcess { .. } => formatter.write_str("process is not declared"),
            Self::EmptyProcessRoots { .. } => formatter.write_str("process has no execution root"),
            Self::MissingExecution { execution, .. } => {
                write!(
                    formatter,
                    "execution '{}' is not declared",
                    execution.as_str()
                )
            }
            Self::MissingModule { module, .. } => {
                write!(formatter, "module '{}' is not declared", module.as_str())
            }
            Self::MissingProvider {
                required_by,
                capability,
                qualifier,
                ..
            } => {
                write!(
                    formatter,
                    "no provider for capability '{}'{} required by module '{}'",
                    capability.as_str(),
                    Qualified(*qualifier),
                    required_by.as_str()
                )
            }
            Self::AmbiguousProvider {
                required_by,
                capability,
                qualifier,
                candidates,
                ..
            } => {
                write!(
                    formatter,
                    "ambiguous providers for capability '{}'{} required by module '{}': {}",
                    capability.as_str(),
                    Qualified(*qualifier),
                    required_by.as_str(),
                    candidates
                        .iter()
                        .map(|module| module.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )
            }
            Self::UnavailableProvider {
                required_by,
                capability,
                qualifier,
                provider,
                ..
            } => {
                write!(
                    formatter,
                    "selected provider '{}' does not provide capability '{}'{} required by module '{}'",
                    provider.as_str(),
                    capability.as_str(),
                    Qualified(*qualifier),
                    required_by.as_str()
                )
            }
            Self::ExcludedProvider {
                required_by,
                capability,
                qualifier,
                provider,
                ..
            } => {
                write!(
                    formatter,
                    "selected provider '{}' for capability '{}'{} required by module '{}' is excluded",
                    provider.as_str(),
                    capability.as_str(),
                    Qualified(*qualifier),
                    required_by.as_str()
                )
            }
            Self::ExcludedRoot { module, .. } => {
                write!(formatter, "root module '{}' is excluded", module.as_str())
            }
            Self::DependencyCycle { path, .. } => {
                write!(
                    formatter,
                    "dependency cycle: {}",
                    path.iter()
                        .map(|module| module.as_str())
                        .collect::<Vec<_>>()
                        .join(" -> ")
                )
            }
            Self::OrphanContribution {
                contributor,
                target,
                qualifier,
                contribution,
                ..
            } => {
                write!(
                    formatter,
                    "required contribution '{}' from module '{}' has no consumer for target '{}' qualified as '{}'",
                    contribution.as_str(),
                    contributor.as_str(),
                    target.as_str(),
                    qualifier.as_str()
                )
            }
        }
    }
}

impl Error for ProjectionError {}

/// Renders an optional qualifier suffix in diagnostics.
struct Qualified(Option<QualifierId>);

impl fmt::Display for Qualified {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0 {
            Some(qualifier) => write!(formatter, " qualified as '{}'", qualifier.as_str()),
            None => Ok(()),
        }
    }
}

/// Caller-owned declarations for one typed contribution target and qualifier.
pub struct TargetComposition<T: ContributionTarget, Q: Qualifier> {
    contributions: Vec<(ModuleId, T::Contribution)>,
    target: PhantomData<(T, Q)>,
}

impl<T: ContributionTarget, Q: Qualifier> TargetComposition<T, Q> {
    /// Creates a target composition from contributor identities and declarations.
    pub fn new(contributions: Vec<(ModuleId, T::Contribution)>) -> Self {
        Self {
            contributions,
            target: PhantomData,
        }
    }

    /// Consumes declarations into the selected target's runtime form.
    ///
    /// If no target is selected, required declarations produce a structured
    /// unconsumed-contribution error. Optional declarations are discarded. An
    /// empty composition without a target is a no-op.
    pub fn build(
        self,
        target: Option<&T>,
    ) -> Result<Option<T::Runtime>, TargetCompositionError<T::Error>> {
        let Some(target) = target else {
            let mut contributors = self
                .contributions
                .iter()
                .filter(|_| T::Contribution::REQUIRED)
                .map(|(module, _)| *module)
                .collect::<Vec<_>>();
            if contributors.is_empty() {
                return Ok(None);
            }
            contributors.sort_unstable();
            return Err(TargetCompositionError::UnconsumedRequired {
                target: T::ID,
                contribution: T::Contribution::ID,
                qualifier: Q::ID,
                contributors,
            });
        };

        target
            .build(&self.contributions)
            .map(Some)
            .map_err(TargetCompositionError::Target)
    }
}

/// A target-owned build failure or an unconsumed required declaration.
#[derive(Debug, Eq, PartialEq)]
pub enum TargetCompositionError<E> {
    /// The active composition has required declarations but no matching target.
    UnconsumedRequired {
        /// The target that was expected to consume the declarations.
        target: ContributionTargetId,
        /// The contribution kind that was left unconsumed.
        contribution: ContributionId,
        /// The qualifier whose active composition contains the declarations.
        qualifier: QualifierId,
        /// Modules that contributed required declarations.
        contributors: Vec<ModuleId>,
    },
    /// The selected target rejected the declarations.
    Target(E),
}

impl<E: fmt::Display> fmt::Display for TargetCompositionError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnconsumedRequired {
                target,
                contribution,
                qualifier,
                contributors,
            } => write!(
                formatter,
                "required contribution '{}' qualified as '{}' has no target '{}'; contributors: {}",
                contribution.as_str(),
                qualifier.as_str(),
                target.as_str(),
                contributors
                    .iter()
                    .map(|module| module.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Target(error) => write!(formatter, "target rejected declarations: {error}"),
        }
    }
}

impl<E: Error + 'static> Error for TargetCompositionError<E> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Target(error) => Some(error),
            Self::UnconsumedRequired { .. } => None,
        }
    }
}

/// A mismatch between supplied contributions and the frozen process, or a target failure.
#[derive(Debug, Eq, PartialEq)]
pub enum ComposeError<E> {
    /// An included module supplied a contribution the frozen process does not declare.
    UndeclaredContribution {
        /// The target being composed.
        target: ContributionTargetId,
        /// The target qualifier.
        qualifier: QualifierId,
        /// The module whose contribution has no blueprint edge.
        contributor: ModuleId,
    },
    /// A contributor declared in the frozen process supplied no contribution.
    MissingContribution {
        /// The target being composed.
        target: ContributionTargetId,
        /// The target qualifier.
        qualifier: QualifierId,
        /// The declared module that supplied nothing.
        contributor: ModuleId,
    },
    /// [`FrozenProcess::compose_inferred`] found edges into the target under
    /// several qualifiers, or none, so it cannot pick one.
    AmbiguousQualifier {
        /// The target being composed.
        target: ContributionTargetId,
        /// The qualifiers the process's edges use, sorted; empty for none.
        qualifiers: Vec<QualifierId>,
    },
    /// The target rejected the selected contributions.
    Target(E),
}

impl<E: fmt::Display> fmt::Display for ComposeError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UndeclaredContribution {
                target,
                qualifier,
                contributor,
            } => write!(
                formatter,
                "module '{}' contributes to target '{}' qualified as '{}' without a blueprint edge in this process",
                contributor.as_str(),
                target.as_str(),
                qualifier.as_str()
            ),
            Self::MissingContribution {
                target,
                qualifier,
                contributor,
            } => write!(
                formatter,
                "module '{}' is declared to contribute to target '{}' qualified as '{}' but supplied nothing",
                contributor.as_str(),
                target.as_str(),
                qualifier.as_str()
            ),
            Self::AmbiguousQualifier { target, qualifiers } if qualifiers.is_empty() => write!(
                formatter,
                "target '{}' has no contribution edges in this process to infer a qualifier from",
                target.as_str()
            ),
            Self::AmbiguousQualifier { target, qualifiers } => write!(
                formatter,
                "target '{}' is contributed to under several qualifiers ({}); name one with compose::<T, Q>",
                target.as_str(),
                qualifiers
                    .iter()
                    .map(|qualifier| qualifier.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
            Self::Target(error) => write!(formatter, "target rejected contributions: {error}"),
        }
    }
}

impl<E: Error + 'static> Error for ComposeError<E> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Target(error) => Some(error),
            Self::UndeclaredContribution { .. }
            | Self::MissingContribution { .. }
            | Self::AmbiguousQualifier { .. } => None,
        }
    }
}

/// A capability implementation associated with the module that supplies it.
///
/// This is a graph relationship, not a provider base class. The value may be
/// borrowed from an object owned and constructed by the application.
pub struct Provision<'a, C: Capability> {
    module: ModuleId,
    value: &'a C::Value,
}

impl<'a, C: Capability> Provision<'a, C> {
    /// Associates a module identity with a value implementing capability `C`.
    pub fn new(module: ModuleId, value: &'a C::Value) -> Self {
        Self { module, value }
    }

    /// Creates a provision from a module's additive [`Provides`] contract.
    pub fn from_module<M: Provides<C>>(module: &'a M) -> Self {
        Self::new(<M as Module>::ID, module.provided_value())
    }

    /// Returns the module identity associated with this provision.
    pub const fn module(&self) -> ModuleId {
        self.module
    }

    /// Returns the provided capability value.
    pub const fn value(&self) -> &'a C::Value {
        self.value
    }
}

/// A capability value owned through an [`Arc`], with no borrow to keep alive.
///
/// Use with [`FrozenProcess::resolve_shared`] when the resolved value must be
/// `'static` (shared state, spawned tasks).
pub struct SharedProvision<C: Capability> {
    module: ModuleId,
    value: Arc<C::Value>,
}

impl<C: Capability> SharedProvision<C> {
    /// Associates a module identity with a shared value implementing capability `C`.
    pub fn new(module: ModuleId, value: Arc<C::Value>) -> Self {
        Self { module, value }
    }

    /// Returns the module identity associated with this provision.
    pub const fn module(&self) -> ModuleId {
        self.module
    }
}

/// A capability provision built on demand, for values whose construction can fail.
///
/// The factory runs only if [`FrozenProcess::resolve_with`] selects this module.
pub struct FactoryProvision<C: Capability, E> {
    module: ModuleId,
    factory: Box<dyn FnOnce() -> Result<Arc<C::Value>, E>>,
}

impl<C: Capability, E> FactoryProvision<C, E> {
    /// Associates a module identity with a factory for capability `C`.
    pub fn new(
        module: ModuleId,
        factory: impl FnOnce() -> Result<Arc<C::Value>, E> + 'static,
    ) -> Self {
        Self {
            module,
            factory: Box::new(factory),
        }
    }

    /// Returns the module identity associated with this provision.
    pub const fn module(&self) -> ModuleId {
        self.module
    }
}

/// Why [`FrozenProcess::resolve_with`] failed.
#[derive(Debug, Eq, PartialEq)]
pub enum FactoryError<E> {
    /// The provider could not be selected.
    Composition(CompositionError),
    /// The selected provider's factory failed.
    Build(E),
}

impl<E: fmt::Display> fmt::Display for FactoryError<E> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Composition(error) => error.fmt(formatter),
            Self::Build(error) => error.fmt(formatter),
        }
    }
}

impl<E: Error + 'static> Error for FactoryError<E> {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Composition(error) => Some(error),
            Self::Build(error) => Some(error),
        }
    }
}

/// One module's requirement for a single typed capability.
pub struct CapabilityRequirement<C: Capability> {
    required_by: ModuleId,
    selected: Option<ModuleId>,
    capability: PhantomData<C>,
}

impl<C: Capability> Copy for CapabilityRequirement<C> {}

impl<C: Capability> Clone for CapabilityRequirement<C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<C: Capability> CapabilityRequirement<C> {
    /// Declares a requirement with an optional explicit provider selection.
    pub const fn new(required_by: ModuleId, selected: Option<ModuleId>) -> Self {
        Self {
            required_by,
            selected,
            capability: PhantomData,
        }
    }

    /// Creates a requirement from a module's additive [`Requires`] contract.
    pub fn from_module<M: Requires<C>>() -> Self {
        Self::new(<M as Module>::ID, M::SELECTED_PROVIDER)
    }

    /// Returns the module that owns this requirement.
    pub const fn required_by(self) -> ModuleId {
        self.required_by
    }

    /// Returns the explicitly selected provider, if one was declared.
    pub const fn selected_provider(self) -> Option<ModuleId> {
        self.selected
    }
}

/// A caller-owned, single-capability composition snapshot.
///
/// This prototype stores declarations only; it does not construct modules or
/// keep global state. Edits return a new snapshot so callers can validate the
/// resulting graph before adopting it.
pub struct CapabilityComposition<'a, C: Capability> {
    provisions: Vec<Provision<'a, C>>,
    requirements: Vec<CapabilityRequirement<C>>,
}

impl<'a, C: Capability> CapabilityComposition<'a, C> {
    /// Creates a composition snapshot from providers and consumer requirements.
    pub fn new(
        provisions: Vec<Provision<'a, C>>,
        requirements: Vec<CapabilityRequirement<C>>,
    ) -> Self {
        Self {
            provisions,
            requirements,
        }
    }

    /// Removes a module's declarations and revalidates the remaining graph.
    ///
    /// Requirements owned by other modules remain, even when the removed module
    /// was their selected provider; validation then reports the broken edge.
    pub fn without_module(&self, module: ModuleId) -> Self {
        Self {
            provisions: self
                .provisions
                .iter()
                .filter(|provision| provision.module != module)
                .map(|provision| Provision::new(provision.module, provision.value))
                .collect(),
            requirements: self
                .requirements
                .iter()
                .copied()
                .filter(|requirement| requirement.required_by != module)
                .collect(),
        }
    }

    /// Returns the active consumer requirements in this snapshot.
    pub fn requirements(&self) -> &[CapabilityRequirement<C>] {
        &self.requirements
    }

    /// Replaces one provider for this capability while retaining module
    /// requirements and redirecting explicit selections to the replacement.
    /// Returns `None` when `replaced` does not currently provide this capability.
    pub fn replace_provider(
        &self,
        replaced: ModuleId,
        replacement: Provision<'a, C>,
    ) -> Option<Self> {
        if !self
            .provisions
            .iter()
            .any(|provision| provision.module == replaced)
        {
            return None;
        }

        let mut provisions = self
            .provisions
            .iter()
            .filter(|provision| provision.module != replaced)
            .map(|provision| Provision::new(provision.module, provision.value))
            .collect::<Vec<_>>();
        let replacement_module = replacement.module;
        provisions.push(replacement);
        let requirements = self
            .requirements
            .iter()
            .map(|requirement| {
                CapabilityRequirement::new(
                    requirement.required_by,
                    (requirement.selected == Some(replaced))
                        .then_some(replacement_module)
                        .or(requirement.selected),
                )
            })
            .collect();

        Some(Self::new(provisions, requirements))
    }

    /// Resolves one declared requirement against this snapshot.
    pub fn resolve_requirement(
        &self,
        requirement: CapabilityRequirement<C>,
    ) -> Result<&'a C::Value, CompositionError> {
        Resolver::resolve::<C>(
            requirement.required_by,
            &self.provisions,
            requirement.selected,
        )
    }

    /// Revalidates every consumer requirement in this snapshot.
    pub fn validate(&self) -> Result<(), CompositionError> {
        for requirement in &self.requirements {
            self.resolve_requirement(*requirement)?;
        }
        Ok(())
    }
}

/// A capability provision distinguished by a compile-time qualifier type.
pub struct QualifiedProvision<'a, C: Capability, Q: Qualifier> {
    module: ModuleId,
    value: &'a C::Value,
    qualifier: PhantomData<Q>,
}

impl<'a, C: Capability, Q: Qualifier> QualifiedProvision<'a, C, Q> {
    /// Associates a module and a typed qualifier with a capability value.
    pub fn new(module: ModuleId, value: &'a C::Value) -> Self {
        Self {
            module,
            value,
            qualifier: PhantomData,
        }
    }

    /// Returns the module identity associated with this provision.
    pub const fn module(&self) -> ModuleId {
        self.module
    }
}

/// The structured category of a capability composition failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum CompositionErrorKind {
    /// No module provides a required capability.
    MissingProvider,
    /// More than one module provides the capability and none was selected.
    AmbiguousProviders,
    /// The selected module is not among the available provisions.
    ProviderSelectionUnavailable,
    /// The frozen process has no active requirement for this consumer and capability.
    UndeclaredRequirement,
}

/// A composition failure with stable identities and candidate context.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompositionError {
    kind: CompositionErrorKind,
    required_by: ModuleId,
    capability: CapabilityId,
    qualifier: Option<QualifierId>,
    candidates: Vec<ModuleId>,
}

impl CompositionError {
    fn new(
        kind: CompositionErrorKind,
        required_by: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        candidates: Vec<ModuleId>,
    ) -> Self {
        Self {
            kind,
            required_by,
            capability,
            qualifier,
            candidates,
        }
    }

    /// Returns the structured failure category.
    pub const fn kind(&self) -> CompositionErrorKind {
        self.kind
    }

    /// Returns the module whose requirement could not be resolved.
    pub const fn required_by(&self) -> ModuleId {
        self.required_by
    }

    /// Returns the stable identity of the missing or ambiguous capability.
    pub const fn capability(&self) -> CapabilityId {
        self.capability
    }

    /// Returns the qualifier identity when the failed requirement was qualified.
    pub const fn qualifier(&self) -> Option<QualifierId> {
        self.qualifier
    }

    /// Returns candidate module identities in stable sorted order.
    pub fn candidates(&self) -> &[ModuleId] {
        &self.candidates
    }
}

impl fmt::Display for CompositionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{:?} for capability '{}' required by module '{}'",
            self.kind,
            self.capability.as_str(),
            self.required_by.as_str()
        )?;
        if let Some(qualifier) = self.qualifier {
            write!(formatter, " qualified as '{}'", qualifier.as_str())?;
        }
        if !self.candidates.is_empty() {
            formatter.write_str("; candidates: ")?;
            for (index, candidate) in self.candidates.iter().enumerate() {
                if index > 0 {
                    formatter.write_str(", ")?;
                }
                formatter.write_str(candidate.as_str())?;
            }
        }
        Ok(())
    }
}

impl Error for CompositionError {}

/// A directed construction dependency from a module to a module it needs.
///
/// An edge `consumer -> dependency` means the dependency must be constructed
/// before the consumer. The graph only validates construction order; it does
/// not construct modules or support lazy/proxy edges.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ConstructionDependency {
    consumer: ModuleId,
    dependency: ModuleId,
}

impl ConstructionDependency {
    /// Declares that `consumer` requires `dependency` during construction.
    pub const fn new(consumer: ModuleId, dependency: ModuleId) -> Self {
        Self {
            consumer,
            dependency,
        }
    }

    /// Returns the module that has the dependency.
    pub const fn consumer(self) -> ModuleId {
        self.consumer
    }

    /// Returns the module required during construction.
    pub const fn dependency(self) -> ModuleId {
        self.dependency
    }
}

/// A caller-owned set of construction dependencies for cycle validation.
#[derive(Clone, Debug, Default)]
pub struct ConstructionGraph {
    dependencies: Vec<ConstructionDependency>,
}

impl ConstructionGraph {
    /// Creates a graph from module-to-module construction dependencies.
    pub fn new(dependencies: Vec<ConstructionDependency>) -> Self {
        Self { dependencies }
    }

    /// Returns the declared construction dependencies.
    pub fn dependencies(&self) -> &[ConstructionDependency] {
        &self.dependencies
    }

    /// Rejects a construction cycle and returns its closed module path.
    ///
    /// For example, `A -> B -> C -> A` reports `[A, B, C, A]`. Traversal is
    /// sorted by stable module identity, so the selected diagnostic is
    /// independent of dependency registration order.
    pub fn validate(&self) -> Result<(), ConstructionCycle> {
        let mut adjacency = BTreeMap::<ModuleId, Vec<ModuleId>>::new();
        for edge in &self.dependencies {
            adjacency
                .entry(edge.consumer)
                .or_default()
                .push(edge.dependency);
            adjacency.entry(edge.dependency).or_default();
        }

        // Deduplicate and sort once so traversal and diagnostics are stable.
        for dependencies in adjacency.values_mut() {
            dependencies.sort_unstable();
            dependencies.dedup();
        }

        let mut states = BTreeMap::<ModuleId, VisitState>::new();
        let mut path = Vec::new();
        for module in adjacency.keys().copied() {
            if states
                .get(&module)
                .copied()
                .unwrap_or(VisitState::Unvisited)
                == VisitState::Unvisited
            {
                states.insert(module, VisitState::Visiting);
                path.push(module);
                let mut stack = vec![(module, 0usize)];

                while let Some((current, next_index)) = stack.last_mut() {
                    let dependencies = &adjacency[current];
                    if *next_index == dependencies.len() {
                        let (finished, _) = stack.pop().expect("stack is non-empty");
                        path.pop();
                        states.insert(finished, VisitState::Visited);
                        continue;
                    }

                    let dependency = dependencies[*next_index];
                    *next_index += 1;
                    match states
                        .get(&dependency)
                        .copied()
                        .unwrap_or(VisitState::Unvisited)
                    {
                        VisitState::Unvisited => {
                            states.insert(dependency, VisitState::Visiting);
                            path.push(dependency);
                            stack.push((dependency, 0));
                        }
                        VisitState::Visiting => {
                            let start = path
                                .iter()
                                .position(|item| *item == dependency)
                                .expect("visiting modules are in the active path");
                            let mut cycle = path[start..].to_vec();
                            cycle.push(dependency);
                            return Err(ConstructionCycle { path: cycle });
                        }
                        VisitState::Visited => {}
                    }
                }
            }
        }
        Ok(())
    }
}

#[derive(Clone, Copy, Eq, PartialEq)]
enum VisitState {
    Unvisited,
    Visiting,
    Visited,
}

/// A construction cycle with the repeated start module closing its path.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ConstructionCycle {
    path: Vec<ModuleId>,
}

impl ConstructionCycle {
    /// Returns the dependency path, including the repeated start module.
    pub fn path(&self) -> &[ModuleId] {
        &self.path
    }
}

impl fmt::Display for ConstructionCycle {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str("construction cycle: ")?;
        for (index, module) in self.path.iter().enumerate() {
            if index > 0 {
                formatter.write_str(" -> ")?;
            }
            formatter.write_str(module.as_str())?;
        }
        Ok(())
    }
}

impl Error for ConstructionCycle {}

/// Resolves one typed requirement from the provisions declared for it.
pub struct Resolver;

impl Resolver {
    /// Resolves a unique provision, or the provision named by `selected`.
    ///
    /// Registration order never selects a winner. Multiple candidates without
    /// explicit selection produce a structured ambiguity error. No global
    /// registry, runtime type map, or allocation is needed on the success path.
    pub fn resolve<'value, C: Capability>(
        required_by: ModuleId,
        provisions: &[Provision<'value, C>],
        selected: Option<ModuleId>,
    ) -> Result<&'value C::Value, CompositionError> {
        let capability = C::ID;
        Self::resolve_candidates(
            required_by,
            capability,
            None,
            provisions
                .iter()
                .map(|provision| (provision.module, provision.value)),
            provisions.len(),
            selected,
        )
    }

    /// Resolves an optional requirement without installing a default provider.
    /// Zero candidates returns `Ok(None)`, one returns its value, and multiple
    /// candidates remain ambiguous.
    pub fn resolve_optional<'value, C: Capability>(
        required_by: ModuleId,
        provisions: &[Provision<'value, C>],
    ) -> Result<Option<&'value C::Value>, CompositionError> {
        match provisions {
            [] => Ok(None),
            [provision] => Ok(Some(provision.value)),
            _ => Err(Self::error(
                CompositionErrorKind::AmbiguousProviders,
                required_by,
                C::ID,
                None,
                provisions
                    .iter()
                    .map(|provision| (provision.module, provision.value)),
            )),
        }
    }

    /// Returns every provider for a many-valued requirement.
    ///
    /// Results are sorted by module identity for stable inspection only. This
    /// order does not define provider execution or dependency order.
    pub fn resolve_many<'value, C: Capability>(
        provisions: &[Provision<'value, C>],
    ) -> Vec<Provision<'value, C>> {
        let mut resolved = provisions
            .iter()
            .map(|provision| Provision::new(provision.module, provision.value))
            .collect::<Vec<_>>();
        resolved.sort_unstable_by_key(Provision::module);
        resolved
    }

    /// Resolves a provision for one typed qualifier, excluding other qualifiers
    /// from candidate counting and diagnostics.
    pub fn resolve_qualified<'value, C: Capability, Q: Qualifier>(
        required_by: ModuleId,
        provisions: &[QualifiedProvision<'value, C, Q>],
        selected: Option<ModuleId>,
    ) -> Result<&'value C::Value, CompositionError> {
        Self::resolve_candidates(
            required_by,
            C::ID,
            Some(Q::ID),
            provisions
                .iter()
                .map(|provision| (provision.module, provision.value)),
            provisions.len(),
            selected,
        )
    }

    fn resolve_candidates<'value, V: ?Sized + 'value>(
        required_by: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        mut provisions: impl Iterator<Item = (ModuleId, &'value V)> + Clone,
        count: usize,
        selected: Option<ModuleId>,
    ) -> Result<&'value V, CompositionError> {
        if let Some(selected) = selected {
            let mut matches = provisions.clone().filter(|(module, _)| *module == selected);
            if let Some((_, value)) = matches.next() {
                if matches.next().is_none() {
                    return Ok(value);
                }
                return Err(Self::error(
                    CompositionErrorKind::AmbiguousProviders,
                    required_by,
                    capability,
                    qualifier,
                    provisions,
                ));
            }
            return Err(Self::error(
                CompositionErrorKind::ProviderSelectionUnavailable,
                required_by,
                capability,
                qualifier,
                provisions,
            ));
        }

        match count {
            0 => Err(Self::error(
                CompositionErrorKind::MissingProvider,
                required_by,
                capability,
                qualifier,
                provisions,
            )),
            1 => Ok(provisions.next().expect("count checked").1),
            _ => Err(Self::error(
                CompositionErrorKind::AmbiguousProviders,
                required_by,
                capability,
                qualifier,
                provisions,
            )),
        }
    }

    fn error<'value, V: ?Sized + 'value>(
        kind: CompositionErrorKind,
        required_by: ModuleId,
        capability: CapabilityId,
        qualifier: Option<QualifierId>,
        provisions: impl Iterator<Item = (ModuleId, &'value V)>,
    ) -> CompositionError {
        let mut candidates = provisions.map(|(module, _)| module).collect::<Vec<_>>();
        candidates.sort_unstable();
        CompositionError::new(kind, required_by, capability, qualifier, candidates)
    }
}