scc-core 0.2.11

System Context Compiler core: System IR types, identifiers, provenance
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
//! System IR core types.
//!
//! These types mirror `docs/system-ir.schema.json` exactly so that a `SystemIr`
//! document serializes to the documented export format without translation.

use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet};

pub const SCHEMA_VERSION: &str = "0.1.0";

pub mod handles;
pub mod identity;
pub mod languages;
pub mod lex;
pub mod resolution;
pub mod retrieval;

pub use handles::{fnv1a64_hex, ContentHandle, HandleError, HandleKind};
pub use languages::{
    extracted_language_ids, language_by_id, language_registry, support_matrix_markdown,
    LanguageCapability, LanguageTier, LANGUAGE_REGISTRY,
};
pub use lex::{
    bm25_rank, bm25_scores, bm25_scores_with_stats, classify_query, extract_query_mentions,
    is_exact_anchor, mention_matches_doc, path_matches_locus, ranking_arm_ids, relevance_hits,
    relevance_hits_with_stats, route_query, subtokens, Bm25CorpusStats, LexDoc, LexField, QueryLocus,
    QueryMention, QueryShape,
    RankingArm, RelevanceHit, RetrievalPlan, BM25_B, BM25_K1, QUERY_MENTION_MAX_RAW, WEIGHT_BODY,
    WEIGHT_DOC, WEIGHT_NAME, WEIGHT_PATH,
};
pub use resolution::{
    choose_representation, AnalysisQuality, CallQuality, FileQuality, RecvKind,
    RepresentationChoice, RepresentationKind, ResolutionClass,
};
pub use retrieval::{mean_reciprocal_rank, recall_at_k};

// ---------------------------------------------------------------------------
// Provenance
// ---------------------------------------------------------------------------

// trace:exempt reason=internal-detail

/// Evidence class of a fact, per docs/SYSTEM_IR_SCHEMA.md §5.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
// trace:v1 id=impl.crates-scc-core-src-lib.Provenance work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum Provenance {
    /// Direct syntax/configuration evidence.
    Extracted,
    /// Resolved through compiler/LSP/type/binding resolution.
    Resolved,
    /// Runtime evidence.
    Observed,
    /// Declared architectural intent.
    Declared,
    /// Heuristic/LLM claim.
    Inferred,
    /// Evidence no longer valid for the active revision.
    Stale,
}

// trace:exempt reason=internal-detail
impl Provenance {
// trace:v1 id=impl.crates-scc-core-src-lib-provenance.as-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn as_str(&self) -> &'static str {
        match self {
            Provenance::Extracted => "EXTRACTED",
            Provenance::Resolved => "RESOLVED",
            Provenance::Observed => "OBSERVED",
            Provenance::Declared => "DECLARED",
            Provenance::Inferred => "INFERRED",
            Provenance::Stale => "STALE",
        }
    }

    /// Default confidence per docs/SYSTEM_IR_SCHEMA.md §9.
// trace:v1 id=impl.crates-scc-core-src-lib-provenance.default-confidence work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn default_confidence(&self) -> f64 {
        match self {
            Provenance::Extracted => 1.0,
            Provenance::Resolved => 0.98,
            Provenance::Observed => 1.0,
            Provenance::Declared => 1.0,
            Provenance::Inferred => 0.7,
            Provenance::Stale => 0.0,
        }
    }

    /// STALE facts may never enter trusted context (only as warnings).
// trace:v1 id=impl.crates-scc-core-src-lib-provenance.is-trusted work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn is_trusted(&self) -> bool {
        !matches!(self, Provenance::Stale)
    }
}

// ---------------------------------------------------------------------------
// Severity / kinds
// ---------------------------------------------------------------------------

// trace:exempt reason=internal-detail

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Severity work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum Severity {
    Info,
    Low,
    Medium,
    High,
    Critical,
}

// trace:exempt reason=internal-detail
impl Severity {
// trace:v1 id=impl.crates-scc-core-src-lib-severity.rank work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn rank(&self) -> u8 {
        match self {
            Severity::Info => 0,
            Severity::Low => 1,
            Severity::Medium => 2,
            Severity::High => 3,
            Severity::Critical => 4,
        }
    }
}

// trace:exempt reason=internal-detail

/// Flow view kinds (System Atlas), per docs/SYSTEM_IR_SCHEMA.md §7.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.FlowKind work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum FlowKind {
    Architecture,
    Workflow,
    Sequence,
    Dataflow,
    Lifecycle,
}

// trace:exempt reason=internal-detail
impl FlowKind {
// trace:v1 id=impl.crates-scc-core-src-lib-flowkind.as-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn as_str(&self) -> &'static str {
        match self {
            FlowKind::Architecture => "architecture",
            FlowKind::Workflow => "workflow",
            FlowKind::Sequence => "sequence",
            FlowKind::Dataflow => "dataflow",
            FlowKind::Lifecycle => "lifecycle",
        }
    }
}

// trace:v1 id=impl.crates-scc-core-src-lib.flow-kind-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn flow_kind_str(k: &FlowKind) -> &'static str {
    k.as_str()
}

/// Evidence source type.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "lowercase")]
// trace:v1 id=impl.crates-scc-core-src-lib.EvidenceType work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum EvidenceType {
    Source,
    Config,
    Runtime,
    Test,
    Intent,
    History,
}

// ---------------------------------------------------------------------------
// Archetype (Ontology phase — deterministic repo classification)
// ---------------------------------------------------------------------------

// trace:exempt reason=internal-detail

/// Repository archetype, detected deterministically from graph evidence
/// (routes, exports, cli/framework signals, deployment/workspace shape) by
/// `scc_graph::archetype::detect_archetype`. `Unknown` is the honest
/// fallback when no signal fires.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Archetype work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum Archetype {
    /// HTTP routes + deployment units, no library-scale export ratio.
    ServiceApplication,
    /// cli-subcommand entrypoints or main fns with clap/cobra/argparse.
    Cli,
    /// Exported-symbol ratio over total symbols > 0.5, few/no routes.
    LibrarySdk,
    /// Routes + framework registrations + middleware facts.
    WebFramework,
    /// parse/analyze/transform/generate-style phase symbols.
    CompilerLanguageTool,
    /// plugin/middleware/DI registrations dominating.
    PluginFramework,
    /// docker/k8s/terraform manifests + deployment units, few app symbols.
    InfrastructureProject,
    /// workspace packages >= 3 + multiple deployment units.
    MonorepoPlatform,
    /// No signal fired.
    Unknown,
}

// trace:exempt reason=internal-detail
impl Archetype {
// trace:v1 id=impl.crates-scc-core-src-lib-archetype.as-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn as_str(&self) -> &'static str {
        match self {
            Archetype::ServiceApplication => "service_application",
            Archetype::Cli => "cli",
            Archetype::LibrarySdk => "library_sdk",
            Archetype::WebFramework => "web_framework",
            Archetype::CompilerLanguageTool => "compiler_language_tool",
            Archetype::PluginFramework => "plugin_framework",
            Archetype::InfrastructureProject => "infrastructure_project",
            Archetype::MonorepoPlatform => "monorepo_platform",
            Archetype::Unknown => "unknown",
        }
    }

// trace:v1 id=impl.crates-scc-core-src-lib-archetype.label work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn label(&self) -> &'static str {
        match self {
            Archetype::ServiceApplication => "service application",
            Archetype::Cli => "cli",
            Archetype::LibrarySdk => "library/sdk",
            Archetype::WebFramework => "web framework",
            Archetype::CompilerLanguageTool => "compiler/language tool",
            Archetype::PluginFramework => "plugin framework",
            Archetype::InfrastructureProject => "infrastructure project",
            Archetype::MonorepoPlatform => "monorepo platform",
            Archetype::Unknown => "unknown",
        }
    }

    /// All archetypes in the deterministic tie-break precedence order
    /// (first entry wins a score tie).
    pub const PRECEDENCE: [Archetype; 9] = [
        Archetype::MonorepoPlatform,
        Archetype::InfrastructureProject,
        Archetype::WebFramework,
        Archetype::ServiceApplication,
        Archetype::Cli,
        Archetype::LibrarySdk,
        Archetype::CompilerLanguageTool,
        Archetype::PluginFramework,
        Archetype::Unknown,
    ];
}

// ---------------------------------------------------------------------------
// Core records
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.Repository work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Repository {
    pub id: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.Snapshot work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Snapshot {
    pub revision: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    pub indexed_at: String,
}

// trace:exempt reason=internal-detail

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Entity work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Entity {
    pub id: String,
    pub kind: String,
    pub name: String,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, serde_json::Value>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

// trace:exempt reason=internal-detail
impl Entity {
// trace:v1 id=impl.crates-scc-core-src-lib-entity.new work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn new(id: impl Into<String>, kind: impl Into<String>, name: impl Into<String>) -> Self {
        Entity {
            id: id.into(),
            kind: kind.into(),
            name: name.into(),
            attributes: BTreeMap::new(),
            evidence: Vec::new(),
        }
    }

// trace:v1 id=impl.crates-scc-core-src-lib-entity.attr work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn attr(&mut self, key: &str, value: impl Into<serde_json::Value>) -> &mut Self {
        self.attributes.insert(key.to_string(), value.into());
        self
    }
}

// trace:exempt reason=internal-detail

/// One concrete occurrence of a concept (schema/reactive) in a source file.
///
/// Concept entities (SCHEMA/REACTIVE) are keyed globally by (kind, name) —
/// the same `z.object({...})` in A.ts and B.ts is ONE concept. Occurrences
/// carry per-(concept, path, owner, line) identity instead: each file's
/// occurrence survives independently, so provenance (`sources`) and the
/// derived occurrence count never collapse and a purge of one path never
/// deletes an occurrence another path still has.
#[derive(Debug, Clone, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Occurrence work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Occurrence {
    /// Stable entity id (see [`occurrence_id`]).
    pub id: String,
    /// The concept entity id this occurrence belongs to.
    pub concept: String,
    /// Repository-relative source path.
    pub path: String,
    /// Owning symbol name.
    pub owner: String,
    /// Deterministic site line (owning symbol's start line when the
    /// extractor facts carry no line).
    pub line: u32,
}

// trace:exempt reason=internal-detail

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Relationship work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Relationship {
    pub id: String,
    pub subject: String,
    pub predicate: String,
    pub object: String,
    pub provenance: Provenance,
    pub confidence: f64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub verified_at: String,
}

// trace:exempt reason=internal-detail
impl Relationship {
// trace:v1 id=impl.crates-scc-core-src-lib-relationship.new work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn new(
        id: impl Into<String>,
        subject: impl Into<String>,
        predicate: impl Into<String>,
        object: impl Into<String>,
        provenance: Provenance,
    ) -> Self {
        Relationship {
            id: id.into(),
            subject: subject.into(),
            predicate: predicate.into(),
            object: object.into(),
            provenance,
            confidence: provenance.default_confidence(),
            evidence: Vec::new(),
            verified_at: String::new(),
        }
    }

// trace:v1 id=impl.crates-scc-core-src-lib-relationship.with-confidence work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn with_confidence(mut self, c: f64) -> Self {
        self.confidence = c;
        self
    }

// trace:v1 id=impl.crates-scc-core-src-lib-relationship.with-evidence work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn with_evidence(mut self, evidence: Vec<String>) -> Self {
        self.evidence = evidence;
        self
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.FlowStep work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct FlowStep {
    pub id: String,
    pub order: u32,
    pub actor: String,
    pub operation: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub r#async: Option<bool>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub timeout_ms: Option<u64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub retry_policy: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failure_outcome: Option<String>,
    #[serde(default)]
    pub provenance: Option<Provenance>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.Flow work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Flow {
    pub id: String,
    pub kind: FlowKind,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<String>,
    pub steps: Vec<FlowStep>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub attributes: BTreeMap<String, serde_json::Value>,
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.Invariant work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Invariant {
    pub id: String,
    pub statement: String,
    pub severity: Severity,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scope: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub enforced_by: Vec<String>,
    #[serde(default)]
    pub provenance: Option<Provenance>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

// trace:exempt reason=internal-detail

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Evidence work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Evidence {
    pub id: String,
    #[serde(rename = "type")]
    pub r#type: EvidenceType,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub symbol: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub start_line: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub end_line: Option<u32>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revision: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub content_hash: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extractor: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extractor_version: Option<String>,
}

// trace:exempt reason=internal-detail
impl Evidence {
// trace:v1 id=impl.crates-scc-core-src-lib-evidence.source work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn source(id: impl Into<String>, path: impl Into<String>) -> Self {
        Evidence {
            id: id.into(),
            r#type: EvidenceType::Source,
            path: Some(path.into()),
            symbol: None,
            start_line: None,
            end_line: None,
            revision: None,
            content_hash: None,
            extractor: None,
            extractor_version: None,
        }
    }
}

// ---------------------------------------------------------------------------
// Canonical Causal FlowGraph (Wave 3 — the behavioral truth)
// ---------------------------------------------------------------------------

/// Edge kind in the canonical causal graph (P1, docs/SYSTEM_DESIGN.md §9).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
// trace:v1 id=impl.crates-scc-core-src-lib.FlowEdgeKind work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum FlowEdgeKind {
    /// Sequential causality.
    Next,
    /// Alternative execution path (fanout from evidence: call fanout,
    /// exception handlers, task spawn, runtime trace variants, declared).
    Branch,
    /// Failure edge to an error/exception handler or failure outcome.
    Error,
    /// Retry edge (back to the retried operation).
    Retry,
    /// Fallback edge to the degraded path.
    /// DEFERRED (§25): no reliable extractor evidence; not produced.
    Fallback,
    /// Asynchronous dispatch.
    Async,
    /// Message/event publication.
    Publish,
    /// Message/event consumption.
    Consume,
    /// Convergence of concurrent paths.
    Join,
    /// Return/terminal edge.
    /// DEFERRED: subsumed by Next topology; not produced as a kind.
    Return,
    /// Timeout edge.
    /// DEFERRED (§25): no reliable extractor evidence; not produced.
    Timeout,
    /// Compensation/rollback edge.
    /// DEFERRED (§25): no reliable extractor evidence; not produced.
    Compensation,
    /// State/data read.
    Read,
    /// State/data write.
    Write,
    /// Data transformation.
    /// DEFERRED: subsumed by call-chain topology; not produced as a kind.
    Transform,
    /// Validation/schema check.
    /// DEFERRED: no reliable extractor evidence; not produced.
    Validate,
    /// Authorization/policy gate.
    /// DEFERRED: trust-boundary analysis covers this; not a flow kind.
    Authorize,
    /// Cache lookup.
    /// DEFERRED: no reliable extractor evidence; not produced.
    Cache,
    /// Cache/state invalidation.
    /// DEFERRED: no reliable extractor evidence; not produced.
    Invalidate,
}

/// One operation node in the canonical flow graph. The canonical graph
/// retains individual operations — component-level grouping (ComponentSpan)
/// happens only at display/context time.
#[derive(Debug, Clone, Serialize, Deserialize)]
// trace:v1 id=impl.crates-scc-core-src-lib.FlowNode work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct FlowNode {
    /// Index within the graph (0-based).
    pub id: u32,
    /// Actor entity id (symbol or component).
    pub actor: String,
    /// Operation label.
    pub operation: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
// trace:v1 id=impl.crates-scc-core-src-lib.FlowEdge work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct FlowEdge {
    pub from: u32,
    pub to: u32,
    pub kind: FlowEdgeKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub condition: Option<String>,
    #[serde(default)]
    pub provenance: Option<Provenance>,
    #[serde(default)]
    pub confidence: f64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

/// The canonical causal representation of one flow: a graph, never a
/// flattened linear step list. Alternate execution paths are preserved as
/// branch edges; false sequential causality is impossible by construction.
#[derive(Debug, Clone, Serialize, Deserialize)]
// trace:v1 id=impl.crates-scc-core-src-lib.FlowGraph work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct FlowGraph {
    pub id: String,
    pub kind: FlowKind,
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<String>,
    #[serde(default)]
    pub nodes: Vec<FlowNode>,
    #[serde(default)]
    pub edges: Vec<FlowEdge>,
    /// Node indices that start the graph.
    #[serde(default)]
    pub entrypoints: Vec<u32>,
    /// Node indices with no outgoing causal edge (returns).
    #[serde(default)]
    pub exits: Vec<u32>,
    #[serde(default)]
    pub provenance_summary: BTreeMap<String, usize>,
}

// ---------------------------------------------------------------------------
// System Atlas (Wave 2 — the startup architecture artifact)
// ---------------------------------------------------------------------------

/// One architectural component in the atlas. Purpose is the highest-ranked
/// responsibility claim; consumes/produces come from data-flow edges;
/// upstream/downstream from dependency edges; retry/failure from extracted
/// failure behavior.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasComponent work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasComponent {
    pub name: String,
    pub purpose: String,
    /// Implementation facts: directory paths AND member symbol names (the
    /// component compiler's `implementation` attribute carries both). The
    /// structured model exposes the full fact layer; the rendered atlas
    /// shows only [`AtlasComponent::implementation_paths`] to stay compact.
    #[serde(default)]
    pub implementation: Vec<String>,
    /// The directory-path subset of `implementation` — the compact view the
    /// rendered ARCHITECTURE block and IMPLEMENTATION MAP use.
    #[serde(default)]
    pub implementation_paths: Vec<String>,
    /// Member symbols attributed to the component (compile-time fact).
    #[serde(default)]
    pub symbols: Vec<String>,
    #[serde(default)]
    pub consumes: Vec<String>,
    #[serde(default)]
    pub produces: Vec<String>,
    #[serde(default)]
    pub upstream: Vec<String>,
    #[serde(default)]
    pub downstream: Vec<String>,
    #[serde(default)]
    pub failure_behavior: Vec<String>,
    #[serde(default)]
    pub owns: Vec<AtlasOwnershipClaim>,
    /// Architectural layer assigned by the hierarchy clusterer:
    /// `code_region | component | subsystem | service`.
    #[serde(default)]
    pub layer: String,
    /// Immediate container entity id (subsystem/service) for merged
    /// members; `None` for unmerged leaves.
    #[serde(default)]
    pub parent: Option<String>,
    /// Repository role from implementation paths: `production` (default),
    /// `test`, `fixture`, `benchmark`, `example`, or `mixed`. Lets renders
    /// scope non-production trees as structure, never production.
    #[serde(default)]
    pub role: String,
}

/// One hierarchical container (service or subsystem) with its direct member
/// entity ids (component ids, or subsystem ids nested inside a service).
/// Deterministic: `members` sorted by entity id.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasHierarchyNode work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasHierarchyNode {
    /// Container entity id (`repo://…/service/…` or `repo://…/subsystem/…`).
    pub id: String,
    pub name: String,
    /// `"service"` | `"subsystem"`
    pub kind: String,
    #[serde(default)]
    pub members: Vec<String>,
}

/// A typed ownership claim (provenance preserved — DECLARED intent never
/// promoted).
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasOwnershipClaim work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasOwnershipClaim {
    pub target: String,
    pub provenance: String,
}

/// A condensed flow: steps collapsed to "Actor: operation" lines, with
/// branch/async/failure markers preserved.
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasFlow work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasFlow {
    pub name: String,
    pub kind: FlowKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub trigger: Option<String>,
    #[serde(default)]
    pub steps: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasEntrypoint work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasEntrypoint {
    pub name: String,
    pub kind: String,
    pub trigger: String,
    #[serde(default)]
    pub symbol: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.AtlasInvariant work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct AtlasInvariant {
    pub statement: String,
    pub severity: Severity,
}

// trace:exempt reason=internal-detail

/// First-class contract subclass (Contract ontology): the semantic contract
/// family, derived by the extractors from general evidence (public fn
/// signatures, builder/factory structure, event producer/consumer pairs,
/// serializer/deserializer pairs, interface+implementations, route/flag/
/// topic/config facts) and rendered by the atlas as per-subclass groups.
/// The legacy `kind` string stays for back-compat; `subclass` is the typed
/// family (`http`/`cli`/`event`/`config`/`public-api`/`extension`/
/// `serialization`/...).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Default, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ContractSubclass work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum ContractSubclass {
    /// A callable contract surface (framework callback, task, annotated
    /// handler, middleware): the framework invokes this callable.
    CallContract,
    /// Public API export (function/method signature surface).
    PublicApi,
    /// HTTP route.
    #[default]
    Http,
    /// RPC method.
    Rpc,
    /// CLI flag / subcommand.
    Cli,
    /// Event (topic with producers/consumers).
    Event,
    /// Message / queue surface.
    Message,
    /// Schema definition (validation/model schema).
    Schema,
    /// Configuration key.
    Configuration,
    /// Plugin registration.
    Plugin,
    /// Extension point: interface + implementations.
    Extension,
    /// Serialization pair (serializer/deserializer around a type).
    Serialization,
}

// trace:exempt reason=internal-detail
impl ContractSubclass {
    /// Render prefix used by the atlas CONTRACTS section (stable, sorted:
    /// `http: GET /x`, `cli: --flag`, `event: user.created`, `config: DEBUG`,
    /// `public-api: Class.method`, `extension: PluginX`, `serialization:
    /// toJson/fromJson`).
// trace:v1 id=impl.crates-scc-core-src-lib-contractsubclass.as-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn as_str(&self) -> &'static str {
        match self {
            ContractSubclass::CallContract => "call",
            ContractSubclass::PublicApi => "public-api",
            ContractSubclass::Http => "http",
            ContractSubclass::Rpc => "rpc",
            ContractSubclass::Cli => "cli",
            ContractSubclass::Event => "event",
            ContractSubclass::Message => "message",
            ContractSubclass::Schema => "schema",
            ContractSubclass::Configuration => "config",
            ContractSubclass::Plugin => "plugin",
            ContractSubclass::Extension => "extension",
            ContractSubclass::Serialization => "serialization",
        }
    }

    /// Map a contract/registration kind string to its first-class subclass.
    /// `None` for framework-specific registration kinds (`include_router`,
    /// `add_middleware`, ...) that stay framework semantics instead of
    /// first-class contracts. `factory` → PublicApi and `builder` →
    /// Configuration are the ontology's builder/factory rule.
// trace:v1 id=impl.crates-scc-core-src-lib-contractsubclass.from-kind-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn from_kind_str(kind: &str) -> Option<ContractSubclass> {
        Some(match kind {
            "http" | "route" => ContractSubclass::Http,
            "cli" => ContractSubclass::Cli,
            "event" | "topic" => ContractSubclass::Event,
            "config" | "configuration" | "next-config" => ContractSubclass::Configuration,
            "factory" | "export" | "public-api" | "public_api" => ContractSubclass::PublicApi,
            "builder" => ContractSubclass::Configuration,
            "serialization" | "serialize" | "deserialize" => ContractSubclass::Serialization,
            "extension" => ContractSubclass::Extension,
            "plugin" => ContractSubclass::Plugin,
            "rpc" => ContractSubclass::Rpc,
            "message" | "queue" => ContractSubclass::Message,
            "schema" => ContractSubclass::Schema,
            "call" | "task" | "bean" | "rule" | "middleware" | "callback" => {
                ContractSubclass::CallContract
            }
            _ => return None,
        })
    }
}

// trace:exempt reason=internal-detail

/// One first-class contract in the atlas (Wave 9): a typed, evidence-backed
/// contract surface (http/cli/event/config/annotation) with its producer
/// symbol and the symbols that consume it. `operations` carries the concrete
/// contract strings (route `GET /api/x`, flag `--paging`, event
/// `user.created`, config key `DEBUG`, annotation `router.get`).
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Contract work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct Contract {
    pub id: String,
    /// `"http" | "cli" | "event" | "config" | "annotation"`.
    pub kind: String,
    /// Semantic contract subclass (Contract ontology): the typed family
    /// derived from general evidence — http/cli/event/config from
    /// route/flag/topic/config facts, public-api from exported fn
    /// signatures, serialization from serializer/deserializer pairs,
    /// extension from interface+implementations, and extractor-emitted
    /// registration kinds mapped by `ContractSubclass::from_kind_str`.
    #[serde(default)]
    pub subclass: ContractSubclass,
    /// Producer entity id (handler symbol, owning symbol, topic, ...).
    #[serde(default)]
    pub producer: String,
    /// Consuming entity ids (symbols with HANDLES/CONSUMES/READS edges).
    #[serde(default)]
    pub consumers: Vec<String>,
    /// Concrete contract strings rendered as `{kind}: {operation}`.
    #[serde(default)]
    pub operations: Vec<String>,
    #[serde(default)]
    pub evidence: Vec<String>,
}

// trace:exempt reason=internal-detail
impl Contract {
// trace:v1 id=impl.crates-scc-core-src-lib-contract.new work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn new(
        id: impl Into<String>,
        kind: impl Into<String>,
        producer: impl Into<String>,
    ) -> Self {
        Contract {
            id: id.into(),
            kind: kind.into(),
            subclass: ContractSubclass::default(),
            producer: producer.into(),
            consumers: Vec::new(),
            operations: Vec::new(),
            evidence: Vec::new(),
        }
    }

    /// Set the semantic subclass (builder-style; the atlas sets it on the
    /// typed families it derives from entity kinds).
// trace:v1 id=impl.crates-scc-core-src-lib-contract.with-subclass work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn with_subclass(mut self, subclass: ContractSubclass) -> Self {
        self.subclass = subclass;
        self
    }
}

// trace:exempt reason=internal-detail

/// How a symbol can be invoked from outside the process (Wave 9): the
/// invocation surfaces the flow compiler seeds entrypoints from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.InvocationSurfaceKind work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum InvocationSurfaceKind {
    /// OS process spawn / executable entry.
    Process,
    /// HTTP route handler.
    Http,
    /// CLI subcommand / flag surface.
    Cli,
    /// Public API export (EXPORTS evidence).
    PublicApi,
    /// Event/topic handler.
    Event,
    /// Queue consumer (SUBSCRIBES evidence).
    Queue,
    /// Scheduled job.
    Schedule,
    /// Plugin/extension registration.
    Plugin,
    /// Framework callback (HANDLES_CALLBACK evidence).
    FrameworkCallback,
    /// Lifecycle callback (JUnit @Before*/@After* annotation facts).
    Lifecycle,
}

// trace:exempt reason=internal-detail
impl InvocationSurfaceKind {
// trace:v1 id=impl.crates-scc-core-src-lib-invocationsurfacekind.as-str work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn as_str(&self) -> &'static str {
        match self {
            InvocationSurfaceKind::Process => "process",
            InvocationSurfaceKind::Http => "http",
            InvocationSurfaceKind::Cli => "cli",
            InvocationSurfaceKind::PublicApi => "public_api",
            InvocationSurfaceKind::Event => "event",
            InvocationSurfaceKind::Queue => "queue",
            InvocationSurfaceKind::Schedule => "schedule",
            InvocationSurfaceKind::Plugin => "plugin",
            InvocationSurfaceKind::FrameworkCallback => "framework_callback",
            InvocationSurfaceKind::Lifecycle => "lifecycle",
        }
    }
}

/// One invocation surface: a symbol reachable from outside the process.
#[derive(Debug, Clone, Serialize, Deserialize)]
// trace:v1 id=impl.crates-scc-core-src-lib.InvocationSurface work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct InvocationSurface {
    pub symbol: String,
    pub kind: InvocationSurfaceKind,
    pub trigger: String,
}

/// The full System Atlas: structured architecture before rendering. This is
/// the machine model handed to agents at session start (docs/SYSTEM_DESIGN.md
/// §8, Wave 2).
#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.crates-scc-core-src-lib.SystemAtlas work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SystemAtlas {
    pub repository: String,
    pub revision: String,
    pub indexed_at: String,
    pub freshness: String,
    pub purpose: String,
    #[serde(default)]
    pub components: Vec<AtlasComponent>,
    #[serde(default)]
    pub entrypoints: Vec<AtlasEntrypoint>,
    #[serde(default)]
    pub contracts: Vec<Contract>,
    /// Explicit uncertainty/coverage map (Wave 9): section key -> line.
    /// What the model knows AND what it does not.
    #[serde(default)]
    pub coverage: BTreeMap<String, String>,
    #[serde(default)]
    pub flows: Vec<AtlasFlow>,
    #[serde(default)]
    pub invariants: Vec<AtlasInvariant>,
    #[serde(default)]
    pub deployment_units: Vec<String>,
    #[serde(default)]
    pub external_systems: Vec<String>,
    #[serde(default)]
    pub trust_boundaries: Vec<String>,
    #[serde(default)]
    pub async_boundaries: Vec<String>,
    #[serde(default)]
    pub implementation_map: BTreeMap<String, Vec<String>>,
    /// Data stores / data entities written by components (WRITES-derived),
    /// rendered as a DATA STORES list under DATA OWNERSHIP.
    #[serde(default)]
    pub data_stores: Vec<String>,
    /// Detected repository archetype (deterministic evidence scoring).
    #[serde(default)]
    pub archetype: Option<Archetype>,
    /// STATE & DATA AUTHORITY (ontology phase): section key
    /// (persistent|runtime|configuration|caches|derived) -> deterministic
    /// `COMPONENT owns/reads TARGET (PROV)`-style lines.
    #[serde(default)]
    pub state_authority: BTreeMap<String, Vec<String>>,
    /// Hierarchical architecture containers (services first, then
    /// subsystems) with their direct member entity ids.
    #[serde(default)]
    pub hierarchy: Vec<AtlasHierarchyNode>,
    #[serde(default)]
    pub evidence_summary: BTreeMap<String, usize>,
    #[serde(default)]
    pub warnings: Vec<String>,
    /// PUBLIC API (Wave 10 COMPILER-gap attack): component name ->
    /// sorted public-export names (EXPORT entities + exported module-level
    /// symbols). Rendered as `component: exports...` compact lines.
    #[serde(default)]
    pub public_api: BTreeMap<String, Vec<String>>,
    /// FRAMEWORK SEMANTICS (Wave 10): component name -> sorted semantic
    /// lines (`annotates X`, `registers Y (kind)`, `handles callback Z`)
    /// from ANNOTATES/REGISTERS/HANDLES_CALLBACK facts.
    #[serde(default)]
    pub framework_semantics: BTreeMap<String, Vec<String>>,
    /// PIPELINE (Wave 10, CompilerLanguageTool archetype): phase-named
    /// symbols/files grouped by stage (`parse`/`analyze`/`transform`/
    /// `generate`/`emit`/`other`), rendered as `[stage] symbol` lines.
    #[serde(default)]
    pub pipeline: Vec<String>,
    /// LANDMARKS (Wave 10): notable exports + annotated targets, bounded
    /// (~40) — the informational one-zoom-deeper symbol list.
    #[serde(default)]
    pub landmarks: Vec<String>,
}

// ---------------------------------------------------------------------------
// Whole-document export
// ---------------------------------------------------------------------------

// trace:exempt reason=internal-detail

#[derive(Debug, Clone, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SystemIr work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SystemIr {
    pub schema_version: String,
    pub repository: Repository,
    pub snapshot: Snapshot,
    pub entities: Vec<Entity>,
    pub relationships: Vec<Relationship>,
    pub flows: Vec<Flow>,
    pub invariants: Vec<Invariant>,
    #[serde(default)]
    pub evidence: Vec<Evidence>,
    /// Plugin-contributed facts preserved verbatim (§106): provider ->
    /// the ids this export carries from that provider. Core consumers
    /// ignore this section; extension-aware consumers resolve it.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub extensions: BTreeMap<String, Vec<String>>,
}

// trace:exempt reason=internal-detail
impl SystemIr {
// trace:v1 id=impl.crates-scc-core-src-lib-systemir.empty work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
    pub fn empty(repository: Repository, snapshot: Snapshot) -> Self {
        SystemIr {
            schema_version: SCHEMA_VERSION.to_string(),
            repository,
            snapshot,
            entities: Vec::new(),
            relationships: Vec::new(),
            flows: Vec::new(),
            invariants: Vec::new(),
            evidence: Vec::new(),
            extensions: BTreeMap::new(),
        }
    }
}

// ---------------------------------------------------------------------------
// Identifiers
// ---------------------------------------------------------------------------

/// Sanitize a free-form name into a stable URI key.
// trace:v1 id=impl.crates-scc-core-src-lib.sanitize-key work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn sanitize_key(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    let mut prev_dash = false;
    for c in input.chars() {
        let ok = c.is_ascii_alphanumeric() || c == '_' || c == '-' || c == '.' || c == '/';
        if ok {
            // keep path separators but normalize repeated dashes
            if c == '/' {
                out.push('/');
                prev_dash = false;
            } else if c == '-' || c == '_' {
                if !prev_dash {
                    out.push('-');
                }
                prev_dash = true;
            } else {
                out.push(c.to_ascii_lowercase());
                prev_dash = false;
            }
        } else {
            if !prev_dash {
                out.push('-');
            }
            prev_dash = true;
        }
    }
    while out.ends_with('-') {
        out.pop();
    }
    if out.is_empty() {
        out.push_str("unnamed");
    }
    out
}

/// `repo://{repo}/{kind}/{key}` stable identifier.
// trace:v1 id=impl.crates-scc-core-src-lib.entity-id work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn entity_id(repo: &str, kind: &str, key: &str) -> String {
    format!("repo://{}/{}/{}", sanitize_key(repo), kind, sanitize_key(key))
}

/// Occurrence entity id: collision-free per (concept key, path, owner,
/// line) — the identity occurrences carry so shared concepts never lose
/// per-file provenance. Unlike [`entity_id`], the concept/path/owner
/// components are percent-encoded (`@`-separated), so case and separator
/// distinctions (`a_b` vs `a-b`) never merge distinct occurrences.
// trace:v1 id=impl.scc.core.occurrence work=WORK-SCC-001 satisfies=REQ-SCC-IR
// trace:v1 id=impl.crates-scc-core-src-lib.occurrence-id work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn occurrence_id(repo: &str, concept: &str, path: &str, owner: &str, line: u32) -> String {
    format!(
        "repo://{}/occurrence/{}@{}@{}@{}",
        sanitize_key(repo),
        encode_component(concept),
        encode_component(path),
        encode_component(owner),
        line
    )
}

/// Percent-encode a path/name component for use inside an entity id while
/// preserving case and common separators (`/`, `.`, `_`, `-`). Collision-free
/// where `sanitize_key` would risk merging distinct names.
// trace:v1 id=impl.crates-scc-core-src-lib.encode-component work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn encode_component(input: &str) -> String {
    let mut out = String::with_capacity(input.len());
    for b in input.bytes() {
        let keep = b.is_ascii_alphanumeric() || matches!(b, b'/' | b'.' | b'_' | b'-');
        if keep {
            out.push(b as char);
        } else {
            out.push('%');
            out.push_str(&format!("{b:02X}"));
        }
    }
    out
}

/// Inverse of `encode_component`: percent-decodes `%XX` sequences back to
/// bytes. Used by benchmark/impact tooling to map entity ids back to names.
// trace:v1 id=impl.crates-scc-core-src-lib.decode-component work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn decode_component(input: &str) -> String {
    let bytes = input.as_bytes();
    let mut out = Vec::with_capacity(bytes.len());
    let mut i = 0;
    while i < bytes.len() {
        if bytes[i] == b'%' && i + 2 < bytes.len() {
            let hi = (bytes[i + 1] as char).to_digit(16);
            let lo = (bytes[i + 2] as char).to_digit(16);
            if let (Some(hi), Some(lo)) = (hi, lo) {
                out.push((hi * 16 + lo) as u8);
                i += 3;
                continue;
            }
        }
        out.push(bytes[i]);
        i += 1;
    }
    String::from_utf8_lossy(&out).to_string()
}

/// Stable symbol id: `repo://{repo}/symbol/{encoded-file}/{encoded-name}`.
// trace:v1 id=impl.crates-scc-core-src-lib.symbol-id work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn symbol_id(repo: &str, file: &str, name: &str) -> String {
    format!(
        "repo://{}/symbol/{}/{}",
        sanitize_key(repo),
        encode_component(file),
        encode_component(name)
    )
}

/// Evidence id namespace: `evidence:{n}` — stable within a snapshot, assigned
/// by the store.
// trace:v1 id=impl.crates-scc-core-src-lib.evidence-id work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn evidence_id(n: u64) -> String {
    format!("evidence:{n}")
}

/// Relationship id: `rel:{n}` — stable within a snapshot, assigned by store.
// trace:v1 id=impl.crates-scc-core-src-lib.relationship-id work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn relationship_id(n: u64) -> String {
    format!("rel:{n}")
}

// ---------------------------------------------------------------------------
// Entity kind / predicate constants
// ---------------------------------------------------------------------------

pub mod kinds {
    pub const FILE: &str = "file";
    pub const SYMBOL: &str = "symbol";
    pub const PACKAGE: &str = "package";
    pub const MODULE: &str = "module";
    pub const SYSTEM: &str = "system";
    pub const SUBSYSTEM: &str = "subsystem";
    pub const SERVICE: &str = "service";
    pub const COMPONENT: &str = "component";
    pub const DEPLOYMENT_UNIT: &str = "deployment_unit";
    pub const ROUTE: &str = "route";
    pub const ENDPOINT: &str = "endpoint";
    pub const EVENT: &str = "event";
    pub const TOPIC: &str = "topic";
    pub const QUEUE: &str = "queue";
    pub const DATA_ENTITY: &str = "data";
    pub const DATA_STORE: &str = "store";
    pub const TABLE: &str = "table";
    pub const COLLECTION: &str = "collection";
    pub const CACHE: &str = "cache";
    pub const EXTERNAL_SYSTEM: &str = "external_system";
    pub const EXTERNAL_API: &str = "external_api";
    pub const CONFIGURATION: &str = "configuration";
    pub const FEATURE_FLAG: &str = "feature_flag";
    pub const SECRET_REFERENCE: &str = "secret_reference";
    pub const CONTRACT: &str = "contract";
    pub const INVARIANT: &str = "invariant";
    pub const TEST: &str = "test";
    pub const TEST_SUITE: &str = "test_suite";
    pub const FLOW: &str = "flow";
    pub const WORKFLOW: &str = "workflow";
    pub const STATE: &str = "state";
    // Semantic fact layer (Wave 9): first-class representations the
    // extractors emit for framework/library semantics.
    pub const EXPORT: &str = "export";
    pub const ANNOTATION: &str = "annotation";
    pub const FIELD: &str = "field";
    pub const REGISTRY: &str = "registry";
    pub const MIDDLEWARE: &str = "middleware";
    pub const DI_BINDING: &str = "di_binding";
    pub const TRANSITION: &str = "transition";
    pub const RESOURCE: &str = "resource";
    pub const TRUST_BOUNDARY: &str = "trust_boundary";
    pub const SECURITY_CONTROL: &str = "security_control";
    pub const RUNTIME_OBSERVATION: &str = "runtime_observation";
    // Wave 11: first-class schema and reactive-state contracts.
    pub const SCHEMA: &str = "schema";
    pub const REACTIVE: &str = "reactive";
    // Occurrence layer: one entity per (concept, path, owner, line) so
    // shared concepts never lose per-file provenance (Wave 13).
    pub const OCCURRENCE: &str = "occurrence";

    /// All entity kinds. Tests fail if a `pub const` is added above and
    /// omitted here.
    pub const ALL: &[&str] = &[
        FILE, SYMBOL, PACKAGE, MODULE, SYSTEM, SUBSYSTEM, SERVICE, COMPONENT, DEPLOYMENT_UNIT,
        ROUTE, ENDPOINT, EVENT, TOPIC, QUEUE, DATA_ENTITY, DATA_STORE, TABLE, COLLECTION, CACHE,
        EXTERNAL_SYSTEM, EXTERNAL_API, CONFIGURATION, FEATURE_FLAG, SECRET_REFERENCE, CONTRACT,
        INVARIANT, TEST, TEST_SUITE, FLOW, WORKFLOW, STATE, EXPORT, ANNOTATION, FIELD, REGISTRY,
        MIDDLEWARE, DI_BINDING, TRANSITION, RESOURCE, TRUST_BOUNDARY, SECURITY_CONTROL,
        RUNTIME_OBSERVATION, SCHEMA, REACTIVE, OCCURRENCE,
    ];
}

pub mod predicates {
    pub const CONTAINS: &str = "contains";
    pub const IMPLEMENTS: &str = "implements";
    pub const INHERITS: &str = "inherits";
    pub const IMPORTS: &str = "imports";
    pub const CALLS: &str = "calls";
    pub const READS: &str = "reads";
    pub const WRITES: &str = "writes";
    pub const QUERIES: &str = "queries";
    pub const OWNS: &str = "owns";
    pub const PUBLISHES: &str = "publishes";
    pub const CONSUMES: &str = "consumes";
    pub const SUBSCRIBES: &str = "subscribes";
    pub const PRODUCES: &str = "produces";
    pub const TRANSFORMS: &str = "transforms";
    pub const VALIDATES: &str = "validates";
    pub const DEFINES: &str = "defines";
    pub const COMPOSES: &str = "composes";
    pub const ROUTES_TO: &str = "routes_to";
    pub const HANDLES: &str = "handles";
    pub const INVOKES: &str = "invokes";
    pub const DEPENDS_ON: &str = "depends_on";
    pub const DEPLOYED_WITH: &str = "deployed_with";
    pub const DEPLOYED_IN: &str = "deployed_in";
    pub const CONFIGURED_BY: &str = "configured_by";
    pub const PROTECTED_BY: &str = "protected_by";
    pub const CROSSES_BOUNDARY: &str = "crosses_boundary";
    pub const ENFORCES: &str = "enforces";
    pub const TESTED_BY: &str = "tested_by";
    pub const PARTICIPATES_IN: &str = "participates_in";
    pub const PRECEDES: &str = "precedes";
    pub const FOLLOWS: &str = "follows";
    pub const BRANCHES_TO: &str = "branches_to";
    pub const RETRIES: &str = "retries";
    pub const FALLS_BACK_TO: &str = "falls_back_to";
    pub const OBSERVED_AS: &str = "observed_as";
    pub const DECLARED_AS: &str = "declared_as";
    pub const IMPLEMENTED_BY: &str = "implemented_by";
    // Semantic fact layer (Wave 9)
    pub const EXPORTS: &str = "exports";
    pub const ANNOTATES: &str = "annotates";
    pub const REGISTERS: &str = "registers";
    pub const INJECTS: &str = "injects";
    pub const HANDLES_CALLBACK: &str = "handles_callback";
    pub const DECORATES: &str = "decorates";
    /// An occurrence entity's attachment to its concept entity
    /// (occurrence OCCURS concept).
    pub const OCCURS: &str = "occurs";

    /// All predicates in the documented ontology. Must include every
    /// `pub const` in this module — `kinds`/`predicates` drift is a
    /// silent ranking/export bug.
    pub const ALL: &[&str] = &[
        CONTAINS, IMPLEMENTS, INHERITS, IMPORTS, CALLS, READS, WRITES, QUERIES, OWNS, PUBLISHES,
        CONSUMES, SUBSCRIBES, PRODUCES, TRANSFORMS, VALIDATES, DEFINES, COMPOSES, ROUTES_TO,
        HANDLES, INVOKES, DEPENDS_ON, DEPLOYED_WITH, DEPLOYED_IN, CONFIGURED_BY, PROTECTED_BY,
        CROSSES_BOUNDARY, ENFORCES, TESTED_BY, PARTICIPATES_IN, PRECEDES, FOLLOWS, BRANCHES_TO,
        RETRIES, FALLS_BACK_TO, OBSERVED_AS, DECLARED_AS, IMPLEMENTED_BY, EXPORTS, ANNOTATES,
        REGISTERS, INJECTS, HANDLES_CALLBACK, DECORATES, OCCURS,
    ];
}

/// Authoritative kind and predicate ids. Rankers, exporters, and tests
/// must derive from these slices rather than a second hand-maintained list.
// trace:v1 id=impl.scc.core.ontology-registry work=WORK-ripwire-lessons-phase1 satisfies=REQ-ontology-single-source
pub fn ontology_registries() -> (&'static [&'static str], &'static [&'static str]) {
    (kinds::ALL, predicates::ALL)
}

// ---------------------------------------------------------------------------
// Token budgeting
// ---------------------------------------------------------------------------

/// Rough token estimate: 4 characters per token (byte-based for ASCII, but we
/// operate on char count which is a close approximation across scripts).
// trace:v1 id=impl.crates-scc-core-src-lib.estimate-tokens work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn estimate_tokens(text: &str) -> usize {
    let chars = text.chars().count();
    chars.div_ceil(4)
}

/// Hard-truncate `text` to at most `budget` tokens, preferring a clean cut at
/// a line boundary.
// trace:v1 id=impl.crates-scc-core-src-lib.truncate-to-budget work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn truncate_to_budget(text: &str, budget: usize) -> String {
    if estimate_tokens(text) <= budget {
        return text.to_string();
    }
    let max_chars = budget.saturating_mul(4);
    let mut end = 0;
    let mut chars = 0;
    for (i, c) in text.char_indices() {
        chars += 1;
        if chars > max_chars {
            break;
        }
        end = i + c.len_utf8();
    }
    // Back off to the previous newline for a clean boundary (but keep at least
    // half the budget worth of content).
    let min_chars = max_chars / 2;
    let mut cut = end;
    if let Some(nl) = text[..end].rfind('\n') {
        let prefix_chars = text[..nl].chars().count();
        if prefix_chars >= min_chars {
            cut = nl;
        }
    }
    let mut out = text[..cut].to_string();
    out.push_str("\n… (truncated by token budget)");
    out
}

// ---------------------------------------------------------------------------
// Misc
// ---------------------------------------------------------------------------

// trace:v1 id=impl.crates-scc-core-src-lib.now-rfc3339 work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub fn now_rfc3339() -> String {
    chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
}

// ---------------------------------------------------------------------------
// Wave 14: System Surface Map — the actual callable code surface (Aider
// RepoMap equivalent built from System IR). Level 1 of the four-level
// context stack (docs/SYSTEM_DESIGN.md Wave 14).
// ---------------------------------------------------------------------------

/// A source range: file path + 1-based inclusive line span.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SourceRange work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SourceRange {
    pub path: String,
    pub start_line: u32,
    pub end_line: u32,
}

// trace:exempt reason=internal-detail
impl SourceRange {
// trace:exempt reason=internal-detail
    pub fn new(path: impl Into<String>, start_line: u32, end_line: u32) -> Self {
        SourceRange {
            path: path.into(),
            start_line,
            end_line,
        }
    }
}

/// Symbol visibility as declared in source.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.Visibility work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum Visibility {
    Public,
    Protected,
    Private,
    Package,
}

// trace:exempt reason=internal-detail
impl Visibility {
// trace:exempt reason=internal-detail
    pub fn as_str(&self) -> &'static str {
        match self {
            Visibility::Public => "public",
            Visibility::Protected => "protected",
            Visibility::Private => "private",
            Visibility::Package => "package",
        }
    }
}

/// The kind of code surface a definition exposes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SurfaceKind work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum SurfaceKind {
    Function,
    Method,
    Constructor,
    Class,
    Interface,
    Trait,
    Type,
    Enum,
    Const,
    Module,
    Record,
}

// trace:exempt reason=internal-detail
impl SurfaceKind {
// trace:exempt reason=internal-detail
    pub fn as_str(&self) -> &'static str {
        match self {
            SurfaceKind::Function => "function",
            SurfaceKind::Method => "method",
            SurfaceKind::Constructor => "constructor",
            SurfaceKind::Class => "class",
            SurfaceKind::Interface => "interface",
            SurfaceKind::Trait => "trait",
            SurfaceKind::Type => "type",
            SurfaceKind::Enum => "enum",
            SurfaceKind::Const => "const",
            SurfaceKind::Module => "module",
            SurfaceKind::Record => "record",
        }
    }
}

/// One function/method parameter in structured form.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SemanticParameter work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SemanticParameter {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ty: Option<String>,
    /// `&self` / `self` receiver parameters.
    #[serde(default)]
    pub receiver: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    #[serde(default)]
    pub variadic: bool,
}

/// The structured machine form of a signature — the semantic layer over
/// the exact source text. Benchmark matching uses this, never string
/// comparisons of source signatures alone.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SemanticSignature work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SemanticSignature {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub owner: Option<String>,
    #[serde(default)]
    pub visibility: Option<Visibility>,
    #[serde(default)]
    pub async_: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub generic_parameters: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<SemanticParameter>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub returns: Option<String>,
    /// `where` / trait-bound constraints (`T: Send + Sync`).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub constraints: Vec<String>,
}

/// Why a surface entry earned its rank (explainability; `scc surface
/// --explain` renders this).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SurfaceRank work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SurfaceRank {
    pub task_ppr: f64,
    pub global_ppr: f64,
    pub lexical: f64,
    pub semantic: f64,
    pub confidence: f64,
    pub criticality: f64,
    pub change_risk: f64,
    pub novelty: f64,
    pub total: f64,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub reasons: Vec<String>,
}

// trace:exempt reason=internal-detail
impl Default for SurfaceRank {
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn default() -> Self {
        SurfaceRank {
            task_ppr: 0.0,
            global_ppr: 0.0,
            lexical: 0.0,
            semantic: 0.0,
            confidence: 0.0,
            criticality: 0.0,
            change_risk: 0.0,
            novelty: 0.0,
            total: 0.0,
            reasons: Vec::new(),
        }
    }
}

/// One ranked definition on the system surface — a callable/typeable
/// reality of the architecture, with exact signatures and architectural
/// meaning attached.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SurfaceEntry work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SurfaceEntry {
    pub id: String,
    pub symbol_id: String,
    pub qualified_name: String,
    pub kind: SurfaceKind,
    pub path: String,
    pub range: SourceRange,
    /// Exact source representation of the signature.
    pub source_signature: String,
    /// Whitespace/dialect-normalized signature (dedupe/comparison/index).
    pub canonical_signature: String,
    pub semantic_signature: SemanticSignature,
    pub visibility: Visibility,
    #[serde(default)]
    pub exported: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub modifiers: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub annotations: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub component: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subsystem: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub flows: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub contracts: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub state_authorities: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invocation_surfaces: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callers: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub callees: Vec<String>,
    /// Exact distinct fan-in/fan-out (the displayed name lists stay capped
    /// at 12; the counts are never truncated).
    #[serde(default)]
    pub caller_count: usize,
    #[serde(default)]
    pub callee_count: usize,
    /// Derived importance explanation (badges + counts + architecture
    /// signals). Populated by the surface pipeline; default-empty for
    /// entries built before ranking.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub importance: Option<ImportanceProfile>,
    pub provenance: Provenance,
    #[serde(default)]
    pub confidence: f32,
    #[serde(default)]
    pub rank: SurfaceRank,
}

/// A definition deliberately omitted by a token-budget cut — the artifact
/// never silently implies completeness.
/// Derived importance explanation for one surface symbol (audit item 3):
/// topology (exact fan-in/fan-out, never truncated), architecture signals,
/// and change impact — computed from data the pipeline ALREADY has. Badges
/// are derived labels over those numbers, not extra scoring magic: the
/// overall score stays `rank.total`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:v1 id=impl.scc.core.importance-profile work=WORK-SI-MMMJA4G6 satisfies=REQ-SI-503JSBGP
pub struct ImportanceProfile {
    pub overall: f64,
    pub caller_count: usize,
    pub callee_count: usize,
    pub global_ppr: f64,
    pub task_ppr: f64,
    pub entrypoint: bool,
    pub exported: bool,
    pub flow_count: usize,
    pub contract_count: usize,
    pub state_read_count: usize,
    pub state_write_count: usize,
    pub dependent_count: usize,
    pub change_risk: f64,
    pub badges: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SurfaceOmission work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SurfaceOmission {
    pub count: usize,
    pub kind: String,
    pub reason: String,
}

/// The System Surface Map: the ranked actual-API layer of a repository,
/// built from System IR (Level 1 of the context stack).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SystemSurfaceMap work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SystemSurfaceMap {
    pub repository: String,
    pub revision: String,
    pub epoch: String,
    pub entries: Vec<SurfaceEntry>,
    #[serde(default)]
    pub token_count: usize,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub omitted: Vec<SurfaceOmission>,
}

/// The production surface render: the budget-selected subset plus honest
/// omission accounting (Wave 14F). `rendered_ids` are exactly the entries
/// the agent sees (ledger recording MUST use only these — omitted
/// candidates are never marked visible); `omitted_ids` are every candidate
/// the pipeline cut. `omissions` summarizes the cuts by kind.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, schemars::JsonSchema)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.SurfaceRenderResult work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct SurfaceRenderResult {
    /// The rendered surface text (header + selected entry blocks).
    pub text: String,
    /// Entry ids actually rendered, in selection order.
    pub rendered_ids: Vec<String>,
    /// The rendered entries themselves (post hard-max pops — exactly the
    /// set `rendered_ids` names). Lets callers resolve rendered ids without
    /// recompiling the surface map. Wire-compatible: skipped when empty.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub rendered_entries: Vec<SurfaceEntry>,
    /// Candidate entry ids the pipeline omitted (budget/quotas/diversity).
    pub omitted_ids: Vec<String>,
    /// Per-kind omission summaries.
    pub omissions: Vec<SurfaceOmission>,
    /// Token estimate of `text`.
    pub token_count: usize,
    /// Required entries the hard-max invariant had to DROP after every
    /// compression level was exhausted (explicit CRITICAL omissions — the
    /// highest-ranked required entry is preserved whenever anything fits).
    /// Empty in every non-pathological render.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub critical_drops: Vec<String>,
}

/// One node in the heterogeneous ranking universe (Wave 14B): any rankable
/// entity — symbol, component, subsystem, service, flow, contract, state,
/// reactive, route, topic, queue, store, schema, or file. The ranker walks
/// edges whose endpoints are rankable entities, so architectural importance
/// (flows, contracts, state) participates in PageRank directly.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.RankNode work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct RankNode {
    /// The entity id (`repo://{repo}/{kind}/{key}`).
    pub id: String,
    /// Entity kind (`scc_core::kinds::*`).
    pub kind: String,
    /// Entity display name.
    pub name: String,
}

/// A normalized reference between two symbols (Wave 14): the graph the
/// ranker walks. Many SCC relationships already express these concepts;
/// this layer normalizes them for ranking.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ReferenceEdge work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct ReferenceEdge {
    pub source_symbol: String,
    pub target_symbol: String,
    pub kind: ReferenceKind,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub locations: Vec<SourceRange>,
    pub provenance: Provenance,
    #[serde(default)]
    pub confidence: f32,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ReferenceKind work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub enum ReferenceKind {
    Read,
    Write,
    #[default]
    Call,
    TypeUse,
    Instantiate,
    Implement,
    Extend,
    Decorate,
    Register,
    Import,
    Export,
    Macro,
    FieldAccess,
    Construct,
}

// trace:exempt reason=internal-detail
impl ReferenceKind {
// trace:exempt reason=internal-detail
    pub fn as_str(&self) -> &'static str {
        match self {
            ReferenceKind::Read => "read",
            ReferenceKind::Write => "write",
            ReferenceKind::Call => "call",
            ReferenceKind::TypeUse => "type_use",
            ReferenceKind::Instantiate => "instantiate",
            ReferenceKind::Implement => "implement",
            ReferenceKind::Extend => "extend",
            ReferenceKind::Decorate => "decorate",
            ReferenceKind::Register => "register",
            ReferenceKind::Import => "import",
            ReferenceKind::Export => "export",
            ReferenceKind::Macro => "macro",
            ReferenceKind::FieldAccess => "field_access",
            ReferenceKind::Construct => "construct",
        }
    }
}

/// A token-optimized context candidate (Aider-style hard budget search).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ContextItem work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct ContextItem {
    pub id: String,
    pub value: f64,
    pub token_cost: usize,
    #[serde(default)]
    pub required: bool,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub group: Option<String>,
}

/// The startup/task context budget split (Wave 14 dynamic budgets).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:v1 id=impl.crates-scc-core-src-lib.ContextBudget work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct ContextBudget {
    pub total: usize,
    pub atlas: usize,
    pub surface: usize,
    pub task_delta: usize,
    pub structural_source: usize,
}

// trace:exempt reason=internal-detail
impl Default for ContextBudget {
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn default() -> Self {
        ContextBudget {
            total: 20_000,
            atlas: 13_000,
            surface: 7_000,
            task_delta: 3_000,
            structural_source: 6_000,
        }
    }
}

/// Absolute ceiling on the massive-tier surface slice: a 20k-entity repo
/// must not hand the model an unbounded surface even under a huge total.
const MASSIVE_SURFACE_CAP: usize = 10_000;

// trace:exempt reason=internal-detail  # impl grouping; adaptive below is traced
impl ContextBudget {
    /// Adaptive startup split: scale the Atlas/Surface allocation by repo
    /// complexity instead of the fixed 13:7 default. Tiers by entity count
    /// (component count escalates to `large`; flow count escalates to
    /// `architecture-heavy`):
    ///
    /// - tiny (`entity_count < 200`): 55/45 — a small atlas leaves room
    ///   for a proportionally larger surface;
    /// - ordinary: 60/40;
    /// - architecture-heavy (`flow_count > 40`): 65/35 — flows, routes and
    ///   contracts are Atlas content, so a flow-dense repo needs the Atlas
    ///   slice even when its entity count is ordinary;
    /// - large (`entity_count > 5000` or `component_count > 30`): 65/35 —
    ///   the atlas dominates;
    /// - massive (`entity_count > 20_000`): 70/30 with the surface slice
    ///   capped absolutely ([`MASSIVE_SURFACE_CAP`]) and no candidate
    ///   boost.
    ///
    /// Within a tier, the actual candidate pool feeds the surface share:
    /// every 2,000 surface candidates earns up to +5 percentage points
    /// (surface never over 50% of the total), so a repo whose surface map
    /// is genuinely large gets a proportionally larger surface slice.
    /// `total` is caller-supplied — adaptive scales the SPLIT, never the
    /// total. Deterministic and no-panic. Defaults stay for callers that
    /// do not adapt.
    // trace:v1 id=impl.scc.core.budget-adaptive work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching satisfies=REQ-adaptive-startup-budgets
    pub fn adaptive(
        total: usize,
        entity_count: usize,
        component_count: usize,
        flow_count: usize,
        surface_candidates: usize,
    ) -> ContextBudget {
        let (surface_pct, boost, cap): (f64, f64, Option<usize>) = if entity_count > 20_000 {
            (30.0, 0.0, Some(MASSIVE_SURFACE_CAP))
        } else if entity_count > 5_000 || component_count > 30 {
            (35.0, 5.0, None)
        } else if flow_count > 40 {
            // Architecture-heavy: flows/routes/contracts are Atlas content.
            // Checked BEFORE the tiny tier — a small but flow-dense repo
            // still needs the Atlas slice.
            (35.0, 5.0, None)
        } else if entity_count < 200 {
            (45.0, 5.0, None)
        } else {
            (40.0, 5.0, None)
        };
        let boost_pp = (surface_candidates / 2_000).min(boost as usize) as f64;
        let surface_pct = (surface_pct + boost_pp).min(50.0);
        let atlas_pct = 100.0 - surface_pct;
        let mut surface = ((total as f64) * surface_pct / 100.0).round() as usize;
        if let Some(c) = cap {
            surface = surface.min(c);
        }
        let atlas = ((total as f64) * atlas_pct / 100.0).round() as usize;
        let def = ContextBudget::default();
        ContextBudget {
            total,
            atlas,
            surface,
            task_delta: def.task_delta,
            structural_source: def.structural_source,
        }
    }
}

/// What the agent has already seen — novelty suppression source (the
/// general form of Aider treating chat files specially).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ContextLedger work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct ContextLedger {
    pub model_epoch: String,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub visible_entities: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub visible_symbols: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub visible_files: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub visible_components: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub visible_flows: BTreeSet<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_task: Option<String>,
}

/// One structural-source unit: semantic skeleton of an implementation
/// slice (Level 2), with provenance back to the exact source.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.StructuralSourceUnit work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct StructuralSourceUnit {
    pub path: String,
    /// `source: <path>:L<start>-L<end>` provenance line.
    pub source: String,
    pub representation: String,
    pub revision: String,
    pub content: String,
    /// Stable content handle for lazy exact-source retrieval. Empty when
    /// the compiler has no repo/epoch identity.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub handle: String,
    /// Why EXACT vs STRUCTURAL/SIGNATURES was chosen. Empty when no
    /// on-disk body was available to compare.
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub representation_reason: String,
}

/// The deterministic startup artifact (Atlas + Surface), hash-stable per
/// epoch so prompt caches hit.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.ContextArtifact work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct ContextArtifact {
    pub kind: String,
    pub epoch: String,
    pub renderer_version: String,
    pub trust_policy: String,
    pub budget: ContextBudget,
    /// Deterministic config-only hash (epoch + renderer + policy + budget) —
    /// the prompt-cache key, stable per epoch. Field name kept for the JSON
    /// contract.
    pub sha256: String,
    /// Hash over the *actual rendered content* (config preimage + rendered
    /// text), so a content change that keeps the config identical still
    /// changes the hash (the audit's name/content mismatch fix).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub content_hash: String,
    pub text: String,
}

/// One task-seed resolution: task language -> SCC entities.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
// trace:exempt reason=internal-detail
// trace:v1 id=impl.crates-scc-core-src-lib.TaskSeed work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
pub struct TaskSeed {
    pub kind: String,
    pub id: String,
    pub weight: f64,
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    // trace:v1 id=test.scc-core.estimate-tokens work=WORK-SI-MMMJA4G6 verifies=REQ-SI-NX53P4B7 exercises=impl.crates-scc-core-src-lib.estimate-tokens
    fn estimate_tokens_is_chars_ceiling() {
        // Authoritative estimator: chars/4 ceiling. All budget paths
        // (Rust packs, CLI builders, Python harness mirrors) must agree.
        assert_eq!(estimate_tokens(""), 0);
        assert_eq!(estimate_tokens("a"), 1);
        assert_eq!(estimate_tokens("abcd"), 1);
        assert_eq!(estimate_tokens("abcde"), 2);
        assert_eq!(estimate_tokens("fn main() { println!(\"hi\"); }"), 8);
        // Unicode counts code points (Rust chars), not bytes or graphemes.
        assert_eq!(estimate_tokens("日本語"), 1);
        assert_eq!(estimate_tokens("日本語テスト"), 2);
        // Long identifier-heavy paths stay proportional.
        let path = "crates/scc-context/src/surface/structural_source_selection_policy.rs";
        assert_eq!(estimate_tokens(path), path.chars().count().div_ceil(4));
    }

    #[test]
// trace:v1 id=impl.crates-scc-core-src-lib-context-budget.component-encode-decode-roundtrip work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
// trace:exempt reason=internal-detail
    fn component_encode_decode_roundtrip() {
        for name in [
            "Normalizer",
            "GET /api/transcripts/:id handler",
            "OrderStateMachine.advance",
            "test_normalization_preserves_raw",
            "src/app.ts",
            "a b%c",
        ] {
            assert_eq!(decode_component(&encode_component(name)), name, "{name}");
        }
    }

    #[test]
// trace:v1 id=impl.crates-scc-core-src-lib-context-budget.component-ids-are-collision-free work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
// trace:exempt reason=internal-detail
    fn component_ids_are_collision_free() {
        assert_ne!(
            encode_component("foo_bar"),
            encode_component("foo-bar"),
            "underscore and dash must not collide"
        );
    }

// trace:exempt reason=internal-detail

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn occurrence_ids_are_collision_free_per_site() {
        // distinct paths/owners/lines/concepts never merge
        assert_ne!(
            occurrence_id("r", "expr", "a.ts", "A", 1),
            occurrence_id("r", "expr", "b.ts", "A", 1)
        );
        assert_ne!(
            occurrence_id("r", "expr", "a.ts", "A", 1),
            occurrence_id("r", "expr", "a.ts", "B", 1)
        );
        assert_ne!(
            occurrence_id("r", "expr", "a.ts", "A", 1),
            occurrence_id("r", "expr", "a.ts", "A", 2)
        );
        assert_ne!(
            occurrence_id("r", "expr1", "a.ts", "A", 1),
            occurrence_id("r", "expr2", "a.ts", "A", 1)
        );
        // case/separator distinctions survive (unlike sanitize_key)
        assert_ne!(
            occurrence_id("r", "expr", "a_b.ts", "A", 1),
            occurrence_id("r", "expr", "a-b.ts", "A", 1)
        );
        assert_ne!(
            occurrence_id("r", "expr", "a.ts", "Foo", 1),
            occurrence_id("r", "expr", "a.ts", "foo", 1)
        );
        // deterministic
        assert_eq!(
            occurrence_id("r", "expr", "a.ts", "A", 1),
            occurrence_id("r", "expr", "a.ts", "A", 1)
        );
    }

// trace:exempt reason=internal-detail

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn occurrence_roundtrips_through_serde() {
        let o = Occurrence {
            id: occurrence_id("r", "z.object({ x: z.string() })", "src/a.ts", "make", 7),
            concept: entity_id("r", kinds::SCHEMA, "z.object({ x: z.string() })"),
            path: "src/a.ts".into(),
            owner: "make".into(),
            line: 7,
        };
        let json = serde_json::to_string(&o).unwrap();
        let back: Occurrence = serde_json::from_str(&json).unwrap();
        assert_eq!(back.id, o.id);
        assert_eq!(back.concept, o.concept);
        assert_eq!(back.line, 7);
    }

// trace:exempt reason=internal-detail

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn adaptive_budget_scales_split_by_repo_complexity() {
        // tiny repo: 55/45 split — a small atlas leaves room for a
        // proportionally larger surface (45% share, vs the normal 40%)
        let tiny = ContextBudget::adaptive(20_000, 50, 2, 1, 10);
        let tiny_ratio = tiny.surface as f64 / tiny.total as f64;
        assert!(
            (tiny_ratio - 0.45).abs() <= 0.01,
            "tiny: surface share {tiny_ratio}"
        );
        assert_eq!(tiny.total, 20_000);
        assert!(tiny.atlas + tiny.surface <= 20_000);

        // normal repo: 60/40
        let normal = ContextBudget::adaptive(20_000, 1_000, 5, 4, 10);
        let normal_ratio = normal.surface as f64 / normal.total as f64;
        assert!(
            (normal_ratio - 0.40).abs() <= 0.01,
            "normal: surface share {normal_ratio}"
        );

        // large repo (component-heavy): 65/35
        let large = ContextBudget::adaptive(20_000, 1_000, 40, 4, 10);
        let large_ratio = large.surface as f64 / large.total as f64;
        assert!(
            (large_ratio - 0.35).abs() <= 0.01,
            "large: surface share {large_ratio}"
        );

        // massive repo: 70/30 and the surface slice is absolutely capped
        let massive = ContextBudget::adaptive(20_000, 25_000, 60, 30, 10);
        assert!(massive.atlas > massive.surface);
        let massive_ratio = massive.surface as f64 / massive.total as f64;
        assert!(
            (massive_ratio - 0.30).abs() <= 0.01,
            "massive: surface share {massive_ratio}"
        );
        // the absolute cap binds under a huge total
        let massive_huge = ContextBudget::adaptive(100_000, 25_000, 60, 30, 10);
        assert_eq!(
            massive_huge.surface, MASSIVE_SURFACE_CAP,
            "massive surface absolutely capped"
        );

        // tiny and large must produce different atlas/surface splits
        assert_ne!(
            tiny.atlas as f64 / tiny.surface as f64,
            large.atlas as f64 / large.surface as f64,
            "tiny vs large splits must differ"
        );
    }

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn adaptive_budget_candidate_pool_boosts_surface_share() {
        // 10k candidates: +5pp surface share (10_000 / 2_000 = 5, capped at 5)
        let boosted = ContextBudget::adaptive(20_000, 1_000, 5, 4, 10_000);
        let boosted_ratio = boosted.surface as f64 / boosted.total as f64;
        assert!(
            (boosted_ratio - 0.45).abs() <= 0.01,
            "boosted: surface share {boosted_ratio}"
        );
        // surface never over 50% of the total
        let huge = ContextBudget::adaptive(20_000, 100, 2, 1, 100_000);
        assert!(huge.surface <= huge.total / 2, "surface capped at 50%");
    }

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn adaptive_budget_is_deterministic_and_total_preserving() {
        let a = ContextBudget::adaptive(15_000, 3_000, 8, 6, 500);
        let b = ContextBudget::adaptive(15_000, 3_000, 8, 6, 500);
        assert_eq!(a, b);
        assert_eq!(a.total, 15_000);
        assert!(a.atlas + a.surface <= 15_000);
    }

    #[test]
// trace:v1 id=impl.crates-scc-core-src-lib-context-budget.contract-kind-renders-as-operation-lines work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
// trace:exempt reason=internal-detail
    fn contract_kind_renders_as_operation_lines() {
        let mut c = Contract::new(
            "repo://repo/contract/http/get--api-x",
            "http",
            "repo://repo/symbol/main.py/handler",
        );
        c.operations.push("GET /api/x".into());
        c.consumers.push("repo://repo/symbol/main.py/handler".into());
        let lines: Vec<String> = c
            .operations
            .iter()
            .map(|op| format!("{}: {}", c.kind, op))
            .collect();
        assert_eq!(lines, vec!["http: GET /api/x"]);
    }

    #[test]
// trace:v1 id=impl.crates-scc-core-src-lib-context-budget.contract-subclass-ontology-maps-and-renders work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
// trace:exempt reason=internal-detail
    fn contract_subclass_ontology_maps_and_renders() {
        // Render prefixes per-subclass (the atlas CONTRACTS group prefixes).
        assert_eq!(ContractSubclass::Http.as_str(), "http");
        assert_eq!(ContractSubclass::Cli.as_str(), "cli");
        assert_eq!(ContractSubclass::Event.as_str(), "event");
        assert_eq!(ContractSubclass::Configuration.as_str(), "config");
        assert_eq!(ContractSubclass::PublicApi.as_str(), "public-api");
        assert_eq!(ContractSubclass::Extension.as_str(), "extension");
        assert_eq!(ContractSubclass::Serialization.as_str(), "serialization");
        assert_eq!(ContractSubclass::CallContract.as_str(), "call");
        assert_eq!(ContractSubclass::Rpc.as_str(), "rpc");
        assert_eq!(ContractSubclass::Message.as_str(), "message");
        assert_eq!(ContractSubclass::Schema.as_str(), "schema");
        assert_eq!(ContractSubclass::Plugin.as_str(), "plugin");

        // Derivation from contract/registration kind strings (the ontology
        // mapping the atlas applies to extractor-emitted facts).
        assert_eq!(ContractSubclass::from_kind_str("http"), Some(ContractSubclass::Http));
        assert_eq!(ContractSubclass::from_kind_str("route"), Some(ContractSubclass::Http));
        assert_eq!(ContractSubclass::from_kind_str("cli"), Some(ContractSubclass::Cli));
        assert_eq!(ContractSubclass::from_kind_str("event"), Some(ContractSubclass::Event));
        assert_eq!(
            ContractSubclass::from_kind_str("config"),
            Some(ContractSubclass::Configuration)
        );
        assert_eq!(
            ContractSubclass::from_kind_str("next-config"),
            Some(ContractSubclass::Configuration)
        );
        // builder = Configuration, factory = PublicApi (the ontology rule).
        assert_eq!(
            ContractSubclass::from_kind_str("builder"),
            Some(ContractSubclass::Configuration)
        );
        assert_eq!(
            ContractSubclass::from_kind_str("factory"),
            Some(ContractSubclass::PublicApi)
        );
        assert_eq!(
            ContractSubclass::from_kind_str("serialization"),
            Some(ContractSubclass::Serialization)
        );
        assert_eq!(
            ContractSubclass::from_kind_str("extension"),
            Some(ContractSubclass::Extension)
        );
        assert_eq!(ContractSubclass::from_kind_str("plugin"), Some(ContractSubclass::Plugin));
        assert_eq!(ContractSubclass::from_kind_str("rpc"), Some(ContractSubclass::Rpc));
        assert_eq!(ContractSubclass::from_kind_str("message"), Some(ContractSubclass::Message));
        assert_eq!(ContractSubclass::from_kind_str("schema"), Some(ContractSubclass::Schema));
        assert_eq!(ContractSubclass::from_kind_str("task"), Some(ContractSubclass::CallContract));
        // framework-specific registration kinds are NOT first-class contracts
        assert_eq!(ContractSubclass::from_kind_str("include_router"), None);
        assert_eq!(ContractSubclass::from_kind_str("add_middleware"), None);

        // Contract carries the subclass; `new` defaults to Http, serde
        // roundtrip preserves it, and a missing field (legacy JSON) defaults.
        let mut c = Contract::new(
            "repo://repo/contract/http/get--api-x",
            "http",
            "repo://repo/symbol/main.py/handler",
        );
        assert_eq!(c.subclass, ContractSubclass::Http);
        c.subclass = ContractSubclass::Serialization;
        let json = serde_json::to_string(&c).unwrap();
        let back: Contract = serde_json::from_str(&json).unwrap();
        assert_eq!(back.subclass, ContractSubclass::Serialization);
        let legacy = serde_json::json!({
            "id": "repo://repo/contract/x",
            "kind": "http",
            "producer": "p",
            "operations": ["GET /x"],
            "evidence": [],
            "consumers": [],
        });
        let c2: Contract = serde_json::from_value(legacy).unwrap();
        assert_eq!(c2.subclass, ContractSubclass::Http);
    }

    #[test]
// trace:v1 id=impl.crates-scc-core-src-lib-context-budget.invocation-surface-kinds-stringify work=WORK-wave-15-2-heterogeneous-hierarchy-edges-semantic-scoring-explain-rank-caching
// trace:exempt reason=internal-detail
    fn invocation_surface_kinds_stringify() {
        assert_eq!(InvocationSurfaceKind::PublicApi.as_str(), "public_api");
        assert_eq!(InvocationSurfaceKind::Queue.as_str(), "queue");
        assert_eq!(InvocationSurfaceKind::Lifecycle.as_str(), "lifecycle");
        assert_eq!(InvocationSurfaceKind::FrameworkCallback.as_str(), "framework_callback");
        // serde roundtrip is snake_case-stable
        let json = serde_json::to_string(&InvocationSurfaceKind::PublicApi).unwrap();
        assert_eq!(json, "\"public_api\"");
        let back: InvocationSurfaceKind = serde_json::from_str(&json).unwrap();
        assert_eq!(back, InvocationSurfaceKind::PublicApi);
    }

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn surface_render_result_roundtrips_through_serde() {
        let r = SurfaceRenderResult {
            text: "SCC SYSTEM SURFACE MAP\n\n  function serve\n".into(),
            rendered_ids: vec!["repo://r/symbol/api.py/serve".into()],
            rendered_entries: vec![],
            omitted_ids: vec!["repo://r/symbol/api.py/internal".into()],
            omissions: vec![SurfaceOmission {
                count: 1,
                kind: "function".into(),
                reason: "token budget".into(),
            }],
            token_count: 7,
            critical_drops: vec![],
        };
        let json = serde_json::to_string(&r).unwrap();
        let back: SurfaceRenderResult = serde_json::from_str(&json).unwrap();
        assert_eq!(back, r);
        assert_eq!(back.rendered_ids[0], "repo://r/symbol/api.py/serve");
        assert_eq!(back.omissions[0].count, 1);
    }

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn rank_node_carries_kind_and_name() {
        let n = RankNode {
            id: "repo://r/contract/c1".into(),
            kind: kinds::CONTRACT.into(),
            name: "c1".into(),
        };
        let json = serde_json::to_string(&n).unwrap();
        let back: RankNode = serde_json::from_str(&json).unwrap();
        assert_eq!(back.kind, "contract");
        assert_eq!(back.name, "c1");
    }

    #[test]
// trace:exempt reason=internal-detail
// trace:exempt reason=internal-detail
    fn context_artifact_content_hash_roundtrips_and_defaults() {
        // new field roundtrips
        let a = ContextArtifact {
            kind: "startup".into(),
            epoch: "e1".into(),
            renderer_version: "0.1.0".into(),
            trust_policy: "floor=0.85".into(),
            budget: ContextBudget::default(),
            sha256: "abc".into(),
            content_hash: "def".into(),
            text: "body".into(),
        };
        let json = serde_json::to_string(&a).unwrap();
        let back: ContextArtifact = serde_json::from_str(&json).unwrap();
        assert_eq!(back.content_hash, "def");

        // legacy JSON without content_hash deserializes (default empty)
        let legacy = serde_json::json!({
            "kind": "startup",
            "epoch": "e1",
            "renderer_version": "0.1.0",
            "trust_policy": "floor=0.85",
            "budget": ContextBudget::default(),
            "sha256": "abc",
            "text": "body",
        });
        let c: ContextArtifact = serde_json::from_value(legacy).unwrap();
        assert_eq!(c.content_hash, "");
    }

    #[test]
    // trace:v1 id=test.scc.core.predicate-registry-complete verifies=REQ-ontology-single-source exercises=impl.scc.core.ontology-registry
    fn predicate_and_kind_registries_are_complete() {
        // Mutation gate: dropping DEFINES/COMPOSES/EXPORTS from ALL used to
        // compile while ranking/export silently omitted those edges.
        let (kind_ids, predicate_ids) = ontology_registries();
        for required in [
            predicates::DEFINES,
            predicates::COMPOSES,
            predicates::EXPORTS,
            predicates::ANNOTATES,
            predicates::REGISTERS,
            predicates::INJECTS,
            predicates::HANDLES_CALLBACK,
            predicates::DECORATES,
            predicates::OCCURS,
        ] {
            assert!(
                predicate_ids.contains(&required),
                "predicates::ALL missing {required}"
            );
        }
        for required in [kinds::FIELD, kinds::SCHEMA, kinds::TRUST_BOUNDARY, kinds::OCCURRENCE]
        {
            assert!(kind_ids.contains(&required), "kinds::ALL missing {required}");
        }
        let mut seen = std::collections::BTreeSet::new();
        for p in predicate_ids {
            assert!(seen.insert(*p), "duplicate predicate in ALL: {p}");
        }
    }
}