scc-context 0.2.9

System Context Compiler context: ranking and bounded context packs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
//! System Atlas compiler (Wave 2): the full-system architecture artifact
//! injected into coding agents at session start (docs/SYSTEM_DESIGN.md §8).
//!
//! Builds a structured [`scc_core::SystemAtlas`] from the trusted view, then
//! renders it as compact structured text. The atlas is the product: the
//! agent should know the architecture *before* its first coding task.
//!
//! Trust contract: every fact comes from the TrustedGraphView — STALE facts
//! are excluded and surfaced as warnings; low-confidence inference is
//! excluded unless `include_low_confidence_inference` is set.

use crate::packs::{entity_name, finish, finish_soft, Section};
use crate::{ContextCompiler, ContextPack};
use scc_core::{
    language_by_id, Archetype, AtlasComponent, AtlasEntrypoint, AtlasFlow, AtlasHierarchyNode,
    AtlasInvariant, AtlasOwnershipClaim, ContractSubclass, FlowKind, SystemAtlas,
};
use scc_graph::TrustedGraphView;
use std::collections::{BTreeMap, BTreeSet, HashMap};

/// Semantic compilation scope: which repository roles feed the
/// architecture sections (entrypoints, contracts, state authority,
/// flows, boundaries, deployment). Components and files ALWAYS list
/// every role (labeled) — structure stays visible; only the inferred
/// architecture is scoped, so a fixture route never becomes a global
/// entrypoint and a benchmark DB writer never owns production state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
// trace:v1 id=impl.scc.atlas-scope work=WORK-SI-MMMJA4G6 satisfies=REQ-SI-503JSBGP
pub enum AtlasScope {
    /// Default: production-role evidence only, plus test relationships
    /// that explain production (TESTED_BY). Counts of scoped-out facts
    /// land in the coverage map under `scope`.
    Production,
    /// Everything: benchmark/fixture archaeology, benchmark tasks.
    Full,
}

/// Repository role of one entity: its `file` attribute (routes, symbols,
/// contracts carry it), else its handler symbol's file, else a manifest
/// pointer (`dockerfile`). Entities without any placement evidence are
/// production — never drop facts we cannot place.
// trace:exempt reason=internal-detail
fn entity_role(view: &TrustedGraphView, e: &scc_core::Entity) -> &'static str {
    let file: Option<String> = e
        .attributes
        .get("file")
        .and_then(|v| v.as_str())
        .map(String::from)
        .or_else(|| {
            e.attributes
                .get("handler")
                .and_then(|v| v.as_str())
                .and_then(|h| view.entity(h))
                .and_then(|s| {
                    s.attributes
                        .get("file")
                        .and_then(|v| v.as_str())
                        .map(String::from)
                })
        })
        .or_else(|| {
            e.attributes
                .get("dockerfile")
                .and_then(|v| v.as_str())
                .map(String::from)
        });
    file.as_deref()
        .and_then(scc_graph::components::path_role)
        .unwrap_or("production")
}

/// Role of an entity id (`production` when unknown — see [`entity_role`]).
// trace:exempt reason=internal-detail
fn entity_id_role(view: &TrustedGraphView, id: &str) -> &'static str {
    view.entity(id)
        .map(|e| entity_role(view, e))
        .unwrap_or("production")
}

/// Scope-filtered entity iteration: architecture sections use this
/// instead of `view.entities_of_kind`. Structural kinds are never
/// filtered by callers (components/files list every role, labeled).
/// Dropped counts accumulate per section for the honesty receipt.
/// Participant verdict for unattributed hubs (topics, configurations):
/// `None` when no participant carries placement evidence (kept — never
/// drop facts we cannot place), else whether ANY participant is production.
/// A topic whose publishers/subscribers are ALL fixture files is fixture
/// chatter, not architecture — even though the topic entity itself has no
/// file attribute.
// trace:exempt reason=internal-detail
fn participants_production(view: &TrustedGraphView, ids: &[String]) -> Option<bool> {
    let mut decided = false;
    let mut prod = false;
    for id in ids {
        if let Some(e) = view.entity(id) {
            if e.attributes.get("file").and_then(|v| v.as_str()).is_some() {
                decided = true;
                if entity_role(view, e) == "production" {
                    prod = true;
                }
            }
        }
    }
    if decided {
        Some(prod)
    } else {
        None
    }
}

/// Actor placement: component actors resolve through the component
/// role map, symbol actors through entity file evidence. `None` means
/// unplaceable (kept — never drop flows we cannot place).
// trace:exempt reason=internal-detail
fn actor_production(
    view: &TrustedGraphView,
    comp_role_by_id: &HashMap<String, String>,
    actor: &str,
) -> Option<bool> {
    if let Some(r) = comp_role_by_id.get(actor) {
        return Some(r == "production");
    }
    view.entity(actor).map(|e| entity_role(view, e) == "production")
}

/// Flow keep rule: a flow with at least one production actor is
/// architecture; a flow whose actors are ALL placed outside production
/// is fixture/test choreography. Unplaceable flows are kept.
// trace:exempt reason=internal-detail
fn keep_flow(
    view: &TrustedGraphView,
    comp_role_by_id: &HashMap<String, String>,
    scope: AtlasScope,
    actors: &[String],
) -> bool {
    if scope == AtlasScope::Full {
        return true;
    }
    let mut decided = false;
    for a in actors {
        match actor_production(view, comp_role_by_id, a) {
            Some(true) => return true,
            Some(false) => decided = true,
            None => {}
        }
    }
    !decided
}

// trace:exempt reason=internal-detail
fn scoped_entities<'a>(
    view: &'a TrustedGraphView,
    kind: &str,
    scope: AtlasScope,
    section: &str,
    scoped_out: &mut BTreeMap<String, usize>,
) -> Vec<&'a scc_core::Entity> {
    let all = view.entities_of_kind(kind);
    if scope == AtlasScope::Full {
        return all;
    }
    let total = all.len();
    let kept: Vec<&'a scc_core::Entity> = all
        .into_iter()
        .filter(|e| entity_role(view, e) == "production")
        .collect();
    let dropped = total - kept.len();
    if dropped > 0 {
        *scoped_out.entry(section.to_string()).or_default() += dropped;
    }
    kept
}

/// Structured atlas compilation — pure data, no rendering. Default
/// scope is [`AtlasScope::Production`]: fixture/test/benchmark evidence
/// labels components but never feeds architecture sections.
// trace:v1 id=impl.scc.atlas work=WORK-SCC-001 satisfies=REQ-state-function-access,REQ-SCC-CTX
pub fn build_atlas(ctx: &ContextCompiler) -> SystemAtlas {
    build_atlas_scoped(ctx, AtlasScope::Production)
}

/// [`build_atlas`] with an explicit scope. `Full` restores the unfiltered
/// compilation for benchmark/fixture archaeology (`scc atlas --full`).
// trace:v1 id=impl.scc.atlas-scoped work=WORK-SI-MMMJA4G6 satisfies=REQ-SCC-CTX
pub fn build_atlas_scoped(ctx: &ContextCompiler, scope: AtlasScope) -> SystemAtlas {
    let view = &ctx.view;
    let store = ctx.store;
    let snapshot = store.latest_snapshot().ok().flatten();
    let repo = store.repository();

    let purpose = store.meta_get("purpose").ok().flatten().unwrap_or_default();

    // ---- components ----
    let mut components: Vec<AtlasComponent> = Vec::new();
    // data stores / data entities written by component symbols (WRITES-derived).
    // Collected per component so the global DATA STORES list can scope to
    // production components: a benchmark DB writer never owns production state.
    let mut data_stores: BTreeSet<String> = BTreeSet::new();
    let mut comp_store_targets: Vec<(String, Vec<String>)> = Vec::new();
    // Honesty receipt: per-section counts of architecture facts scoped out.
    let mut scoped_out: BTreeMap<String, usize> = BTreeMap::new();
    for c in view.components() {
        // Purpose prefers evidence-backed claims (Declared, then Resolved)
        // over bare inference; the trust view already strips low-confidence
        // claims, and this keeps the render honest about what remains.
        let responsibility = c
            .attributes
            .get("responsibility")
            .and_then(|v| v.as_array());
        fn claim_text(r: &serde_json::Value) -> &str {
            r.get("text").and_then(|t| t.as_str()).unwrap_or("")
        }
        let purpose_text = responsibility
            .and_then(|a| {
                a.iter()
                    .find(|r| {
                        matches!(
                            r.get("provenance").and_then(|p| p.as_str()),
                            Some("Declared") | Some("Resolved")
                        )
                    })
                    .or_else(|| a.first())
                    .map(claim_text)
            })
            .unwrap_or("")
            .to_string();

        let implementation_attr = c
            .attributes
            .get("implementation")
            .cloned()
            .unwrap_or(serde_json::json!({}));
        let implementation_paths: Vec<String> = implementation_attr
            .get("paths")
            .and_then(|p| p.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|x| x.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        // the full implementation fact: directory paths AND member symbol
        // names (the component compiler attributes every contained symbol).
        // The structured model carries both; the render shows only the
        // paths (`implementation_paths`) to stay compact.
        // Role first: owns/data-stores scoping below needs it before the
        // AtlasComponent literal is built.
        let role = c
            .attributes
            .get("role")
            .and_then(|v| v.as_str())
            .map(String::from)
            .unwrap_or_else(|| scc_graph::components::component_role(&implementation_paths).into());
        let mut implementation: Vec<String> = implementation_paths.clone();
        let mut symbols: Vec<String> = implementation_attr
            .get("symbols")
            .and_then(|s| s.as_array())
            .map(|a| {
                a.iter()
                    .filter_map(|x| x.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();
        symbols.sort();
        symbols.dedup();
        implementation.extend(symbols.iter().cloned());

        let mut upstream: BTreeSet<String> = BTreeSet::new();
        let mut downstream: BTreeSet<String> = BTreeSet::new();
        for r in view.in_pred(&c.id, scc_core::predicates::DEPENDS_ON) {
            upstream.insert(entity_name(view, &r.subject));
        }
        for r in view.out_pred(&c.id, scc_core::predicates::DEPENDS_ON) {
            downstream.insert(entity_name(view, &r.object));
        }

        let mut failure_behavior: Vec<String> = Vec::new();
        if let Some(rs) = c.attributes.get("retries").and_then(|v| v.as_array()) {
            failure_behavior.extend(rs.iter().filter_map(|x| x.as_str().map(String::from)));
        }
        for r in view.out_pred(&c.id, scc_core::predicates::CROSSES_BOUNDARY) {
            failure_behavior.push(format!(
                "crosses boundary -> {}",
                entity_name(view, &r.object)
            ));
        }

        let mut consumes: BTreeSet<String> = BTreeSet::new();
        let mut produces: BTreeSet<String> = BTreeSet::new();
        for pred in [
            scc_core::predicates::READS,
            scc_core::predicates::CONSUMES,
            scc_core::predicates::QUERIES,
        ] {
            for r in view.out_pred(&c.id, pred) {
                consumes.insert(entity_name(view, &r.object));
            }
        }
        for pred in [
            scc_core::predicates::PRODUCES,
            scc_core::predicates::PUBLISHES,
            scc_core::predicates::WRITES,
        ] {
            for r in view.out_pred(&c.id, pred) {
                produces.insert(entity_name(view, &r.object));
            }
        }

        // Ownership claims come from the component compiler's `owns` attr
        // (write-edge derived + declared intent, provenance preserved).
        // Claims targeting data-store / data-entity entities additionally
        // surface in the atlas DATA STORES list, using the full store
        // reference (`db.users`) so data entities stay attributed to their
        // store.
        let mut owns: Vec<AtlasOwnershipClaim> = Vec::new();
        let mut my_store_targets: Vec<String> = Vec::new();
        if let Some(oa) = c.attributes.get("owns").and_then(|v| v.as_array()) {
            for o in oa {
                let Some(t) = o.get("target").and_then(|v| v.as_str()) else {
                    continue;
                };
                let p = o.get("provenance").and_then(|v| v.as_str()).unwrap_or("");
                let is_store_target = view
                    .entity(t)
                    .map(|e| {
                        e.kind == scc_core::kinds::DATA_STORE
                            || e.kind == scc_core::kinds::DATA_ENTITY
                    })
                    .unwrap_or(false);
                let target_name = match view.entity(t) {
                    Some(e) if e.kind == scc_core::kinds::DATA_STORE => e.name.clone(),
                    Some(e) if e.kind == scc_core::kinds::DATA_ENTITY => e
                        .attributes
                        .get("store")
                        .and_then(|v| v.as_str())
                        .map(|s| format!("{s}.{}", e.name))
                        .unwrap_or_else(|| e.name.clone()),
                    _ => entity_name(view, t),
                };
                if is_store_target {
                    data_stores.insert(target_name.clone());
                    my_store_targets.push(target_name.clone());
                }
                owns.push(AtlasOwnershipClaim {
                    target: target_name,
                    provenance: p.to_string(),
                });
            }
        }
        // defensive dedupe: the same (target, provenance) pair may repeat
        // across claims
        let mut seen: BTreeSet<(String, String)> = BTreeSet::new();
        owns.retain(|o| seen.insert((o.target.clone(), o.provenance.clone())));

        // Ontology phase: hierarchical layer + immediate container (set by
        // the component compiler's clusterer; defaulted for pre-ontology
        // components so grouping stays total and deterministic).
        let layer = c
            .attributes
            .get("layer")
            .and_then(|v| v.as_str())
            .unwrap_or("component")
            .to_string();
        let parent = c
            .attributes
            .get("parent")
            .and_then(|v| v.as_str())
            .map(String::from);
        comp_store_targets.push((c.name.clone(), my_store_targets));

        components.push(AtlasComponent {
            name: c.name.clone(),
            purpose: purpose_text,
            implementation,
            implementation_paths,
            symbols,
            consumes: consumes.into_iter().collect(),
            produces: produces.into_iter().collect(),
            upstream: upstream.into_iter().collect(),
            downstream: downstream.into_iter().collect(),
            failure_behavior,
            owns,
            layer,
            parent,
            role,
        });
    }
    components.sort_by(|a, b| a.name.cmp(&b.name));

    // ---- scope: production component set ----
    // Component roles are presentation AND scope: every component lists
    // (structure stays visible), but owns/data-stores/public-api/framework
    // sections only admit production components by default. Unknown
    // components are kept — never drop facts we cannot place.
    let comp_role: HashMap<String, String> = components
        .iter()
        .map(|c| (c.name.clone(), c.role.clone()))
        .collect();
    let comp_role_by_id: HashMap<String, String> = view
        .components()
        .into_iter()
        .map(|c| {
            let paths: Vec<String> = c
                .attributes
                .get("implementation")
                .and_then(|v| v.get("paths"))
                .and_then(|v| v.as_array())
                .map(|a| {
                    a.iter()
                        .filter_map(|x| x.as_str().map(String::from))
                        .collect()
                })
                .unwrap_or_default();
            let role = c
                .attributes
                .get("role")
                .and_then(|v| v.as_str())
                .map(String::from)
                .unwrap_or_else(|| scc_graph::components::component_role(&paths).into());
            (c.id.clone(), role)
        })
        .collect();
    let prod_comp = |name: &str| -> bool {
        scope == AtlasScope::Full
            || comp_role.get(name).map(|r| r == "production").unwrap_or(true)
    };
    if scope == AtlasScope::Production {
        data_stores = comp_store_targets
            .into_iter()
            .filter(|(name, _)| prod_comp(name))
            .flat_map(|(_, tgts)| tgts)
            .collect();
    }

    let mut entrypoints: Vec<AtlasEntrypoint> = Vec::new();
    // Exact duplicates (same method+path+handler from overlapping evidence)
    // collapse to one line; distinct handlers stay visible so genuinely
    // ambiguous routes are never hidden.
    let mut seen_routes: BTreeSet<(String, String, String)> = BTreeSet::new();
    for r in scoped_entities(view, scc_core::kinds::ROUTE, scope, "entrypoints", &mut scoped_out) {
        let method = r
            .attributes
            .get("method")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let path = r
            .attributes
            .get("path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let handler = r
            .attributes
            .get("handler")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        if !seen_routes.insert((method.to_string(), path.to_string(), handler.clone())) {
            continue;
        }
        entrypoints.push(AtlasEntrypoint {
            name: r.name.clone(),
            kind: "route".into(),
            trigger: format!("{method} {path}"),
            symbol: handler,
        });
    }
    for e in scoped_entities(view, scc_core::kinds::SYMBOL, scope, "entrypoints", &mut scoped_out) {
        let Some(kinds) = e.attributes.get("entrypoints").and_then(|v| v.as_array()) else {
            continue;
        };
        if kinds.is_empty() {
            continue;
        }
        // extractor contract: entrypoint kinds are strings ("main-guard",
        // "cli-subcommand", ...); cli-subcommand entrypoints render as
        // `name [cli-subcommand]` instead of the generic kind
        let kind = if kinds.iter().any(|k| k.as_str() == Some("cli-subcommand")) {
            "cli-subcommand"
        } else {
            "entrypoint"
        };
        entrypoints.push(AtlasEntrypoint {
            name: e.name.clone(),
            kind: kind.into(),
            trigger: format!("entrypoint:{}", e.name),
            symbol: e.id.clone(),
        });
    }
    // Wave 9: invocation-surface seeds (public exports → public_api, queue
    // consumers → queue, framework callbacks → framework_callback,
    // lifecycle callbacks → lifecycle, event handlers → event). Additive and
    // deterministic (invocation_surfaces sorts its output). Deduped by
    // (name, kind): a symbol that is several surfaces at once (exported AND
    // callback registrar) renders under each kind — the atlas has no
    // unique-id constraint.
    let mut surface_names: BTreeSet<(String, String)> = entrypoints
        .iter()
        .map(|e| (e.name.clone(), e.kind.clone()))
        .collect();
    for s in scc_graph::flows::invocation_surfaces(view.graph) {
        if scope == AtlasScope::Production && entity_id_role(view, &s.symbol) != "production" {
            *scoped_out.entry("entrypoints".into()).or_default() += 1;
            continue;
        }
        let name = view.name_of(&s.symbol);
        let kind = s.kind.as_str().to_string();
        if !surface_names.insert((name.clone(), kind.clone())) {
            continue;
        }
        entrypoints.push(AtlasEntrypoint {
            name,
            kind,
            trigger: s.trigger.clone(),
            symbol: s.symbol.clone(),
        });
    }
    entrypoints.sort_by(|a, b| a.name.cmp(&b.name));

    // ---- contracts (Wave 9: first-class, typed) ----
    let mut contracts: Vec<scc_core::Contract> = Vec::new();
    let mut contract_seen: BTreeMap<(String, String), usize> = BTreeMap::new();

    // http: ROUTE entities (producer = handler symbol)
    for r in scoped_entities(view, scc_core::kinds::ROUTE, scope, "contracts", &mut scoped_out) {
        let method = r
            .attributes
            .get("method")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        let path = r
            .attributes
            .get("path")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if path.is_empty() {
            continue;
        }
        let handler = r
            .attributes
            .get("handler")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();
        let mut consumers: BTreeSet<String> = BTreeSet::new();
        for pred in [
            scc_core::predicates::HANDLES,
            scc_core::predicates::CONSUMES,
            scc_core::predicates::READS,
        ] {
            for rel in view.in_pred(&r.id, pred) {
                consumers.insert(entity_name(view, &rel.subject));
            }
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: r.id.clone(),
                kind: "http".into(),
                subclass: ContractSubclass::Http,
                producer: handler,
                consumers: consumers.into_iter().collect(),
                operations: vec![format!("{method} {path}").trim().to_string()],
                evidence: r.evidence.clone(),
            },
        );
    }

    // cli: SYMBOL entities carrying `cli_flags: ["--flag", ...]` attrs
    // (producer = the owning symbol)
    for e in scoped_entities(view, scc_core::kinds::SYMBOL, scope, "contracts", &mut scoped_out) {
        let Some(flags) = e.attributes.get("cli_flags").and_then(|v| v.as_array()) else {
            continue;
        };
        let mut ops: Vec<String> = flags
            .iter()
            .filter_map(|f| f.as_str().map(String::from))
            .collect();
        ops.sort();
        ops.dedup();
        if ops.is_empty() {
            continue;
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: scc_core::entity_id(
                    &store.repo_id,
                    scc_core::kinds::CONTRACT,
                    &format!("cli:{}", e.name),
                ),
                kind: "cli".into(),
                subclass: ContractSubclass::Cli,
                producer: e.id.clone(),
                consumers: Vec::new(),
                operations: ops,
                evidence: e.evidence.clone(),
            },
        );
    }

    // event: TOPIC entities with PUBLISHES/SUBSCRIBES edges (producer = the
    // topic; consumers = the publishing/subscribing symbols). Participant-
    // scoped: an unattributed topic is judged by its publishers, not kept
    // by default — fixture topics never reach the architecture sections.
    for t in view.entities_of_kind(scc_core::kinds::TOPIC) {
        let mut consumers: BTreeSet<String> = BTreeSet::new();
        let mut participant_ids: Vec<String> = Vec::new();
        let mut any = false;
        for pred in [
            scc_core::predicates::PUBLISHES,
            scc_core::predicates::SUBSCRIBES,
            scc_core::predicates::CONSUMES,
        ] {
            for rel in view.in_pred(&t.id, pred) {
                consumers.insert(entity_name(view, &rel.subject));
                participant_ids.push(rel.subject.clone());
                any = true;
            }
        }
        if !any {
            continue;
        }
        if scope == AtlasScope::Production {
            let self_prod = t
                .attributes
                .get("file")
                .and_then(|v| v.as_str())
                .and_then(scc_graph::components::path_role)
                .map(|r| r == "production")
                .unwrap_or(false);
            let parts_prod = participants_production(view, &participant_ids).unwrap_or(true);
            if !self_prod && !parts_prod {
                *scoped_out.entry("contracts".into()).or_default() += 1;
                continue;
            }
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: t.id.clone(),
                kind: "event".into(),
                subclass: ContractSubclass::Event,
                producer: t.id.clone(),
                consumers: consumers.into_iter().collect(),
                operations: vec![t.name.clone()],
                evidence: t.evidence.clone(),
            },
        );
    }

    // config: CONFIGURATION entities (producer = the owning symbol via
    // CONFIGURED_BY; consumers = READS edges + the configured-by symbols)
    for c in view.entities_of_kind(scc_core::kinds::CONFIGURATION) {
        if scope == AtlasScope::Production {
            let self_prod = c
                .attributes
                .get("file")
                .and_then(|v| v.as_str())
                .and_then(scc_graph::components::path_role)
                .map(|r| r == "production")
                .unwrap_or(false);
            if !self_prod {
                let mut party: Vec<String> = view
                    .out_pred(&c.id, scc_core::predicates::CONFIGURED_BY)
                    .into_iter()
                    .map(|r| r.object.clone())
                    .collect();
                for pred in [
                    scc_core::predicates::READS,
                    scc_core::predicates::CONSUMES,
                    scc_core::predicates::HANDLES,
                ] {
                    for rel in view.in_pred(&c.id, pred) {
                        party.push(rel.subject.clone());
                    }
                }
                if participants_production(view, &party) == Some(false) {
                    *scoped_out.entry("contracts".into()).or_default() += 1;
                    continue;
                }
            }
        }
        let mut owners: Vec<String> = view
            .out_pred(&c.id, scc_core::predicates::CONFIGURED_BY)
            .into_iter()
            .map(|r| r.object.clone())
            .collect();
        owners.sort();
        owners.dedup();
        let producer = owners.first().cloned().unwrap_or_else(|| c.id.clone());
        let mut consumers: BTreeSet<String> = BTreeSet::new();
        for pred in [
            scc_core::predicates::READS,
            scc_core::predicates::CONSUMES,
            scc_core::predicates::HANDLES,
        ] {
            for rel in view.in_pred(&c.id, pred) {
                consumers.insert(entity_name(view, &rel.subject));
            }
        }
        for o in &owners {
            consumers.insert(entity_name(view, o));
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: c.id.clone(),
                kind: "config".into(),
                subclass: ContractSubclass::Configuration,
                producer,
                consumers: consumers.into_iter().collect(),
                operations: vec![c.name.clone()],
                evidence: c.evidence.clone(),
            },
        );
    }

    // subclass contracts: CONTRACT entities carrying a first-class
    // registration kind (serialization/extension/plugin/rpc/message/schema/
    // call/factory/builder/...). Framework-specific registration kinds
    // (`include_router`, `add_middleware`, ...) map to None and stay
    // public-api: EXPORT entities whose export kind is a callable signature
    // (function/method/constructor) — the "public fn signature" surface.
    // The EXPORT entity's symbol is the EXPORTS edge subject; consumers are
    // the symbols that call it.
    for e in view.entities_of_kind(scc_core::kinds::EXPORT) {
        if scope == AtlasScope::Production && entity_role(view, e) != "production" {
            let sym_prod = view
                .in_pred(&e.id, scc_core::predicates::EXPORTS)
                .into_iter()
                .next()
                .map(|r| entity_id_role(view, &r.subject) == "production")
                .unwrap_or(true);
            if !sym_prod {
                *scoped_out.entry("contracts".into()).or_default() += 1;
                continue;
            }
        }
        let kind_attr = e
            .attributes
            .get("kind")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        if !matches!(kind_attr, "function" | "method" | "constructor") {
            continue;
        }
        let symbol = view
            .in_pred(&e.id, scc_core::predicates::EXPORTS)
            .into_iter()
            .next()
            .map(|r| r.subject.clone())
            .unwrap_or_default();
        let mut consumers: BTreeSet<String> = BTreeSet::new();
        for pred in [
            scc_core::predicates::CALLS,
            scc_core::predicates::CONSUMES,
            scc_core::predicates::HANDLES,
        ] {
            for rel in view.in_pred(&symbol, pred) {
                consumers.insert(entity_name(view, &rel.subject));
            }
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: e.id.clone(),
                kind: "public-api".into(),
                subclass: ContractSubclass::PublicApi,
                producer: symbol,
                consumers: consumers.into_iter().collect(),
                operations: vec![e.name.clone()],
                evidence: e.evidence.clone(),
            },
        );
    }

    // subclass contracts: CONTRACT entities carrying a first-class
    // registration kind (serialization/extension/plugin/rpc/message/schema/
    // call/factory/builder/...). Framework-specific registration kinds
    // (`include_router`, `add_middleware`, ...) map to None and stay
    // framework semantics (FRAMEWORK SEMANTICS), never first-class
    // contracts. Annotations are per-symbol framework semantics too — they
    // render under FRAMEWORK SEMANTICS, not here. Producer = the
    // registering symbol (REGISTERS subject); consumers = symbols consuming
    // the surface.
    for ce in scoped_entities(view, scc_core::kinds::CONTRACT, scope, "contracts", &mut scoped_out) {
        let Some(kind_attr) = ce
            .attributes
            .get("kind")
            .and_then(|v| v.as_str())
            .map(str::to_string)
        else {
            continue;
        };
        let Some(subclass) = ContractSubclass::from_kind_str(&kind_attr) else {
            continue;
        };
        let producer = view
            .in_pred(&ce.id, scc_core::predicates::REGISTERS)
            .into_iter()
            .next()
            .map(|r| r.subject.clone())
            .unwrap_or_default();
        let mut consumers: BTreeSet<String> = BTreeSet::new();
        for pred in [
            scc_core::predicates::CONSUMES,
            scc_core::predicates::READS,
            scc_core::predicates::HANDLES,
        ] {
            for rel in view.in_pred(&ce.id, pred) {
                consumers.insert(entity_name(view, &rel.subject));
            }
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: ce.id.clone(),
                kind: subclass.as_str().to_string(),
                subclass,
                producer,
                consumers: consumers.into_iter().collect(),
                operations: vec![ce.name.clone()],
                evidence: ce.evidence.clone(),
            },
        );
    }
    // schema: SCHEMA concepts (Wave 11/13) — the schema name, its composed
    // parents (COMPOSES edges, schema→parent) and validation lines (the
    // defining owner's VALIDATES edges) render per-subclass with the
    // `schema:` prefix: `schema: User`, `schema: User extends Base`,
    // `schema: User validates`. Producer = the most frequent occurrence
    // owner (a symbol, never the concept/expr itself).
    //
    // Inline constructions (name == expr, the `z.object({...})` test and
    // handler forms) are frequency-capped: only the *repeated* DSL surface
    // (count >= 2, top 40 by count) renders — one-off test schemas are
    // noise, not architecture, and would flood the contracts layer. The
    // count is DERIVED from the live OCCURRENCE entities — never a stored,
    // write-time-mutated counter.
    let mut inline: Vec<(usize, String)> = Vec::new();
    for s in scoped_entities(view, scc_core::kinds::SCHEMA, scope, "contracts", &mut scoped_out) {
        let count = scc_graph::state::occurrence_count(view.graph, &s.id);
        let expr = s
            .attributes
            .get("expr")
            .and_then(|v| v.as_str())
            .map(|e| e.to_string());
        let is_inline = expr.as_deref() == Some(s.name.as_str());
        let producer = scc_graph::state::occurrence_producer(view.graph, &s.id)
            .unwrap_or_else(|| s.id.clone());
        if is_inline {
            inline.push((count, s.id.clone()));
            continue;
        }
        let owner = view
            .in_pred(&s.id, scc_core::predicates::DEFINES)
            .into_iter()
            .next()
            .map(|r| r.subject.clone());
        let mut ops: Vec<String> = vec![s.name.clone()];
        // the defining expression (`z.object({ name: z.string() })`)
        // renders as `schema: <name> = <expr>` when the extractor
        // captured one — the concrete code form a human would quote.
        // Inline constructions use the expression itself as the name
        // (`schema: z.object({...})`); never render `X = X`.
        if let Some(e) = &expr {
            if !e.is_empty() && e != &s.name {
                ops.push(format!("{} = {}", s.name, e));
            }
        }
        let mut composed: Vec<String> = view
            .out_pred(&s.id, scc_core::predicates::COMPOSES)
            .into_iter()
            .map(|r| format!("{} extends {}", s.name, entity_name(view, &r.object)))
            .collect();
        composed.sort();
        composed.dedup();
        ops.extend(composed);
        if let Some(owner_id) = &owner {
            let mut validated: Vec<String> = view
                .out_pred(owner_id, scc_core::predicates::VALIDATES)
                .into_iter()
                .map(|_| format!("{} validates", s.name))
                .collect();
            validated.sort();
            validated.dedup();
            ops.extend(validated);
        }
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: s.id.clone(),
                kind: "schema".into(),
                subclass: ContractSubclass::Schema,
                producer,
                consumers: Vec::new(),
                operations: ops,
                evidence: s.evidence.clone(),
            },
        );
    }
    // repeated inline DSL forms (count desc, id asc for determinism)
    inline.sort_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1)));
    for (count, id) in inline.into_iter().take(40) {
        if count < 2 {
            continue;
        }
        let Some(s) = view.entity(&id) else { continue };
        let producer = scc_graph::state::occurrence_producer(view.graph, &s.id)
            .unwrap_or_else(|| s.id.clone());
        push_contract(
            &mut contracts,
            &mut contract_seen,
            scc_core::Contract {
                id: s.id.clone(),
                kind: "schema".into(),
                subclass: ContractSubclass::Schema,
                producer,
                consumers: Vec::new(),
                operations: vec![s.name.clone()],
                evidence: s.evidence.clone(),
            },
        );
    }
    // deterministic order for the machine model: per-subclass groups,
    // then by operation, then producer
    contracts.sort_by(|a, b| {
        a.subclass
            .as_str()
            .cmp(b.subclass.as_str())
            .then(a.operations.join("\u{1}").cmp(&b.operations.join("\u{1}")))
            .then(a.producer.cmp(&b.producer))
    });

    // ---- flows: SEQUENCES project from the canonical FlowGraph (P1 §18);
    // the old linear flows table is never the atlas's sequence source ----
    let mut flows: Vec<AtlasFlow> = Vec::new();
    let mut async_boundaries: BTreeSet<String> = BTreeSet::new();
    for g in store.flow_graphs().unwrap_or_default() {
        if g.kind != scc_core::FlowKind::Sequence {
            continue;
        }
        if !keep_flow(
            view,
            &comp_role_by_id,
            scope,
            &g.nodes.iter().map(|n| n.actor.clone()).collect::<Vec<_>>(),
        ) {
            *scoped_out.entry("flows".into()).or_default() += 1;
            continue;
        }
        let steps = project_flow_graph(view, &g, &mut async_boundaries);
        if steps.is_empty() {
            continue;
        }
        flows.push(AtlasFlow {
            name: g.name.clone(),
            kind: g.kind,
            trigger: g.trigger.clone(),
            steps,
        });
    }
    // derived views (workflow/dataflow/lifecycle) still come from the
    // derived compilers — but lifecycle is SIGNALS, never authoritative
    for f in view.flows() {
        if f.kind == scc_core::FlowKind::Sequence {
            continue; // sequences come from the canonical graphs
        }
        if !keep_flow(
            view,
            &comp_role_by_id,
            scope,
            &f.steps.iter().map(|s| s.actor.clone()).collect::<Vec<_>>(),
        ) {
            *scoped_out.entry("flows".into()).or_default() += 1;
            continue;
        }
        let mut steps: Vec<String> = Vec::new();
        let mut prev_actor: Option<String> = None;
        for s in &f.steps {
            let actor = entity_name(view, &s.actor);
            let mut line = if prev_actor.as_deref() == Some(actor.as_str()) {
                format!("  -> {}", s.operation)
            } else {
                format!("{}: {}", actor, s.operation)
            };
            if s.r#async == Some(true) {
                line.push_str(" [async]");
            }
            if let Some(c) = &s.condition {
                line.push_str(&format!(" (if {c})"));
            }
            if let Some(rp) = &s.retry_policy {
                line.push_str(&format!(" [retry: {rp}]"));
            }
            if let Some(fo) = &s.failure_outcome {
                line.push_str(&format!(" [fail: {fo}]"));
            }
            steps.push(line);
            prev_actor = Some(actor);
        }
        if f.attributes.get("signals_only").and_then(|v| v.as_bool()) == Some(true) {
            flows.push(AtlasFlow {
                name: format!("{} (LIFECYCLE SIGNALS — NOT VERIFIED TRANSITIONS)", f.name),
                kind: f.kind,
                trigger: f.trigger.clone(),
                steps,
            });
        } else {
            flows.push(AtlasFlow {
                name: f.name.clone(),
                kind: f.kind,
                trigger: f.trigger.clone(),
                steps,
            });
        }
    }
    flows.sort_by(|a, b| a.name.cmp(&b.name));

    // ---- invariants ----
    let invariants: Vec<AtlasInvariant> = view
        .invariants()
        .into_iter()
        .map(|i| AtlasInvariant {
            statement: i.statement,
            severity: i.severity,
        })
        .collect();

    // ---- deployment / externals / trust boundaries ----
    let deployment_units: Vec<String> = scoped_entities(
        view,
        scc_core::kinds::DEPLOYMENT_UNIT,
        scope,
        "deployment",
        &mut scoped_out,
    )
    .into_iter()
        .map(|e| {
            let img = e
                .attributes
                .get("image")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            if img.is_empty() {
                e.name.clone()
            } else {
                format!("{} ({})", e.name, img)
            }
        })
        .collect();
    let external_systems: Vec<String> = scoped_entities(
        view,
        scc_core::kinds::EXTERNAL_API,
        scope,
        "external-systems",
        &mut scoped_out,
    )
    .into_iter()
        .map(|e| e.name.clone())
        .collect();
    let trust_boundaries: Vec<String> = if scope == AtlasScope::Full {
        scc_graph::boundaries::boundary_crossings(view.graph, store).unwrap_or_default()
    } else {
        scc_graph::boundaries::production_crossings(view.graph, store).unwrap_or_default()
    };

    // ---- implementation map ----
    let mut implementation_map: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for c in &components {
        implementation_map.insert(c.name.clone(), c.implementation_paths.clone());
    }

    // ---- evidence + warnings + freshness ----
    let comp_ids: Vec<String> = view
        .components()
        .into_iter()
        .map(|c| c.id.clone())
        .collect();
    let evidence_summary = ctx.evidence_summary(&comp_ids);

    let mut warnings: Vec<String> = Vec::new();
    let stale = view.stale_paths();
    if snapshot.is_some() {
        if stale.is_empty() {
            warnings.push("Model is FRESH".into());
        } else {
            warnings.push(format!(
                "Model is stale: {} changed file(s) not yet re-indexed.",
                stale.len()
            ));
        }
    } else {
        warnings.push("Repository is NOT indexed — run `scc index`.".into());
    }
    warnings.extend(view.stale_warnings());

    let freshness = if snapshot.is_none() {
        "NOT INDEXED".to_string()
    } else if stale.is_empty() {
        "FRESH".to_string()
    } else {
        format!("STALE ({})", stale.len())
    };

    // ---- Ontology phase: archetype + STATE & DATA AUTHORITY + hierarchy ----
    let archetype = Some(scc_graph::archetype::detect_archetype(view.graph, store));

    // symbol -> component name over the *stored* components (the state
    // compiler attributes ownership per component from the fact layer)
    let mut symbol_comp: HashMap<String, String> = HashMap::new();
    for c in view.components() {
        for r in view.out_pred(&c.id, scc_core::predicates::CONTAINS) {
            for sr in view.out_pred(&r.object, scc_core::predicates::CONTAINS) {
                symbol_comp.insert(sr.object.clone(), c.name.clone());
            }
        }
    }
    let mut state_authority = scc_graph::state::compile_state_authority(view.graph, &symbol_comp);
    // State lines read `{comp} owns/reads …` / `{comp}::{sym} …`: the
    // leading component attributes the claim. Non-production components
    // never own production state in the default scope.
    if scope == AtlasScope::Production {
        for lines in state_authority.values_mut() {
            let before = lines.len();
            lines.retain(|l| {
                let head = l.split([' ', ':']).next().unwrap_or("");
                prod_comp(head)
            });
            let dropped = before - lines.len();
            if dropped > 0 {
                *scoped_out.entry("state-authority".into()).or_default() += dropped;
            }
        }
    }

    // hierarchical containers: services first, then subsystems; members are
    // direct member entity ids (component ids or nested subsystem ids)
    let mut hierarchy: Vec<AtlasHierarchyNode> = Vec::new();
    for kind in [scc_core::kinds::SERVICE, scc_core::kinds::SUBSYSTEM] {
        for e in view.graph.entities_of_kind(kind) {
            let mut members: Vec<String> = view
                .graph
                .out_pred(&e.id, scc_core::predicates::CONTAINS)
                .into_iter()
                .map(|r| r.object.clone())
                .collect();
            members.sort();
            hierarchy.push(AtlasHierarchyNode {
                id: e.id.clone(),
                name: e.name.clone(),
                kind: kind.to_string(),
                members,
            });
        }
    }
    hierarchy.sort_by(|a, b| a.kind.cmp(&b.kind).then_with(|| a.name.cmp(&b.name)));

    // ---- STATE & DATA AUTHORITY: structured bridge ----
    // The state compiler's per-component claims (mutable fields, STATE/
    // REGISTRY entities, configuration targets, topics, middleware/registry
    // registrations, store writes) become component `owns` claims too, so
    // the state fact layer is part of the machine model — not just rendered
    // text. Provenance preserved; deduped by (target, provenance).
    let state_claims = scc_graph::state::compile_state_claims(view.graph, &symbol_comp);
    for claim in state_claims {
        if !prod_comp(&claim.component) {
            *scoped_out.entry("state-authority".into()).or_default() += 1;
            continue;
        }
        let Some(c) = components.iter_mut().find(|c| c.name == claim.component) else {
            continue;
        };
        let seen_claim = (claim.target.clone(), claim.provenance.clone());
        if claim.verb == "reads" {
            continue;
        }
        if !c
            .owns
            .iter()
            .any(|o| o.target == seen_claim.0 && o.provenance == seen_claim.1)
        {
            c.owns.push(AtlasOwnershipClaim {
                target: claim.target,
                provenance: claim.provenance,
            });
        }
    }
    for c in &mut components {
        if scope == AtlasScope::Production
            && comp_role.get(&c.name).map(|r| r != "production").unwrap_or(false)
        {
            let n = c.owns.len();
            c.owns.clear();
            if n > 0 {
                *scoped_out.entry("state-authority".into()).or_default() += n;
            }
        }
        c.owns.sort_by(|a, b| {
            a.target
                .cmp(&b.target)
                .then(a.provenance.cmp(&b.provenance))
        });
    }

    // ---- PUBLIC API (Wave 10): exports grouped by component ----
    // EXPORT entities (extractor-emitted public-export facts) plus symbols
    // the extractor statically marked `exported: true` at module level.
    // Grouped by the exporting symbol's component.
    let mut public_api: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    // EXPORT entities: the exporting symbol is the EXPORTS relationship
    // subject; its name matches the export entity name.
    for r in view.all_rels() {
        if r.predicate != scc_core::predicates::EXPORTS {
            continue;
        }
        let Some(comp) = symbol_comp.get(&r.subject) else {
            continue;
        };
        if !prod_comp(comp) {
            *scoped_out.entry("public-api".into()).or_default() += 1;
            continue;
        }
        if let Some(name) = view.entity(&r.object).map(|e| e.name.clone()) {
            if !name.is_empty() {
                public_api.entry(comp.clone()).or_default().insert(name);
            }
        }
    }
    // exported module-level symbols (`exported: true`, no `.` in the name)
    for e in view.entities_of_kind(scc_core::kinds::SYMBOL) {
        if e.name.is_empty() || e.name.starts_with('_') || e.name.contains('.') {
            continue;
        }
        if e.attributes.get("exported").and_then(|v| v.as_bool()) != Some(true) {
            continue;
        }
        let Some(comp) = symbol_comp.get(&e.id) else {
            continue;
        };
        if !prod_comp(comp) {
            *scoped_out.entry("public-api".into()).or_default() += 1;
            continue;
        }
        public_api
            .entry(comp.clone())
            .or_default()
            .insert(e.name.clone());
    }
    let public_api: BTreeMap<String, Vec<String>> = public_api
        .into_iter()
        .map(|(k, v)| (k, v.into_iter().collect()))
        .collect();

    // ---- FRAMEWORK SEMANTICS (Wave 10): annotations / registrations /
    // callbacks grouped by component ----
    let mut framework_semantics: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    // annotations: ANNOTATION entity ANNOTATES target symbol
    for a in view.entities_of_kind(scc_core::kinds::ANNOTATION) {
        let mut rels = view.out_pred(&a.id, scc_core::predicates::ANNOTATES);
        rels.sort_by(|x, y| x.object.cmp(&y.object));
        for r in rels {
            if let Some(comp) = symbol_comp.get(&r.object) {
                if !prod_comp(comp) {
                    *scoped_out.entry("framework".into()).or_default() += 1;
                    continue;
                }
                let target = entity_name(view, &r.object);
                framework_semantics
                    .entry(comp.clone())
                    .or_default()
                    .insert(format!("annotates {target} ({})", a.name));
            }
        }
    }
    // REGISTERS + HANDLES_CALLBACK: symbol -> target
    for pred in [
        scc_core::predicates::REGISTERS,
        scc_core::predicates::HANDLES_CALLBACK,
    ] {
        let mut rels = view.all_rels().to_vec();
        rels.sort_by(|x, y| {
            x.subject
                .cmp(&y.subject)
                .then(x.object.cmp(&y.object))
                .then(x.id.cmp(&y.id))
        });
        for r in rels {
            if r.predicate != pred {
                continue;
            }
            let Some(comp) = symbol_comp.get(&r.subject) else {
                continue;
            };
            if !prod_comp(comp) {
                *scoped_out.entry("framework".into()).or_default() += 1;
                continue;
            }
            let target = entity_name(view, &r.object);
            let line = if pred == scc_core::predicates::REGISTERS {
                format!("registers {target}")
            } else {
                format!("handles callback {target}")
            };
            framework_semantics
                .entry(comp.clone())
                .or_default()
                .insert(line);
        }
    }
    let framework_semantics: BTreeMap<String, Vec<String>> = framework_semantics
        .into_iter()
        .map(|(k, v)| (k, v.into_iter().collect()))
        .collect();

    // ---- PIPELINE (Wave 10): phase-named symbols grouped by stage ----
    // Rendered only for the CompilerLanguageTool archetype: symbols whose
    // name contains a phase verb, plus phase-named files (`1-parse`-style
    // stage directories). Grouped by stage; bounded.
    let pipeline = build_pipeline(view, archetype);

    // ---- LANDMARKS (Wave 10): notable exports + annotated targets,
    // bounded (~40) ----
    let landmarks = build_landmarks(view, &public_api, &symbol_comp, scope, &comp_role, &mut scoped_out);

    SystemAtlas {
        repository: repo.name,
        revision: snapshot
            .as_ref()
            .map(|s| s.revision.clone())
            .unwrap_or_else(|| "not-indexed".to_string()),
        indexed_at: snapshot.map(|s| s.indexed_at).unwrap_or_default(),
        freshness,
        purpose,
        components,
        entrypoints,
        contracts,
        coverage: {
            let mut coverage = compute_coverage(ctx);
            let scoped_total: usize = scoped_out.values().sum();
            let scope_line = if scope == AtlasScope::Full {
                "full (every repository role feeds the architecture sections)".to_string()
            } else if scoped_total == 0 {
                "production (no non-production architecture facts found)".to_string()
            } else {
                let parts: Vec<String> = scoped_out
                    .iter()
                    .map(|(k, v)| format!("{k}:{v}"))
                    .collect();
                format!(
                    "production ({} non-production facts scoped out of architecture sections: {}; components/files still list all roles)",
                    scoped_total,
                    parts.join(", ")
                )
            };
            coverage.insert("scope".to_string(), scope_line);
            coverage
        },
        flows,
        invariants,
        deployment_units,
        external_systems,
        trust_boundaries,
        async_boundaries: async_boundaries.into_iter().collect(),
        implementation_map,
        data_stores: data_stores.into_iter().collect(),
        archetype,
        state_authority,
        hierarchy,
        evidence_summary,
        warnings,
        public_api,
        framework_semantics,
        pipeline,
        landmarks,
    }
}

/// Phase-stage verbs for the PIPELINE section (CompilerLanguageTool
/// archetype): a symbol whose name contains a stage verb is a phase symbol.
const PIPELINE_STAGES: [(&str, &[&str]); 5] = [
    (
        "parse",
        &[
            "parse",
            "parser",
            "lexer",
            "lex",
            "tokenize",
            "tokeniser",
            "ast",
        ],
    ),
    ("analyze", &["analyze", "analyse", "analysis"]),
    (
        "transform",
        &["transform", "lower", "resolve", "resolveconfig"],
    ),
    (
        "generate",
        &["generate", "generator", "codegen", "compile", "compiler"],
    ),
    (
        "emit",
        &["emit", "print", "format", "formatdoc", "serialize"],
    ),
];

/// PIPELINE (Wave 10): phase-named symbols grouped by stage, plus
/// phase-named file paths (`1-parse`-style stage dirs). Only rendered for
/// the CompilerLanguageTool archetype. Deterministic: sorted by
/// (stage-rank, name); bounded to keep the section compact.
// trace:exempt reason=internal-detail
fn build_pipeline(view: &TrustedGraphView, archetype: Option<scc_core::Archetype>) -> Vec<String> {
    if archetype != Some(scc_core::Archetype::CompilerLanguageTool) {
        return Vec::new();
    }
    let mut lines: Vec<(usize, String)> = Vec::new();
    let mut seen: BTreeSet<String> = BTreeSet::new();
    let stage_of = |name: &str| -> Option<usize> {
        let lower = name.to_ascii_lowercase();
        PIPELINE_STAGES
            .iter()
            .position(|(_, verbs)| verbs.iter().any(|v| lower.contains(v)))
    };
    // phase-named symbols (module-level and method symbols)
    for e in view.entities_of_kind(scc_core::kinds::SYMBOL) {
        if e.name.is_empty() {
            continue;
        }
        let Some(rank) = stage_of(&e.name) else {
            continue;
        };
        if !seen.insert(e.name.clone()) {
            continue;
        }
        lines.push((rank, e.name.clone()));
    }
    // phase-named files: `phases/1-parse/index.js` or a `1-parse`-style
    // directory segment, or a path segment containing a stage verb
    for f in view.entities_of_kind(scc_core::kinds::FILE) {
        let name = f.name.clone();
        let lower = name.to_ascii_lowercase();
        let mut rank: Option<usize> = None;
        for (i, (_, verbs)) in PIPELINE_STAGES.iter().enumerate() {
            // digit-prefixed stage dirs: `1-parse`, `2-analyze`, `3-transform`
            let numbered = verbs.iter().any(|v| {
                lower.contains(&format!("/{v}"))
                    || lower.split('/').any(|seg| {
                        let seg = seg.trim_start_matches(|c: char| c.is_ascii_digit());
                        seg.trim_start_matches(['-', '_']).starts_with(v)
                    })
            });
            if numbered {
                rank = Some(i);
                break;
            }
        }
        if rank.is_none() && lower.contains("/phases/") {
            rank = Some(0); // compiler phase tree without a matched verb
        }
        if let Some(r) = rank {
            if seen.insert(name.clone()) {
                lines.push((r, name));
            }
        }
    }
    lines.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
    let mut out: Vec<String> = Vec::new();
    let mut current_stage: Option<&str> = None;
    for (rank, name) in lines.into_iter().take(96) {
        let stage = PIPELINE_STAGES[rank].0;
        if current_stage != Some(stage) {
            out.push(format!("[{}]", stage));
            current_stage = Some(stage);
        }
        out.push(format!("  {name}"));
    }
    out
}

/// LANDMARKS (Wave 10): notable exports + annotated targets, bounded (~40).
/// Exports: the component-sorted public API, preferring classes then
/// functions, capped. Annotated targets: symbols an ANNOTATION/REGISTERS
/// fact targets (framework-decorated code). Deterministic: sorted.
// trace:exempt reason=internal-detail
fn build_landmarks(
    view: &TrustedGraphView,
    public_api: &BTreeMap<String, Vec<String>>,
    symbol_comp: &HashMap<String, String>,
    scope: AtlasScope,
    comp_role: &HashMap<String, String>,
    scoped_out: &mut BTreeMap<String, usize>,
) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();
    let mut seen: BTreeSet<String> = BTreeSet::new();
    // notable exports: exported classes first, then other exports, capped
    let mut classes: Vec<String> = Vec::new();
    let mut others: Vec<String> = Vec::new();
    for names in public_api.values() {
        for n in names {
            let kind = view
                .entities_of_kind(scc_core::kinds::SYMBOL)
                .into_iter()
                .find(|e| e.name == *n)
                .and_then(|e| e.attributes.get("kind"))
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let is_class = matches!(
                kind,
                "class" | "struct" | "trait" | "interface" | "enum" | "type" | "module" | "model"
            );
            if is_class {
                classes.push(n.clone());
            } else {
                others.push(n.clone());
            }
        }
    }
    classes.sort();
    others.sort();
    let mut pool: Vec<String> = classes;
    pool.extend(others);
    for n in pool.into_iter().take(24) {
        if seen.insert(n.clone()) {
            out.push(format!("export {}", n));
        }
    }
    // annotated targets (framework-decorated symbols), capped.
    // Component-scoped: a test-only decorator target is not a landmark.
    let mut targets: Vec<String> = Vec::new();
    for a in view.entities_of_kind(scc_core::kinds::ANNOTATION) {
        for r in view.out_pred(&a.id, scc_core::predicates::ANNOTATES) {
            if let Some(comp) = symbol_comp.get(&r.object) {
                if scope == AtlasScope::Production
                    && comp_role.get(comp).map(|r| r != "production").unwrap_or(false)
                {
                    *scoped_out.entry("landmarks".into()).or_default() += 1;
                    continue;
                }
                let name = entity_name(view, &r.object);
                if !name.is_empty() && !name.starts_with('_') {
                    targets.push(format!("{name} (@{})", a.name));
                }
                let _ = comp;
            }
        }
    }
    targets.sort();
    targets.dedup();
    for t in targets.into_iter().take(16) {
        if seen.insert(t.clone()) {
            out.push(t);
        }
    }
    out
}

/// Push one contract, merging consumers/evidence when the same
/// (subclass, operations) surface was already recorded (e.g. the same CLI
/// flag owned by two symbols). Deterministic: consumers/evidence stay
/// sorted.
fn push_contract(
    contracts: &mut Vec<scc_core::Contract>,
    seen: &mut BTreeMap<(String, String), usize>,
    c: scc_core::Contract,
) {
    let key = (c.subclass.as_str().to_string(), c.operations.join("\u{1}"));
    if let Some(&idx) = seen.get(&key) {
        let existing = &mut contracts[idx];
        for s in c.consumers {
            if !existing.consumers.contains(&s) {
                existing.consumers.push(s);
            }
        }
        for e in c.evidence {
            if !existing.evidence.contains(&e) {
                existing.evidence.push(e);
            }
        }
        existing.consumers.sort();
        existing.evidence.sort();
        return;
    }
    seen.insert(key, contracts.len());
    contracts.push(c);
}

/// Languages with a real extractor come from `LANGUAGE_REGISTRY`. Files in
/// any other language are scanned but never parsed — the honest `unparsed`
/// remainder of the coverage map.
// trace:exempt reason=internal-detail
fn is_extractor_language(lang: &str) -> bool {
    language_by_id(lang).is_some_and(|c| c.extractor)
}

/// Deterministic model-coverage facts (Wave 9): what the model knows AND
/// what it does not. Every line is computed from the trusted view + store —
/// no heuristics, no fabrication; when a quantity is unobservable the line
/// says so explicitly.
// trace:exempt reason=internal-detail
fn compute_coverage(ctx: &ContextCompiler) -> BTreeMap<String, String> {
    let view = &ctx.view;
    let store = ctx.store;
    let mut out: BTreeMap<String, String> = BTreeMap::new();

    // ---- parsed source files % ----
    let files = store.all_files().unwrap_or_default();
    let total = files.len();
    let parsed = files
        .iter()
        .filter(|(_, _, lang, _, _)| is_extractor_language(lang))
        .count();
    let pct = parsed
        .checked_mul(100)
        .map(|n| n / total.max(1))
        .unwrap_or(0);
    out.insert(
        "parsed_source_files".to_string(),
        format!("{pct}% ({parsed}/{total})"),
    );

    // ---- exported API identified ----
    let exports = view.entities_of_kind(scc_core::kinds::EXPORT);
    let export_edges = view
        .all_rels()
        .iter()
        .filter(|r| r.predicate == scc_core::predicates::EXPORTS)
        .count();
    out.insert(
        "exported_api".to_string(),
        if exports.is_empty() {
            "none (no EXPORTS evidence)".to_string()
        } else {
            format!(
                "{} export entit{} ({} EXPORTS edges)",
                exports.len(),
                if exports.len() == 1 { "y" } else { "ies" },
                export_edges
            )
        },
    );

    // ---- call targets resolved % ----
    // RESOLVED (compiler/LSP proof) + EXTRACTED calls with a target that
    // resolves to an existing entity (symbol or external API), over every
    // stored CALLS edge. Unresolved calls are never persisted, so the
    // interesting limit is the LSP-vs-candidate split plus the
    // external/dynamic receiver count below.
    let calls: Vec<&scc_core::Relationship> = view
        .all_rels()
        .into_iter()
        .filter(|r| r.predicate == scc_core::predicates::CALLS)
        .collect();
    let total_calls = calls.len();
    let lsp_resolved = calls
        .iter()
        .filter(|r| r.provenance == scc_core::Provenance::Resolved)
        .count();
    let with_target = calls
        .iter()
        .filter(|r| {
            matches!(
                r.provenance,
                scc_core::Provenance::Resolved | scc_core::Provenance::Extracted
            ) && view.entity(&r.object).is_some()
        })
        .count();
    let pct = with_target
        .checked_mul(100)
        .map(|n| n / total_calls.max(1))
        .unwrap_or(0);
    out.insert(
        "call_targets_resolved".to_string(),
        if pct >= 100 {
            format!("{pct}% ({with_target}/{total_calls}, {lsp_resolved} LSP-RESOLVED)")
        } else {
            format!("{pct}% ({with_target}/{total_calls}, {lsp_resolved} LSP-RESOLVED) — exploration still justified in unresolved regions")
        },
    );

    // ---- dynamic receivers unresolved ----
    // Calls whose target is not a local symbol (external/dynamic receivers)
    // are stored with the external target; unknown-receiver calls are not
    // persisted at all — reported honestly as such.
    let unresolved = calls
        .iter()
        .filter(|r| {
            r.provenance != scc_core::Provenance::Resolved
                && view
                    .entity(&r.object)
                    .map(|e| e.kind != scc_core::kinds::SYMBOL)
                    .unwrap_or(true)
        })
        .count();
    out.insert(
        "dynamic_receivers_unresolved".to_string(),
        format!(
            "{unresolved} (calls whose target is not a local symbol; unknown-receiver calls are not persisted)"
        ),
    );

    // ---- invocation surfaces ----
    let surfaces = scc_graph::flows::invocation_surfaces(view.graph);
    let mut by_kind: BTreeMap<&str, usize> = BTreeMap::new();
    for s in &surfaces {
        *by_kind.entry(s.kind.as_str()).or_insert(0) += 1;
    }
    let summary: Vec<String> = by_kind.iter().map(|(k, v)| format!("{k} {v}")).collect();
    out.insert(
        "invocation_surfaces".to_string(),
        format!("{} ({})", surfaces.len(), summary.join(", ")),
    );

    // ---- framework registrations unknown ----
    let known_regs = view
        .all_rels()
        .iter()
        .filter(|r| r.predicate == scc_core::predicates::REGISTERS)
        .count();
    out.insert(
        "framework_registrations_unknown".to_string(),
        format!("0 ({known_regs} known registrations — unknown surfaces only reported with registry evidence)"),
    );

    // ---- stale evidence ----
    let stale = view.stale_paths();
    out.insert(
        "stale_evidence".to_string(),
        if stale.is_empty() {
            "0 (model FRESH)".to_string()
        } else {
            format!("{} changed file(s)", stale.len())
        },
    );

    // ---- unparsed files ----
    let unparsed = files
        .iter()
        .filter(|(_, _, lang, _, _)| !is_extractor_language(lang))
        .count();
    out.insert(
        "unparsed_files".to_string(),
        format!("{unparsed} (config/docs/infra — scanned but not source-parsed)"),
    );

    // ---- model epoch generations ----
    let epoch = store.model_epoch().unwrap_or(scc_store::ModelEpoch::zero());
    let gens = epoch.source
        + epoch.semantic
        + epoch.evidence
        + epoch.intent
        + epoch.runtime
        + epoch.derived;
    out.insert(
        "model_epoch_generations".to_string(),
        format!(
            "{gens} (source {}, semantic {}, evidence {}, intent {}, runtime {}, derived {})",
            epoch.source,
            epoch.semantic,
            epoch.evidence,
            epoch.intent,
            epoch.runtime,
            epoch.derived
        ),
    );

    out
}

/// Render the atlas as compact structured text (agent-facing).
/// `full` is the human `--unbounded` mode: soft legacy render that may
/// exceed the budget (reported, never silent). Agent/MCP paths always
/// pass false.
// trace:v1 id=impl.scc.atlas.render work=WORK-SCC-001 satisfies=REQ-state-function-access,REQ-SCC-CTX
pub fn render_atlas(
    ctx: &ContextCompiler,
    atlas: &SystemAtlas,
    budget: usize,
    full: bool,
) -> ContextPack {
    let mut pack = ContextPack::new("atlas", &atlas.revision);
    let mut sections: Vec<Section> = Vec::new();

    // SYSTEM PURPOSE (never cut); the ARCHETYPE header is the ontology
    // phase's one-line classification of the repository.
    let mut purpose = String::new();
    purpose.push_str(&format!(
        "ARCHETYPE: {}\n",
        atlas
            .archetype
            .map(|a| a.as_str())
            .unwrap_or(Archetype::Unknown.as_str())
    ));
    if !atlas.purpose.is_empty() {
        purpose.push_str(&format!(
            "[SYSTEM PURPOSE — from README, DOCUMENTATION not fact]\n{}\n",
            atlas.purpose
        ));
    }
    if !atlas.entrypoints.is_empty() {
        purpose.push_str("ENTRYPOINTS\n");
        // bounded render: the full structured list stays in the machine
        // model; the agent-facing artifact caps the listing (a framework
        // repo can have thousands of export surfaces).
        const EP_RENDER_CAP: usize = 200;
        for e in atlas.entrypoints.iter().take(EP_RENDER_CAP) {
            // Framework-surface kinds render as compact `kind: name` lines
            // (`queue: consume_order`, `schedule: daily_job`,
            // `plugin: register_hook`, `lifecycle: @BeforeAll` — the
            // lifecycle line names the hook annotation). Classic
            // http/cli/public_api/route/entrypoint lines keep the
            // `name [kind] — trigger` form.
            match e.kind.as_str() {
                "queue" | "schedule" | "plugin" | "lifecycle" => {
                    let label = if e.kind == "lifecycle" {
                        e.trigger
                            .strip_prefix("lifecycle:")
                            .map(|a| format!("@{a}"))
                            .unwrap_or_else(|| e.name.clone())
                    } else {
                        e.name.clone()
                    };
                    purpose.push_str(&format!("  {}: {}\n", e.kind, label));
                }
                _ => {
                    if e.trigger == e.name {
                        purpose.push_str(&format!("  {} [{}]\n", e.name, e.kind));
                    } else {
                        purpose.push_str(&format!("  {} [{}] — {}\n", e.name, e.kind, e.trigger));
                    }
                }
            }
        }
        if atlas.entrypoints.len() > EP_RENDER_CAP {
            purpose.push_str(&format!(
                "  ... +{} more (full list in the machine model)\n",
                atlas.entrypoints.len() - EP_RENDER_CAP
            ));
        }
    }
    sections.push(Section::new("SYSTEM PURPOSE", purpose, 10));

    // ARCHITECTURE (component blocks), grouped by layer: services first,
    // then subsystems, then unmerged components, code-regions last — with
    // `parent` indentation under service/subsystem headers. The flat block
    // format is preserved inside each group.
    let mut arch = String::new();
    let mut rendered: BTreeSet<String> = BTreeSet::new(); // names under containers
    let comp_block = |c: &AtlasComponent, indent: &str| -> String {
        let mut out = format!("\n{}{}", indent, c.name.to_uppercase());
        // Role scoping at the render boundary: test/fixture/benchmark
        // trees stay visible as structure but are never mistaken for
        // production architecture. Production renders unlabeled.
        if !c.role.is_empty() && c.role != "production" {
            out.push_str(&format!(" [{}]", c.role));
        }
        if !c.purpose.is_empty() {
            out.push_str(&format!("\n{}Purpose: {}", indent, c.purpose));
        }
        if !c.implementation_paths.is_empty() {
            out.push_str(&format!(
                "\n{}Implementation: {}",
                indent,
                c.implementation_paths.join(", ")
            ));
            if !c.symbols.is_empty() {
                out.push_str(&format!(" ({} member symbols)", c.symbols.len()));
            }
        }
        if !c.consumes.is_empty() {
            out.push_str(&format!("\n{}Consumes: {}", indent, c.consumes.join(", ")));
        }
        if !c.produces.is_empty() {
            out.push_str(&format!("\n{}Produces: {}", indent, c.produces.join(", ")));
        }
        if !c.upstream.is_empty() {
            out.push_str(&format!("\n{}Upstream: {}", indent, c.upstream.join(", ")));
        }
        if !c.downstream.is_empty() {
            out.push_str(&format!(
                "\n{}Downstream: {}",
                indent,
                c.downstream.join(", ")
            ));
        }
        if !c.owns.is_empty() {
            let owned: Vec<String> = c
                .owns
                .iter()
                .map(|o| format!("{} ({})", o.target, o.provenance))
                .collect();
            out.push_str(&format!("\n{}Owns: {}", indent, owned.join(", ")));
        }
        out.push('\n');
        out
    };
    let name_of = |id: &str| -> Option<String> { ctx.view.entity(id).map(|e| e.name.clone()) };
    // services first: nested subsystems, then directly-contained components
    for svc in atlas.hierarchy.iter().filter(|n| n.kind == "service") {
        arch.push_str(&format!("\nSERVICE {}\n", svc.name.to_uppercase()));
        for m in &svc.members {
            let Some(sub) = atlas.hierarchy.iter().find(|n| &n.id == m) else {
                continue;
            };
            if sub.kind != "subsystem" {
                continue;
            }
            arch.push_str(&format!("  SUBSYSTEM {}\n", sub.name.to_uppercase()));
            for cm in &sub.members {
                if let Some(name) = name_of(cm) {
                    rendered.insert(name.clone());
                    if let Some(c) = atlas.components.iter().find(|c| c.name == name) {
                        arch.push_str(&format!("    {}\n", comp_block(c, "    ").trim_end()));
                    }
                }
            }
            arch.push('\n');
        }
        for m in &svc.members {
            if atlas.hierarchy.iter().any(|n| &n.id == m) {
                continue; // subsystems rendered above
            }
            if let Some(name) = name_of(m) {
                rendered.insert(name.clone());
                if let Some(c) = atlas.components.iter().find(|c| c.name == name) {
                    arch.push_str(&format!("  {}\n", comp_block(c, "  ").trim_end()));
                }
            }
        }
    }
    // standalone subsystems (not nested inside a service)
    for sub in atlas.hierarchy.iter().filter(|n| n.kind == "subsystem") {
        if atlas
            .hierarchy
            .iter()
            .any(|n| n.kind == "service" && n.members.contains(&sub.id))
        {
            continue;
        }
        arch.push_str(&format!("\nSUBSYSTEM {}\n", sub.name.to_uppercase()));
        for cm in &sub.members {
            if let Some(name) = name_of(cm) {
                rendered.insert(name.clone());
                if let Some(c) = atlas.components.iter().find(|c| c.name == name) {
                    arch.push_str(&format!("  {}\n", comp_block(c, "  ").trim_end()));
                }
            }
        }
        arch.push('\n');
    }
    // unmerged components (evidence-backed), then bare code regions
    for layer in ["component", "code_region"] {
        for c in &atlas.components {
            if rendered.contains(&c.name) {
                continue;
            }
            if c.layer != layer {
                continue;
            }
            arch.push_str(&comp_block(c, ""));
        }
    }
    sections.push(Section::new("ARCHITECTURE", arch, 9));

    // PRIMARY FLOWS (never cut); the architecture view is the ARCHITECTURE
    // section itself — skip it here to avoid duplicating the system. The
    // rendered section is bounded so a chain-rich repo's FLOWS view stays
    // compact: the deepest flows (most step lines) render first, capped at
    // FLOW_RENDER_CAP flows and FLOW_RENDER_STEP_CAP lines each. The
    // machine model (`atlas.flows`) carries the full inventory, so the
    // structured behavior layer is unaffected by the render cap.
    const FLOW_RENDER_CAP: usize = 32;
    const FLOW_RENDER_STEP_CAP: usize = 16;
    let mut flows = String::new();
    let mut render_flows: Vec<&AtlasFlow> = atlas
        .flows
        .iter()
        .filter(|f| f.kind != FlowKind::Architecture)
        .collect();
    render_flows.sort_by(|a, b| b.steps.len().cmp(&a.steps.len()).then(a.name.cmp(&b.name)));
    for f in render_flows.into_iter().take(FLOW_RENDER_CAP) {
        flows.push_str(&format!("\n{} [{}]", f.name, flow_kind_str(f.kind)));
        if let Some(t) = &f.trigger {
            flows.push_str(&format!("\nTrigger: {t}"));
        }
        for s in f.steps.iter().take(FLOW_RENDER_STEP_CAP) {
            flows.push_str(&format!("\n{s}"));
        }
        if f.steps.len() > FLOW_RENDER_STEP_CAP {
            flows.push_str(&format!(
                "\n... +{} more steps",
                f.steps.len() - FLOW_RENDER_STEP_CAP
            ));
        }
        flows.push('\n');
    }
    sections.push(Section::new("FLOWS", flows, 9));

    // STATE & DATA AUTHORITY (never cut): six subsections — DATA
    // OWNERSHIP (persistent: the write-derived + declared owns claims and
    // the DATA STORES list), RUNTIME STATE, REACTIVE STATE,
    // CONFIGURATION, CACHES, DERIVED / REGISTRIES. Falls back to the
    // legacy DATA OWNERSHIP title when the state compiler found no state
    // at all.
    let has_state = atlas.state_authority.values().any(|v| !v.is_empty());
    let mut state_body = String::new();
    if has_state {
        state_body.push_str("DATA OWNERSHIP\n");
    }
    for c in &atlas.components {
        for o in &c.owns {
            state_body.push_str(&format!(
                "{} owns {} ({})\n",
                c.name, o.target, o.provenance
            ));
        }
    }
    if let Some(lines) = atlas.state_authority.get(scc_graph::state::S_PERSISTENT) {
        for l in lines {
            if l.contains("::") {
                state_body.push_str(&format!("{l}\n"));
            }
        }
    }
    if !atlas.data_stores.is_empty() {
        state_body.push_str("\nDATA STORES\n");
        for s in &atlas.data_stores {
            state_body.push_str(&format!("  {s}\n"));
        }
    }
    for section in [
        scc_graph::state::S_RUNTIME,
        scc_graph::state::S_REACTIVE,
        scc_graph::state::S_CONFIGURATION,
        scc_graph::state::S_CACHES,
        scc_graph::state::S_DERIVED,
    ] {
        if let Some(lines) = atlas.state_authority.get(section) {
            if !lines.is_empty() {
                state_body.push_str(&format!("\n{}\n", scc_graph::state::section_label(section)));
                for l in lines {
                    state_body.push_str(&format!("  {l}\n"));
                }
            }
        }
    }
    sections.push(Section::new(
        if has_state {
            "STATE & DATA AUTHORITY"
        } else {
            "DATA OWNERSHIP"
        },
        state_body,
        10,
    ));

    // CONTRACTS (never cut) — rendered as per-subclass groups: one
    // `{subclass}: {operation}` line per operation, sorted so each subclass
    // family (http/cli/event/config/public-api/extension/serialization/...)
    // clusters together. Preserves the classic contract strings (route
    // `GET /api/x`, flag `--paging`, event `user.created`, config key
    // `DEBUG`) so pre-Wave-9 consumers keep matching.
    sections.push(Section::new(
        "CONTRACTS",
        if atlas.contracts.is_empty() {
            "(none)".into()
        } else {
            let mut lines: Vec<String> = Vec::new();
            for c in &atlas.contracts {
                let prefix = c.subclass.as_str();
                for op in &c.operations {
                    lines.push(format!("{prefix}: {op}"));
                }
            }
            lines.sort();
            lines.join("\n")
        },
        9,
    ));

    // PUBLIC API (Wave 10): exports grouped by component — compact
    // `component: exports A, B, C` lines from the semantic fact layer
    // (EXPORT entities + exported module-level symbols). Per-component
    // render is bounded (the structured model carries the full list).
    sections.push(Section::new(
        "PUBLIC API",
        if atlas.public_api.is_empty() {
            "(none)".into()
        } else {
            const API_RENDER_CAP: usize = 64;
            let mut lines: Vec<String> = Vec::new();
            for (comp, exports) in &atlas.public_api {
                if exports.is_empty() {
                    continue;
                }
                let shown: Vec<&str> = exports
                    .iter()
                    .take(API_RENDER_CAP)
                    .map(|s| s.as_str())
                    .collect();
                let mut line = format!("{}: exports {}", comp, shown.join(", "));
                if exports.len() > API_RENDER_CAP {
                    line.push_str(&format!(" (+{} more)", exports.len() - API_RENDER_CAP));
                }
                lines.push(line);
            }
            lines.join("\n")
        },
        6,
    ));

    // FRAMEWORK SEMANTICS (Wave 10): annotations on targets,
    // route/bean/middleware registrations, lifecycle callbacks — grouped
    // by component. Per-component render is bounded.
    sections.push(Section::new(
        "FRAMEWORK SEMANTICS",
        if atlas.framework_semantics.is_empty() {
            "(none)".into()
        } else {
            const SEM_RENDER_CAP: usize = 48;
            let mut lines: Vec<String> = Vec::new();
            for (comp, facts) in &atlas.framework_semantics {
                for f in facts.iter().take(SEM_RENDER_CAP) {
                    lines.push(format!("{comp}: {f}"));
                }
                if facts.len() > SEM_RENDER_CAP {
                    lines.push(format!("{comp}: (+{} more)", facts.len() - SEM_RENDER_CAP));
                }
            }
            lines.join("\n")
        },
        6,
    ));

    // PIPELINE (Wave 10, CompilerLanguageTool archetype): phase-named
    // symbols grouped by stage.
    sections.push(Section::new(
        "PIPELINE",
        if atlas.pipeline.is_empty() {
            "(none)".into()
        } else {
            atlas.pipeline.join("\n")
        },
        6,
    ));

    // LANDMARKS (Wave 10, priority 5 — bounded ~40): notable exports and
    // annotated targets, one zoom level deeper than the component list.
    sections.push(Section::new(
        "LANDMARKS",
        if atlas.landmarks.is_empty() {
            "(none)".into()
        } else {
            let mut lines = atlas.landmarks.clone();
            lines.sort();
            lines.join("\n")
        },
        5,
    ));

    // CRITICAL INVARIANTS (never cut)
    let mut inv = String::new();
    for i in &atlas.invariants {
        inv.push_str(&format!(
            "- [{}] {}\n",
            severity_str(i.severity),
            i.statement
        ));
    }
    sections.push(Section::new("CRITICAL INVARIANTS", inv, 10));

    // FAILURE / RETRY (never cut)
    let mut failure = String::new();
    for c in &atlas.components {
        for fb in &c.failure_behavior {
            failure.push_str(&format!("{}: {}\n", c.name, fb));
        }
    }
    sections.push(Section::new("FAILURE / RETRY", failure, 9));

    // DEPLOYMENT
    sections.push(Section::new(
        "DEPLOYMENT",
        if atlas.deployment_units.is_empty() {
            "(none)".into()
        } else {
            atlas.deployment_units.join("\n")
        },
        7,
    ));

    // TRUST BOUNDARIES
    sections.push(Section::new(
        "TRUST BOUNDARIES",
        if atlas.trust_boundaries.is_empty() {
            "(none)".into()
        } else {
            atlas.trust_boundaries.join("\n")
        },
        7,
    ));

    // ASYNC BOUNDARIES
    sections.push(Section::new(
        "ASYNC BOUNDARIES",
        if atlas.async_boundaries.is_empty() {
            "(none)".into()
        } else {
            atlas.async_boundaries.join("\n")
        },
        7,
    ));

    // EXTERNAL SYSTEMS
    sections.push(Section::new(
        "EXTERNAL SYSTEMS",
        if atlas.external_systems.is_empty() {
            "(none)".into()
        } else {
            atlas.external_systems.join("\n")
        },
        7,
    ));

    // IMPLEMENTATION MAP
    let mut impl_map = String::new();
    for (name, paths) in &atlas.implementation_map {
        if !paths.is_empty() {
            impl_map.push_str(&format!("{}: {}\n", name, paths.join(", ")));
        }
    }
    sections.push(Section::new("IMPLEMENTATION MAP", impl_map, 6));

    // EVIDENCE STATUS
    let ev: Vec<String> = atlas
        .evidence_summary
        .iter()
        .map(|(k, v)| format!("{v} {k}"))
        .collect();
    sections.push(Section::new(
        "EVIDENCE STATUS",
        if ev.is_empty() {
            "(none)".into()
        } else {
            ev.join(", ")
        },
        8,
    ));

    // RUNTIME (Wave 6): observed trace-path signatures + three-way drift
    // (declared vs static vs observed). Priority 8 — droppable before any
    // critical section, so a tight budget never hides invariants.
    let mut runtime = String::new();
    let sigs = ctx.store.trace_signatures().unwrap_or_default();
    if !sigs.is_empty() {
        runtime.push_str("OBSERVED PATH\n");
        // store order: (count DESC, signature) — deterministic top-10
        for (signature, count, latency_ms, errors, _last) in sigs.into_iter().take(10) {
            runtime.push_str(&format!(
                "{signature} ({count} reqs, avg {latency_ms:.1} ms, {errors} err)\n"
            ));
        }
    }
    const THREE_WAY_KINDS: [&str; 3] = [
        "undeclared_observed",
        "declared_unobserved",
        "static_unobserved",
    ];
    for (_, kind, _sev, msg, _) in ctx.store.drift_findings(true).unwrap_or_default() {
        if !THREE_WAY_KINDS.contains(&kind.as_str()) {
            continue;
        }
        let label = match kind.as_str() {
            "undeclared_observed" => "undeclared observed",
            "declared_unobserved" => "declared unobserved",
            "static_unobserved" => "static unobserved",
            _ => kind.as_str(),
        };
        runtime.push_str(&format!("DRIFT {label}: {msg}\n"));
    }
    if runtime.is_empty() {
        runtime.push_str("(none)\n");
    }
    sections.push(Section::new("RUNTIME", runtime, 8));

    // MODEL COVERAGE (Wave 9): the explicit uncertainty/coverage map — what
    // the model knows AND what it does not. Priority 7: droppable before
    // any critical section, so a tight budget never hides invariants.
    let mut coverage = String::new();
    for (k, v) in &atlas.coverage {
        coverage.push_str(&format!("{k}: {v}\n"));
    }
    sections.push(Section::new(
        "MODEL COVERAGE",
        if coverage.is_empty() {
            "(none)".into()
        } else {
            coverage
        },
        7,
    ));

    let warnings = atlas.warnings.clone();
    if full {
        finish_soft(&mut pack, sections, budget, warnings);
    } else {
        finish(&mut pack, sections, budget, warnings);
    }
    pack.entity_ids = comp_ids(ctx);
    pack
}

/// Project one canonical FlowGraph into ordered step lines for the atlas.
/// Walks from the entrypoints along POLICY-ALLOWED edges (the trust view's
/// provenance policy applies to derived edges too), marking edge kinds:
/// branch / retry / error / async / publish / consume / join. Never
/// flattens alternate paths into false sequential causality.
// trace:exempt reason=internal-detail
fn project_flow_graph(
    view: &TrustedGraphView,
    g: &scc_core::FlowGraph,
    async_boundaries: &mut BTreeSet<String>,
) -> Vec<String> {
    let policy = view.policy();
    let edge_ok = |e: &scc_core::FlowEdge| -> bool {
        match e.provenance {
            None => true,
            Some(p) => policy.allows(p, e.confidence),
        }
    };
    let mut lines: Vec<String> = Vec::new();
    let mut visited: std::collections::BTreeSet<u32> = std::collections::BTreeSet::new();
    let mut queue: std::collections::VecDeque<u32> = g.entrypoints.iter().copied().collect();
    while let Some(n) = queue.pop_front() {
        if !visited.insert(n) {
            continue;
        }
        let Some(node) = g.nodes.get(n as usize) else {
            continue;
        };
        lines.push(format!(
            "{}: {}",
            entity_name(view, &node.actor),
            node.operation
        ));
        let mut outs: Vec<&scc_core::FlowEdge> = g
            .edges
            .iter()
            .filter(|e| e.from == n && edge_ok(e))
            .collect();
        outs.sort_by(|a, b| {
            edge_rank(a.kind)
                .cmp(&edge_rank(b.kind))
                .then(a.to.cmp(&b.to))
        });
        for e in outs {
            let Some(target) = g.nodes.get(e.to as usize) else {
                continue;
            };
            let mut line = format!(
                "  -> {}: {}",
                entity_name(view, &target.actor),
                target.operation
            );
            match e.kind {
                scc_core::FlowEdgeKind::Branch => line.push_str(" (branch)"),
                scc_core::FlowEdgeKind::Retry => line.push_str(" [retry]"),
                scc_core::FlowEdgeKind::Error => line.push_str(" [error]"),
                scc_core::FlowEdgeKind::Async => line.push_str(" [async]"),
                scc_core::FlowEdgeKind::Publish => line.push_str(" [publish]"),
                scc_core::FlowEdgeKind::Consume => line.push_str(" [consume]"),
                scc_core::FlowEdgeKind::Join => line.push_str(" (join)"),
                scc_core::FlowEdgeKind::Fallback => line.push_str(" [fallback]"),
                scc_core::FlowEdgeKind::Timeout => line.push_str(" [timeout]"),
                scc_core::FlowEdgeKind::Compensation => line.push_str(" [compensate]"),
                scc_core::FlowEdgeKind::Read => line.push_str(" [read]"),
                scc_core::FlowEdgeKind::Write => line.push_str(" [write]"),
                scc_core::FlowEdgeKind::Transform => line.push_str(" [transform]"),
                scc_core::FlowEdgeKind::Validate => line.push_str(" [validate]"),
                scc_core::FlowEdgeKind::Authorize => line.push_str(" [authorize]"),
                scc_core::FlowEdgeKind::Cache => line.push_str(" [cache]"),
                scc_core::FlowEdgeKind::Invalidate => line.push_str(" [invalidate]"),
                _ => {}
            }
            if let Some(c) = &e.condition {
                line.push_str(&format!(" ({c})"));
            }
            lines.push(line);
            if e.kind == scc_core::FlowEdgeKind::Async {
                async_boundaries.insert(format!(
                    "{} --async--> {}",
                    entity_name(view, &node.actor),
                    entity_name(view, &target.actor)
                ));
            }
            queue.push_back(e.to);
        }
    }
    lines
}

fn edge_rank(k: scc_core::FlowEdgeKind) -> u8 {
    match k {
        scc_core::FlowEdgeKind::Next => 0,
        scc_core::FlowEdgeKind::Async => 1,
        scc_core::FlowEdgeKind::Branch => 2,
        scc_core::FlowEdgeKind::Join => 3,
        scc_core::FlowEdgeKind::Retry => 4,
        scc_core::FlowEdgeKind::Fallback => 5,
        scc_core::FlowEdgeKind::Error => 6,
        scc_core::FlowEdgeKind::Publish => 7,
        scc_core::FlowEdgeKind::Consume => 8,
        scc_core::FlowEdgeKind::Return => 9,
        scc_core::FlowEdgeKind::Timeout => 10,
        scc_core::FlowEdgeKind::Compensation => 11,
        scc_core::FlowEdgeKind::Read => 12,
        scc_core::FlowEdgeKind::Write => 13,
        scc_core::FlowEdgeKind::Transform => 14,
        scc_core::FlowEdgeKind::Validate => 15,
        scc_core::FlowEdgeKind::Authorize => 16,
        scc_core::FlowEdgeKind::Cache => 17,
        scc_core::FlowEdgeKind::Invalidate => 18,
    }
}

// trace:exempt reason=internal-detail
fn comp_ids(ctx: &ContextCompiler) -> Vec<String> {
    ctx.view
        .components()
        .into_iter()
        .map(|c| c.id.clone())
        .collect()
}

fn flow_kind_str(k: FlowKind) -> &'static str {
    match k {
        FlowKind::Architecture => "architecture",
        FlowKind::Workflow => "workflow",
        FlowKind::Sequence => "sequence",
        FlowKind::Dataflow => "dataflow",
        FlowKind::Lifecycle => "lifecycle",
    }
}

fn severity_str(s: scc_core::Severity) -> &'static str {
    match s {
        scc_core::Severity::Info => "INFO",
        scc_core::Severity::Low => "LOW",
        scc_core::Severity::Medium => "MEDIUM",
        scc_core::Severity::High => "HIGH",
        scc_core::Severity::Critical => "CRITICAL",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use scc_core::{
        entity_id, kinds, predicates, relationship_id, symbol_id, Entity, Provenance, Relationship,
    };
    use scc_store::Store;

    // trace:exempt reason=internal-detail
    fn test_store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        let store = Store::open(&dir.path().join("scc.db"), &root).unwrap();
        let repo = "repo";

        // files: 2 parsed python + 1 unparsed json
        store
            .upsert_file("app.py", "h1", "python", "source", 10)
            .unwrap();
        store
            .upsert_file("lib.py", "h2", "python", "source", 10)
            .unwrap();
        store
            .upsert_file("config.json", "h3", "json", "config", 10)
            .unwrap();

        // symbols
        let mk = |n: &str| symbol_id(repo, "app.py", n);
        for n in ["handler", "worker", "reader"] {
            let mut e = Entity::new(mk(n), kinds::SYMBOL, n);
            e.attr("file", serde_json::json!("app.py"));
            store.insert_entity(&e, &["app.py".to_string()]).unwrap();
        }
        // cli flags on worker
        let mut w = store.get_entity(&mk("worker")).unwrap().unwrap();
        w.attributes.insert(
            "cli_flags".into(),
            serde_json::json!(["--queue", "--verbose"]),
        );
        store.insert_entity(&w, &["app.py".to_string()]).unwrap();

        // route with handler
        let route_id = entity_id(repo, kinds::ROUTE, "GET /api/x");
        let mut re = Entity::new(route_id.clone(), kinds::ROUTE, "GET /api/x");
        re.attr("method", serde_json::json!("GET"));
        re.attr("path", serde_json::json!("/api/x"));
        re.attr("handler", serde_json::json!(mk("handler")));
        store.insert_entity(&re, &["app.py".to_string()]).unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(1),
                    mk("handler"),
                    predicates::HANDLES,
                    route_id,
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();

        // export: handler EXPORTS export(handler, function)
        let exp_id = entity_id(repo, kinds::EXPORT, "handler");
        let mut ex = Entity::new(exp_id.clone(), kinds::EXPORT, "handler");
        ex.attr("kind", serde_json::json!("function"));
        store.insert_entity(&ex, &["app.py".to_string()]).unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(2),
                    mk("handler"),
                    predicates::EXPORTS,
                    exp_id,
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();

        // configuration DEBUG configured-by reader
        let cfg_id = entity_id(repo, kinds::CONFIGURATION, "DEBUG");
        store
            .insert_entity(
                &Entity::new(cfg_id.clone(), kinds::CONFIGURATION, "DEBUG"),
                &["app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(3),
                    cfg_id,
                    predicates::CONFIGURED_BY,
                    mk("reader"),
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();

        // calls: one EXTRACTED to a local symbol, one EXTRACTED to a missing
        // external target, one RESOLVED (LSP proof)
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(4),
                    mk("handler"),
                    predicates::CALLS,
                    mk("worker"),
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();
        let ext_id = entity_id(repo, kinds::EXTERNAL_API, "os");
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(5),
                    mk("handler"),
                    predicates::CALLS,
                    ext_id,
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(6),
                    mk("worker"),
                    predicates::CALLS,
                    mk("reader"),
                    Provenance::Resolved,
                ),
                "app.py",
            )
            .unwrap();

        // topic jobs + worker SUBSCRIBES
        let topic_id = entity_id(repo, kinds::TOPIC, "jobs");
        store
            .insert_entity(
                &Entity::new(topic_id.clone(), kinds::TOPIC, "jobs"),
                &["app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(7),
                    mk("worker"),
                    predicates::SUBSCRIBES,
                    topic_id,
                    Provenance::Extracted,
                ),
                "app.py",
            )
            .unwrap();

        let _graph = scc_graph::RealityGraph::load(&store).unwrap();
        (dir, store)
    }

    #[test]
    fn kinds_stringify() {
        assert_eq!(flow_kind_str(FlowKind::Sequence), "sequence");
        assert_eq!(severity_str(scc_core::Severity::Critical), "CRITICAL");
    }

    #[test]
    // trace:v1 id=test.scc.context.atlas-production-scope verifies=REQ-SCC-CTX exercises=impl.scc.atlas-scoped
    fn atlas_production_scope_keeps_fixture_routes_out() {
        // The pollution case: fixtures/foo/app.py exposes GET /admin. The
        // default atlas must not list it as an entrypoint or contract, the
        // fixture component must still list (labeled), and --full restores it.
        let (_dir, store) = fact_layer_store();
        let repo = store.repo_id.clone();
        let mk_route = |store: &Store, method: &str, path: &str, file: &str| {
            let name = format!("{method} {path}");
            let mut e = Entity::new(entity_id(&repo, kinds::ROUTE, &name), kinds::ROUTE, &name);
            e.attr("method", serde_json::json!(method));
            e.attr("path", serde_json::json!(path));
            e.attr("handler", serde_json::json!("handler"));
            e.attr("file", serde_json::json!(file));
            store.insert_entity(&e, &[file.to_string()]).unwrap();
        };
        mk_route(&store, "GET", "/api/ok", "api/app.py");
        mk_route(&store, "GET", "/admin", "fixtures/foo/app.py");
        let mut fx_comp = scc_core::Entity::new(
            entity_id(&repo, kinds::COMPONENT, "fx"),
            kinds::COMPONENT,
            "fx",
        );
        fx_comp.attr(
            "implementation",
            serde_json::json!({"paths": ["fixtures/foo"], "symbols": []}),
        );
        // Re-list components: fact_layer_store set [api, web]; rebuild the
        // same two plus fx (replace_components takes the full list).
        let mut api_comp = scc_core::Entity::new(
            entity_id(&repo, kinds::COMPONENT, "api"),
            kinds::COMPONENT,
            "api",
        );
        api_comp.attr(
            "implementation",
            serde_json::json!({"paths": ["api"], "symbols": []}),
        );
        let mut web_comp = scc_core::Entity::new(
            entity_id(&repo, kinds::COMPONENT, "web"),
            kinds::COMPONENT,
            "web",
        );
        web_comp.attr(
            "implementation",
            serde_json::json!({"paths": ["web"], "symbols": []}),
        );
        store.replace_components(&[api_comp, web_comp, fx_comp]).unwrap();

        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(&store, &graph, crate::ContextSettings::default(), Vec::new());
        let atlas = build_atlas(&ctx);
        assert!(
            atlas.entrypoints.iter().any(|e| e.trigger == "GET /api/ok"),
            "production route listed: {:?}",
            atlas.entrypoints
        );
        assert!(
            !atlas.entrypoints.iter().any(|e| e.trigger == "GET /admin"),
            "fixture route must not be a global entrypoint: {:?}",
            atlas.entrypoints
        );
        assert!(
            !atlas.contracts.iter().any(|c| c
                .operations
                .iter()
                .any(|o| o == "GET /admin")),
            "fixture route must not be a contract: {:?}",
            atlas.contracts
        );
        assert!(
            atlas.components.iter().any(|c| c.name == "fx" && c.role == "fixture"),
            "fixture component stays visible, labeled: {:?}",
            atlas.components.iter().map(|c| (&c.name, &c.role)).collect::<Vec<_>>()
        );
        assert!(
            atlas.coverage.get("scope").map(|s| s.contains("production")).unwrap_or(false),
            "scope honesty receipt: {:?}",
            atlas.coverage.get("scope")
        );
        let full = build_atlas_scoped(&ctx, AtlasScope::Full);
        assert!(
            full.entrypoints.iter().any(|e| e.trigger == "GET /admin"),
            "full scope restores the fixture route: {:?}",
            full.entrypoints
        );
    }

    #[test]
    // trace:exempt reason=internal-detail
    fn contracts_and_coverage_from_fact_layer() {
        let (_dir, store) = test_store();
        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(
            &store,
            &graph,
            crate::ContextSettings::default(),
            Vec::new(),
        );
        let atlas = build_atlas(&ctx);

        // contract subclasses: http (route), cli (flags), config (DEBUG),
        // event (topic jobs), public-api (exported function signature) —
        // no annotations in this fixture
        let kinds_found: BTreeSet<String> =
            atlas.contracts.iter().map(|c| c.kind.clone()).collect();
        assert_eq!(
            kinds_found,
            BTreeSet::from([
                "http".to_string(),
                "cli".to_string(),
                "config".to_string(),
                "event".to_string(),
                "public-api".to_string()
            ]),
            "contract kinds: {:?}",
            atlas.contracts
        );
        // every contract carries the typed subclass, and the machine-model
        // kind agrees with the subclass render prefix
        for c in &atlas.contracts {
            assert_eq!(
                c.kind,
                c.subclass.as_str(),
                "kind agrees with subclass: {c:?}"
            );
        }
        let http = atlas.contracts.iter().find(|c| c.kind == "http").unwrap();
        assert_eq!(http.operations, vec!["GET /api/x"]);
        assert_eq!(http.subclass, scc_core::ContractSubclass::Http);
        assert!(
            http.consumers.iter().any(|c| c == "handler"),
            "handler consumes the route: {:?}",
            http.consumers
        );
        let cli = atlas.contracts.iter().find(|c| c.kind == "cli").unwrap();
        assert_eq!(cli.operations, vec!["--queue", "--verbose"]);
        assert_eq!(cli.subclass, scc_core::ContractSubclass::Cli);
        let cfg = atlas.contracts.iter().find(|c| c.kind == "config").unwrap();
        assert_eq!(cfg.operations, vec!["DEBUG"]);
        assert_eq!(cfg.subclass, scc_core::ContractSubclass::Configuration);
        assert!(
            cfg.consumers.iter().any(|c| c == "reader"),
            "reader consumes DEBUG: {:?}",
            cfg.consumers
        );
        let api = atlas
            .contracts
            .iter()
            .find(|c| c.kind == "public-api")
            .unwrap();
        assert_eq!(api.operations, vec!["handler"]);
        assert_eq!(api.subclass, scc_core::ContractSubclass::PublicApi);

        // rendered CONTRACTS lines are `{subclass}: {operation}` per group
        let lines: Vec<String> = atlas
            .contracts
            .iter()
            .flat_map(|c| {
                c.operations
                    .iter()
                    .map(|op| format!("{}: {}", c.subclass.as_str(), op))
            })
            .collect();
        for want in [
            "http: GET /api/x",
            "cli: --queue",
            "config: DEBUG",
            "event: jobs",
            "public-api: handler",
        ] {
            assert!(
                lines.contains(&want.to_string()),
                "missing {want}: {lines:?}"
            );
        }

        // coverage map: honest, deterministic numbers from the store
        assert_eq!(
            atlas.coverage.get("parsed_source_files").unwrap(),
            "66% (2/3)"
        );
        assert_eq!(
            atlas.coverage.get("unparsed_files").unwrap(),
            "1 (config/docs/infra — scanned but not source-parsed)"
        );
        assert!(
            atlas
                .coverage
                .get("exported_api")
                .unwrap()
                .starts_with("1 export entity"),
            "{:?}",
            atlas.coverage.get("exported_api")
        );
        // 3 calls: 2 with existing targets (worker symbol, reader symbol),
        // 1 external target with no entity → 66%, 1 LSP-RESOLVED
        assert_eq!(
            atlas.coverage.get("call_targets_resolved").unwrap(),
            "66% (2/3, 1 LSP-RESOLVED) — exploration still justified in unresolved regions"
        );
        assert_eq!(
            atlas.coverage.get("dynamic_receivers_unresolved").unwrap(),
            "1 (calls whose target is not a local symbol; unknown-receiver calls are not persisted)"
        );
        // invocation surfaces: public_api (handler) + queue (worker) +
        // http (handler via route) + cli (worker cli_flags)
        assert_eq!(
            atlas.coverage.get("invocation_surfaces").unwrap(),
            "4 (cli 1, http 1, public_api 1, queue 1)",
            "{:?}",
            atlas.coverage.get("invocation_surfaces")
        );
        assert_eq!(
            atlas.coverage.get("stale_evidence").unwrap(),
            "0 (model FRESH)"
        );
        assert!(atlas.coverage.contains_key("model_epoch_generations"));
        assert!(atlas
            .coverage
            .contains_key("framework_registrations_unknown"));

        // atlas entrypoints carry the surface kinds
        let ep_kinds: BTreeSet<&str> = atlas.entrypoints.iter().map(|e| e.kind.as_str()).collect();
        assert!(ep_kinds.contains("public_api"), "{ep_kinds:?}");
        assert!(ep_kinds.contains("queue"), "{ep_kinds:?}");
        assert!(ep_kinds.contains("http"), "http surface: {ep_kinds:?}");
        assert!(ep_kinds.contains("cli"), "cli surface: {ep_kinds:?}");
    }

    // trace:exempt reason=internal-detail

    /// Wave 11: schema contracts (SCHEMA entities + DEFINES/COMPOSES/
    /// VALIDATES edges) render under CONTRACTS with the `schema:` prefix,
    /// and reactive state (REACTIVE entities + OWNS edges) renders under
    /// STATE & DATA AUTHORITY's REACTIVE STATE subsection, attributed to
    /// the owning symbol's component.
    #[test]

    // trace:exempt reason=internal-detail
    fn schema_and_reactive_render_in_atlas() {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        let store = Store::open(&dir.path().join("scc.db"), &root).unwrap();
        let repo = store.repo_id.clone();

        // component api (api/app.py) with symbol UserService — components
        // live in the `components` table (RealityGraph::load reads
        // store.components())
        let comp_id = entity_id(&repo, kinds::COMPONENT, "api");
        store
            .replace_components(&[scc_core::Entity::new(
                comp_id.clone(),
                kinds::COMPONENT,
                "api",
            )])
            .unwrap();
        let fid = entity_id(&repo, kinds::FILE, "api/app.py");
        store
            .insert_entity(
                &Entity::new(fid.clone(), kinds::FILE, "api/app.py"),
                &["api/app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:c:api",
                    comp_id,
                    predicates::CONTAINS,
                    fid.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        let svc = symbol_id(&repo, "api/app.py", "UserService");
        store
            .insert_entity(
                &Entity::new(svc.clone(), kinds::SYMBOL, "UserService"),
                &["api/app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:f:svc",
                    fid,
                    predicates::CONTAINS,
                    svc.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        // schema User (UserService DEFINES it, COMPOSES Base, VALIDATES
        // CreateUser) with one occurrence owned by the User symbol
        let base = entity_id(&repo, kinds::SCHEMA, "Base");
        store
            .insert_entity(
                &Entity::new(base.clone(), kinds::SCHEMA, "Base"),
                &["api/app.py".to_string()],
            )
            .unwrap();
        let user = entity_id(&repo, kinds::SCHEMA, "User");
        store
            .insert_entity(
                &Entity::new(user.clone(), kinds::SCHEMA, "User"),
                &["api/app.py".to_string()],
            )
            .unwrap();
        let user_occ = scc_core::occurrence_id(&repo, "User", "api/app.py", "User", 1);
        store
            .insert_entity(
                Entity::new(
                    user_occ.clone(),
                    scc_core::kinds::OCCURRENCE,
                    "User@api/app.py@User@1",
                )
                .attr("concept", serde_json::json!(user))
                .attr("path", serde_json::json!("api/app.py"))
                .attr("owner", serde_json::json!("User"))
                .attr("line", serde_json::json!(1)),
                &["api/app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:occ:user",
                    user_occ,
                    scc_core::predicates::OCCURS,
                    user.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:defines",
                    svc.clone(),
                    predicates::DEFINES,
                    user.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:composes",
                    user,
                    predicates::COMPOSES,
                    base,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        let target = entity_id(&repo, kinds::SYMBOL, "CreateUser");
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:validates",
                    svc.clone(),
                    predicates::VALIDATES,
                    target,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        // reactive state count: one concept, one occurrence owned by
        // UserService (Wave 13 — identity is per concept/path/owner/line)
        let count = entity_id(&repo, kinds::REACTIVE, "count");
        store
            .insert_entity(
                &Entity::new(count.clone(), kinds::REACTIVE, "count"),
                &["api/app.py".to_string()],
            )
            .unwrap();
        let count_occ = scc_core::occurrence_id(&repo, "count", "api/app.py", "UserService", 1);
        store
            .insert_entity(
                Entity::new(
                    count_occ.clone(),
                    scc_core::kinds::OCCURRENCE,
                    "count@api/app.py@UserService@1",
                )
                .attr("concept", serde_json::json!(count))
                .attr("path", serde_json::json!("api/app.py"))
                .attr("owner", serde_json::json!("UserService"))
                .attr("line", serde_json::json!(1))
                .attr("access", serde_json::json!("state")),
                &["api/app.py".to_string()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:occ:count",
                    count_occ.clone(),
                    scc_core::predicates::OCCURS,
                    count.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    "rel:owns:count",
                    svc,
                    predicates::OWNS,
                    count_occ,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(
            &store,
            &graph,
            crate::ContextSettings::default(),
            Vec::new(),
        );
        let atlas = build_atlas(&ctx);

        // schema contract: name + composition + validation operations
        // (find the User schema — the Base schema is a plain name-only
        // contract)
        let schema = atlas
            .contracts
            .iter()
            .find(|c| {
                c.subclass == scc_core::ContractSubclass::Schema
                    && c.operations.first() == Some(&"User".to_string())
            })
            .expect("schema contract for User");
        assert_eq!(schema.kind, "schema");
        assert_eq!(
            schema.operations,
            vec![
                "User".to_string(),
                "User extends Base".to_string(),
                "User validates".to_string()
            ],
            "{schema:?}"
        );
        // Wave 13 (e): the producer is the occurrence owner symbol — never
        // the concept/expr itself
        assert_eq!(
            schema.producer, "User",
            "producer = owner symbol: {schema:?}"
        );

        // reactive state attributed to the owning symbol's component
        assert!(
            atlas
                .state_authority
                .get(scc_graph::state::S_REACTIVE)
                .map(|lines| lines
                    .iter()
                    .any(|l| l == "api owns reactive: count [state] (EXTRACTED)"))
                .unwrap_or(false),
            "{:?}",
            atlas.state_authority
        );

        // rendered atlas lines
        let pack = render_atlas(&ctx, &atlas, usize::MAX, false);
        for want in [
            "schema: User",
            "schema: User extends Base",
            "schema: User validates",
            "REACTIVE STATE",
            "api owns reactive: count [state] (EXTRACTED)",
        ] {
            assert!(
                pack.content.contains(want),
                "missing {want:?} in:\n{}",
                pack.content
            );
        }
    }

    /// A repo with component-attributed symbols exercising the Wave 10
    /// fact-layer sections: exported classes/methods, module exports,
    /// annotations, registrations, callbacks, and state facts.
    // trace:exempt reason=internal-detail
    fn fact_layer_store() -> (tempfile::TempDir, Store) {
        let dir = tempfile::TempDir::new().unwrap();
        let root = dir.path().join("repo");
        std::fs::create_dir_all(&root).unwrap();
        let store = Store::open(&dir.path().join("scc.db"), &root).unwrap();
        let repo = store.repo_id.clone();

        // components api (api/app.py) and web (web/app.py)
        let mk_comp = |store: &Store, name: &str, file: &str| -> String {
            let id = entity_id(&repo, kinds::COMPONENT, name);
            store
                .insert_entity(
                    &scc_core::Entity::new(id.clone(), kinds::COMPONENT, name),
                    &[file.to_string()],
                )
                .unwrap();
            let fid = entity_id(&repo, kinds::FILE, file);
            store
                .insert_relationship(
                    &Relationship::new(
                        format!("rel:c:{name}"),
                        id.clone(),
                        predicates::CONTAINS,
                        fid,
                        Provenance::Extracted,
                    ),
                    file,
                )
                .unwrap();
            id
        };
        mk_comp(&store, "api", "api/app.py");
        mk_comp(&store, "web", "web/app.py");
        // components live in the `components` table (RealityGraph::load
        // reads store.components()) — replace with the full list, carrying
        // the component compiler's `implementation` fact (paths + member
        // symbols).
        let mut api_comp = scc_core::Entity::new(
            entity_id(&repo, kinds::COMPONENT, "api"),
            kinds::COMPONENT,
            "api",
        );
        api_comp.attr(
            "implementation",
            serde_json::json!({
                "paths": ["api"],
                "symbols": ["App", "App.get", "include_router", "_secret"],
            }),
        );
        let mut web_comp = scc_core::Entity::new(
            entity_id(&repo, kinds::COMPONENT, "web"),
            kinds::COMPONENT,
            "web",
        );
        web_comp.attr(
            "implementation",
            serde_json::json!({
                "paths": ["web"],
                "symbols": ["handle_page", "on_message"],
            }),
        );
        store.replace_components(&[api_comp, web_comp]).unwrap();
        store
            .insert_entity(
                &Entity::new(
                    entity_id(&repo, kinds::FILE, "api/app.py"),
                    kinds::FILE,
                    "api/app.py",
                ),
                &["api/app.py".into()],
            )
            .unwrap();
        store
            .insert_entity(
                &Entity::new(
                    entity_id(&repo, kinds::FILE, "web/app.py"),
                    kinds::FILE,
                    "web/app.py",
                ),
                &["web/app.py".into()],
            )
            .unwrap();

        let mk_sym = |path: &str, name: &str, attrs: serde_json::Value| -> String {
            let id = symbol_id(&repo, path, name);
            let mut e = Entity::new(id.clone(), kinds::SYMBOL, name);
            if let Some(obj) = attrs.as_object() {
                for (k, v) in obj {
                    e.attr(k, v.clone());
                }
            }
            store.insert_entity(&e, &[path.to_string()]).unwrap();
            let fid = entity_id(&repo, kinds::FILE, path);
            store
                .insert_relationship(
                    &Relationship::new(
                        format!("rel:f:{path}:{name}"),
                        fid,
                        predicates::CONTAINS,
                        id.clone(),
                        Provenance::Extracted,
                    ),
                    path,
                )
                .unwrap();
            id
        };

        // exported class `App` with public method `App.get` (framework class)
        let app_id = mk_sym(
            "api/app.py",
            "App",
            serde_json::json!({"kind": "class", "exported": true}),
        );
        let app_get = mk_sym(
            "api/app.py",
            "App.get",
            serde_json::json!({"kind": "method", "parent": "App", "exported": false}),
        );
        // exported module-level function + underscore-private one
        mk_sym(
            "api/app.py",
            "include_router",
            serde_json::json!({"kind": "function", "exported": true}),
        );
        mk_sym(
            "api/app.py",
            "_secret",
            serde_json::json!({"kind": "function", "exported": true}),
        );
        // web component symbol
        let web_handle = mk_sym(
            "web/app.py",
            "handle_page",
            serde_json::json!({"kind": "function", "exported": true}),
        );

        // EXPORT entity for include_router (EXPORTS edge)
        let exp_id = entity_id(&repo, kinds::EXPORT, "include_router");
        store
            .insert_entity(
                &Entity::new(exp_id.clone(), kinds::EXPORT, "include_router"),
                &["api/app.py".into()],
            )
            .unwrap();
        let include_id = symbol_id(&repo, "api/app.py", "include_router");
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(100),
                    include_id,
                    predicates::EXPORTS,
                    exp_id,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        // annotation: @Get on App.get
        let ann_id = entity_id(&repo, kinds::ANNOTATION, "Get");
        store
            .insert_entity(
                &Entity::new(ann_id.clone(), kinds::ANNOTATION, "Get"),
                &["api/app.py".into()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(101),
                    ann_id,
                    predicates::ANNOTATES,
                    app_get.clone(),
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        // registration: App registers middleware
        let mw_id = entity_id(&repo, kinds::MIDDLEWARE, "RequestLogger");
        store
            .insert_entity(
                &Entity::new(mw_id.clone(), kinds::MIDDLEWARE, "RequestLogger"),
                &["api/app.py".into()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(102),
                    app_id.clone(),
                    predicates::REGISTERS,
                    mw_id,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        // callback: web_handle HANDLES_CALLBACK on_message (a SYMBOL target)
        let cb_sym = mk_sym(
            "web/app.py",
            "on_message",
            serde_json::json!({"kind": "function", "exported": false}),
        );
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(103),
                    web_handle.clone(),
                    predicates::HANDLES_CALLBACK,
                    cb_sym,
                    Provenance::Extracted,
                ),
                "web/app.py",
            )
            .unwrap();

        // state facts: mutable field CONTAINS-ed by App + config
        let field_id = entity_id(&repo, kinds::FIELD, "App.cache");
        store
            .insert_entity(
                Entity::new(field_id.clone(), kinds::FIELD, "App.cache")
                    .attr("mutable", serde_json::json!(true))
                    .attr("owner", serde_json::json!("App")),
                &["api/app.py".into()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(104),
                    app_id.clone(),
                    predicates::CONTAINS,
                    field_id,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();
        let cfg_id = entity_id(&repo, kinds::CONFIGURATION, "DEBUG");
        store
            .insert_entity(
                &Entity::new(cfg_id.clone(), kinds::CONFIGURATION, "DEBUG"),
                &["api/app.py".into()],
            )
            .unwrap();
        store
            .insert_relationship(
                &Relationship::new(
                    relationship_id(105),
                    cfg_id,
                    predicates::CONFIGURED_BY,
                    app_id,
                    Provenance::Extracted,
                ),
                "api/app.py",
            )
            .unwrap();

        let _graph = scc_graph::RealityGraph::load(&store).unwrap();
        (dir, store)
    }

    #[test]
    // trace:exempt reason=internal-detail
    fn fact_layer_sections_grouped_by_component() {
        let (_dir, store) = fact_layer_store();
        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(
            &store,
            &graph,
            crate::ContextSettings::default(),
            Vec::new(),
        );
        let atlas = build_atlas(&ctx);

        // PUBLIC API grouped by component: api has App (exported class) +
        // include_router (export entity + module export); web has
        // handle_page. `_secret` is excluded (leading underscore).
        let api_exports = atlas.public_api.get("api").expect("api exports");
        assert!(api_exports.contains(&"App".to_string()), "{api_exports:?}");
        assert!(
            api_exports.contains(&"include_router".to_string()),
            "{api_exports:?}"
        );
        assert!(
            !api_exports.iter().any(|e| e == "_secret"),
            "{api_exports:?}"
        );
        let web_exports = atlas.public_api.get("web").expect("web exports");
        assert!(
            web_exports.contains(&"handle_page".to_string()),
            "{web_exports:?}"
        );

        // FRAMEWORK SEMANTICS: annotation, registration, callback per comp
        let api_facts = atlas.framework_semantics.get("api").expect("api facts");
        assert!(
            api_facts
                .iter()
                .any(|f| f.contains("annotates App.get (Get)")),
            "{api_facts:?}"
        );
        assert!(
            api_facts
                .iter()
                .any(|f| f.contains("registers RequestLogger")),
            "{api_facts:?}"
        );
        let web_facts = atlas.framework_semantics.get("web").expect("web facts");
        assert!(
            web_facts
                .iter()
                .any(|f| f.contains("handles callback on_message")),
            "{web_facts:?}"
        );

        // component implementation carries member symbols; paths stay pure
        let api = atlas.components.iter().find(|c| c.name == "api").unwrap();
        assert!(
            api.symbols.contains(&"App".to_string()),
            "{:?}",
            api.symbols
        );
        assert!(
            api.symbols.contains(&"App.get".to_string()),
            "{:?}",
            api.symbols
        );
        assert!(
            api.implementation.contains(&"App".to_string()),
            "{:?}",
            api.implementation
        );
        assert_eq!(api.implementation_paths, vec!["api".to_string()]);
        // paths-only in the implementation map (compact render)
        assert_eq!(
            atlas.implementation_map.get("api").unwrap(),
            &vec!["api".to_string()]
        );

        // STATE & DATA AUTHORITY structured bridge: mutable field + config
        // targets surface as component owns claims
        let api_owns: Vec<&str> = api.owns.iter().map(|o| o.target.as_str()).collect();
        assert!(
            api_owns.contains(&"App.cache"),
            "mutable field owns claim: {api_owns:?}"
        );
        assert!(
            api_owns.contains(&"DEBUG"),
            "config owns claim: {api_owns:?}"
        );

        // LANDMARKS bounded: exports (App, include_router, handle_page)
        assert!(
            atlas.landmarks.len() <= 40,
            "landmarks bounded: {:?}",
            atlas.landmarks.len()
        );
        assert!(
            atlas.landmarks.iter().any(|l| l.contains("App")),
            "{:?}",
            atlas.landmarks
        );

        // rendered atlas carries the new section headers
        let pack = render_atlas(&ctx, &atlas, usize::MAX, false);
        assert!(pack.content.contains("# PUBLIC API"), "{}", pack.content);
        assert!(
            pack.content.contains("# FRAMEWORK SEMANTICS"),
            "{}",
            pack.content
        );
        assert!(pack.content.contains("# LANDMARKS"), "{}", pack.content);
        assert!(
            pack.content.contains("api: exports App, include_router"),
            "{}",
            pack.content
        );
    }

    #[test]
    // trace:exempt reason=internal-detail
    fn pipeline_only_for_compiler_language_tool() {
        let (_dir, store) = fact_layer_store();
        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(
            &store,
            &graph,
            crate::ContextSettings::default(),
            Vec::new(),
        );
        let atlas = build_atlas(&ctx);
        // not a compiler repo → no pipeline lines
        assert!(atlas.pipeline.is_empty(), "{:?}", atlas.pipeline);

        // phase-named symbols group by stage when the archetype fires
        let parse_id = symbol_id(&store.repo_id, "api/app.py", "parse");
        let mut e = store
            .get_entity(&parse_id)
            .ok()
            .flatten()
            .unwrap_or_else(|| {
                let ent = Entity::new(parse_id.clone(), kinds::SYMBOL, "parse");
                store.insert_entity(&ent, &["api/app.py".into()]).unwrap();
                ent
            });
        e.attr("exported", serde_json::json!(true));
        store.insert_entity(&e, &["api/app.py".into()]).unwrap();
        let graph = scc_graph::RealityGraph::load(&store).unwrap();
        let ctx = ContextCompiler::new(
            &store,
            &graph,
            crate::ContextSettings::default(),
            Vec::new(),
        );
        let pipeline = build_pipeline(&ctx.view, Some(scc_core::Archetype::CompilerLanguageTool));
        assert!(
            pipeline.iter().any(|l| l.trim() == "parse"),
            "parse symbol in pipeline: {pipeline:?}"
        );
        assert!(
            pipeline.iter().any(|l| l == "[parse]"),
            "stage header: {pipeline:?}"
        );
    }
}