cellos-core 0.7.2

CellOS domain types and ports — typed authority, formation DAG, CloudEvent envelopes, RBAC primitives. No I/O.
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
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
//! Versioned CloudEvents `data` payloads (JSON only — no I/O).

use std::fmt;

use serde::{Serialize, Serializer};
use serde_json::{json, Map, Value};

use crate::policy::PolicyViolation;
use crate::{
    CloudEventV1, DnsAuthorityDnssecFailed, DnsAuthorityDrift, DnsAuthorityRebindRejected,
    DnsAuthorityRebindThreshold, DnsQueryEvent, ExecutionCellSpec, ExportReceipt,
    NetworkFlowDecision, WorkloadIdentity,
};

/// Subject URN string used by seam-freeze G3/G4 cross-pointers.
///
/// Outcome field for [`lifecycle_destroyed_data_v1`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LifecycleDestroyOutcome {
    Succeeded,
    Failed,
}

/// How the supervisor learned the cell terminated, for the
/// `terminalState` field of [`lifecycle_destroyed_data_v1`].
///
/// `outcome` answers "did the run succeed?" (no phase error). This enum
/// answers a different question that audit cares about: "did we observe a
/// real exit, or did we give up and kill it?"
///
/// - `Clean`: an authenticated exit code arrived through the in-VM bridge
///   (Firecracker + cellos-init vsock). Whatever code arrived is the truth.
/// - `Forced`: the supervisor never received an authenticated exit code —
///   the bridge errored out (vsock channel closed before the 4 bytes were
///   delivered) and teardown proceeded via SIGKILL. Any exit code recorded
///   on this path is synthetic (e.g. -1) and must not be trusted.
///
/// Omitted from the event payload (encoded as `None`) on host backends that
/// do not run an in-VM bridge, since the clean/forced distinction has no
/// meaning when the supervisor itself owns the workload process.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum LifecycleTerminalState {
    Clean,
    Forced,
}

/// FC-50 typed `reason` for `dev.cellos.events.cell.lifecycle.v1.failed` /
/// `.destroyed` payloads.
///
/// Replaces the free-form `Option<&str>` reason used by gap-markers in FC-23,
/// FC-52, FC-59, FC-60, FC-61, FC-63, FC-72 with a constrained set of audit-
/// stable codes. Each variant serializes to its `snake_case` form so the JSON
/// wire format is stable for downstream auditors. `Other(String)` is the
/// escape hatch for operator-supplied free-form reasons that have not yet
/// earned a dedicated variant; it serializes verbatim as the inner string.
///
/// The typed surface is non-exhaustive — adding a new variant is a
/// public-API change that requires schema updates on the
/// `cell.lifecycle.v1.failed` / `.destroyed` contracts. Downstream
/// `match`es outside this crate must include a wildcard arm; `#[non_exhaustive]`
/// is enforced by the compiler so silent breaks at variant-add time aren't
/// possible.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum LifecycleReason {
    /// Workload exceeded its memory limit (cgroup OOM kill or VMM-level OOM).
    Oom,
    /// TTL watchdog fired before the workload completed.
    TtlExceeded,
    /// VMM process exited unexpectedly (e.g. Firecracker crashed).
    VmmCrashed,
    /// Kernel/init failed before reaching `/sbin/init`.
    BootFailed,
    /// Supervisor SIGKILLed the workload after the graceful-shutdown timeout
    /// elapsed.
    SignalKilled,
    /// `cellos-init` segfaulted or aborted inside the guest.
    InitCrashed,
    /// Kernel panicked because it could not mount the rootfs (rootfs
    /// corruption / wrong fs / missing block device).
    KernelCannotMountRoot,
    /// Operator-supplied free-form reason. Serialized verbatim — prefer a
    /// typed variant when one applies.
    Other(String),
}

impl LifecycleReason {
    /// Wire-form string for this reason. Typed variants serialize to
    /// `snake_case`; `Other(s)` returns the inner string verbatim.
    pub fn as_wire_str(&self) -> &str {
        match self {
            LifecycleReason::Oom => "oom",
            LifecycleReason::TtlExceeded => "ttl_exceeded",
            LifecycleReason::VmmCrashed => "vmm_crashed",
            LifecycleReason::BootFailed => "boot_failed",
            LifecycleReason::SignalKilled => "signal_killed",
            LifecycleReason::InitCrashed => "init_crashed",
            LifecycleReason::KernelCannotMountRoot => "kernel_cannot_mount_root",
            LifecycleReason::Other(s) => s.as_str(),
        }
    }
}

impl fmt::Display for LifecycleReason {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_wire_str())
    }
}

impl Serialize for LifecycleReason {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_wire_str())
    }
}

/// Identity lifecycle step for [`identity_failed_data_v1`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum IdentityFailureOperation {
    Materialize,
    Revoke,
}

/// Tranche-1 seam-freeze G2 provenance pointer.
///
/// Surfaces the parent CloudEvent that *caused* the event carrying this
/// `provenance` block, so downstream auditors (taudit, tencrypt) can walk
/// `artifact → compliance.summary → spec → derivation token` without
/// operator-supplied joins. See `docs/seam-freeze-v1.md` §3 G2.
///
/// Today the supervisor populates this on:
///
/// - `dev.cellos.events.cell.identity.v1.revoked` — revoke is caused by the
///   cell that materialized the identity, so `parent` is the
///   `cell.lifecycle.v1.started` event ID and `parentType` is the started
///   event's CloudEvent type URN.
/// - `dev.cellos.events.cell.export.v2.completed` and
///   `dev.cellos.events.cell.export.v2.failed` — exports are caused by the
///   originating cell run, so `parent` is the started event ID with the
///   matching `parentType`.
///
/// The struct is additive: producers omit it on legacy emissions, and the
/// schemas tolerate its absence so v1/v2 consumers keep parsing legacy
/// events unchanged.
///
/// `parent` is the producing tool's CloudEvent envelope `id` — a stable URN
/// is preferred (`urn:cellos:event:<uuid>`) but a raw UUID is accepted in
/// v1. `parent_type` carries the parent event's CloudEvent `type` so a
/// consumer can route without resolving the parent first.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Provenance {
    /// CloudEvent `id` (or URN) of the parent event that caused this event.
    pub parent: String,
    /// CloudEvent `type` of the parent event (e.g.
    /// `dev.cellos.events.cell.lifecycle.v1.started`). Lets consumers
    /// dispatch on the parent class without dereferencing it.
    pub parent_type: String,
}

/// Tranche-1 seam-freeze G3 subject URN.
///
/// Promotes the CloudEvents `subject` envelope field from a free-form string
/// (`cell:<id>` was the legacy convention) to a typed, validated URN of the
/// form `urn:<tool>:<kind>:<id>`. See `docs/seam-freeze-v1.md` §3 G3 / §4.
///
/// `0ryant-shell` and `tedit` use the URN prefix as a routing key; CellOS
/// emitters use [`cell_subject_urn`] for cell subjects. Other tools mint
/// their own (`urn:tsafe:lease:<id>`, `urn:tencrypt:cert:<id>`, etc.).
///
/// Validation rules (see [`SubjectUrn::parse`]):
///
/// 1. must start with the literal scheme `urn:`;
/// 2. exactly four colon-separated segments — `urn`, `<tool>`, `<kind>`,
///    `<id>` — where `<id>` may itself contain colons;
/// 3. `<tool>`, `<kind>`, `<id>` must each be non-empty;
/// 4. `<tool>` and `<kind>` are restricted to lowercase ASCII alphanumerics
///    and `-` (charset `[a-z0-9-]`);
/// 5. no ASCII control characters and no whitespace anywhere.
///
/// `<id>` is intentionally permissive on charset (so producers can carry
/// existing IDs like ULIDs, UUIDs, or `cell-<host>-<n>`) but still must not
/// contain ASCII control or whitespace.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct SubjectUrn(String);

/// Parse-time error returned by [`SubjectUrn::parse`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubjectUrnError {
    /// Did not start with the literal `urn:` scheme.
    MissingUrnScheme,
    /// Fewer than four colon-separated segments.
    TooFewSegments,
    /// One of `<tool>` / `<kind>` / `<id>` was empty.
    EmptySegment,
    /// `<tool>` or `<kind>` contained a character outside `[a-z0-9-]`.
    InvalidToolOrKindCharset,
    /// Subject contained an ASCII control character or whitespace.
    ControlOrWhitespace,
}

impl std::fmt::Display for SubjectUrnError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubjectUrnError::MissingUrnScheme => f.write_str("subject URN must start with `urn:`"),
            SubjectUrnError::TooFewSegments => {
                f.write_str("subject URN must have shape `urn:<tool>:<kind>:<id>`")
            }
            SubjectUrnError::EmptySegment => {
                f.write_str("subject URN tool / kind / id segments must each be non-empty")
            }
            SubjectUrnError::InvalidToolOrKindCharset => {
                f.write_str("subject URN tool and kind must match charset [a-z0-9-]")
            }
            SubjectUrnError::ControlOrWhitespace => {
                f.write_str("subject URN must not contain ASCII control characters or whitespace")
            }
        }
    }
}

impl std::error::Error for SubjectUrnError {}

impl SubjectUrn {
    /// Validate `s` and wrap it as a typed `SubjectUrn`. See the type-level
    /// documentation for the exact rules.
    pub fn parse(s: impl Into<String>) -> Result<Self, SubjectUrnError> {
        let s = s.into();

        // Rule 5: no ASCII control or whitespace anywhere.
        if s.bytes()
            .any(|b| b.is_ascii_control() || (b as char).is_whitespace())
        {
            return Err(SubjectUrnError::ControlOrWhitespace);
        }

        // Rule 1: must start with `urn:`.
        let rest = match s.strip_prefix("urn:") {
            Some(r) => r,
            None => return Err(SubjectUrnError::MissingUrnScheme),
        };

        // Rule 2: split into <tool>:<kind>:<id> with `splitn(3, ':')` so the
        // id portion can itself contain colons (forward-compat for nested
        // identifiers like `urn:cellos:event:<uuid>:<seq>`).
        let mut parts = rest.splitn(3, ':');
        let tool = parts.next().ok_or(SubjectUrnError::TooFewSegments)?;
        let kind = parts.next().ok_or(SubjectUrnError::TooFewSegments)?;
        let id = parts.next().ok_or(SubjectUrnError::TooFewSegments)?;

        // Rule 3: non-empty tool/kind/id.
        if tool.is_empty() || kind.is_empty() || id.is_empty() {
            return Err(SubjectUrnError::EmptySegment);
        }

        // Rule 4: tool/kind charset [a-z0-9-].
        let ok_segment = |seg: &str| {
            seg.bytes()
                .all(|b| matches!(b, b'a'..=b'z' | b'0'..=b'9' | b'-'))
        };
        if !ok_segment(tool) || !ok_segment(kind) {
            return Err(SubjectUrnError::InvalidToolOrKindCharset);
        }

        Ok(SubjectUrn(s))
    }

    /// Borrow the validated URN as a `&str`.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the wrapper and return the owned string.
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for SubjectUrn {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SubjectUrn {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

/// Build the canonical CellOS cell subject URN (`urn:cellos:cell:<cell_id>`).
///
/// The single helper means the literal prefix `urn:cellos:cell:` lives in
/// exactly one place; the `scripts/audit/subject-urn-check.sh` CI gate
/// enforces that no other site hand-crafts the same shape. Callers should
/// prefer this helper over `format!("urn:cellos:cell:{cell_id}")`.
///
/// Returns `Err(SubjectUrnError::EmptySegment)` if `cell_id` is empty and
/// surfaces charset / whitespace errors from [`SubjectUrn::parse`] for IDs
/// that contain ASCII control / whitespace characters.
pub fn cell_subject_urn(cell_id: &str) -> Result<SubjectUrn, SubjectUrnError> {
    SubjectUrn::parse(format!("urn:cellos:cell:{cell_id}"))
}

/// `data` for event type `dev.cellos.events.cell.lifecycle.v1.started`.
///
/// Schema: `contracts/schemas/cell-lifecycle-started-data-v1.schema.json`.
///
/// Authority derivation fields (L5-05): when the spec carries an
/// `authority.authorityDerivation` token, the supervisor verifies the proof
/// before this event is emitted and surfaces the outcome here so taudit can
/// answer "prove every prod cell derived authority from role X" without
/// re-running the verification.
///
/// - `derivation_verified`: `Some(true)` when the proof verified, `Some(false)`
///   when verification failed (non-fatal — the run still proceeds), `None`
///   when the spec carried no derivation token at all.
/// - `role_root`: the role root identifier from the derivation token (when
///   the token was present), regardless of whether verification succeeded.
/// - `parent_run_id`: optional lineage attribution from the derivation token.
///
/// All three fields are emitted into the `data` JSON only when `Some`, so
/// specs without a derivation token produce the same payload as before this
/// change (backward-compatible with the v1 schema).
///
/// **A2-03 — per-tenant event stream isolation**: when
/// `spec.correlation.tenantId` is `Some(_)`, the value is mirrored into a
/// top-level `tenantId` field on the event `data` (in addition to staying
/// embedded inside the `correlation` block for joins). The supervisor's
/// JetStream sink reads this field at publish time to substitute
/// `{tenantId}` in the configured subject template. When the tenant is
/// `None`, the top-level `tenantId` is OMITTED entirely so the wire format
/// is byte-identical to pre-A2-03 builds for single-tenant operators.
///
/// **FC-08**: when the host backend has a verified artifact manifest
/// (currently the Firecracker backend), the supervisor surfaces the on-disk
/// SHA256 digests of the boot artifacts on the started event so taudit can
/// answer "which kernel/rootfs/firecracker bytes did this run boot?" without
/// querying any backend-side state. The three digest fields are independently
/// optional — backends without a manifest path (stub, host-cellos) pass
/// `None` for all three; the Firecracker backend passes `Some(hex)` for
/// kernel and rootfs (always verified) and `Some(hex)` for firecracker only
/// when the manifest also declares the firecracker binary digest. Each is
/// emitted into the JSON only when `Some`, preserving the v1 schema's
/// backward-compat semantics.
#[allow(clippy::too_many_arguments)]
pub fn lifecycle_started_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    derivation_verified: Option<bool>,
    role_root: Option<&str>,
    parent_run_id: Option<&str>,
    spec_hash: Option<&str>,
    kernel_digest_sha256: Option<&str>,
    rootfs_digest_sha256: Option<&str>,
    firecracker_digest_sha256: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("ttlSeconds".to_string(), json!(spec.lifetime.ttl_seconds));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(verified) = derivation_verified {
        m.insert("derivationVerified".to_string(), json!(verified));
    }
    if let Some(role) = role_root {
        m.insert("roleRoot".to_string(), json!(role));
    }
    if let Some(parent) = parent_run_id {
        m.insert("parentRunId".to_string(), json!(parent));
    }
    if let Some(hash) = spec_hash {
        m.insert("specHash".to_string(), json!(hash));
    }
    if let Some(d) = kernel_digest_sha256 {
        m.insert("kernelDigestSha256".to_string(), json!(d));
    }
    if let Some(d) = rootfs_digest_sha256 {
        m.insert("rootfsDigestSha256".to_string(), json!(d));
    }
    if let Some(d) = firecracker_digest_sha256 {
        m.insert("firecrackerDigestSha256".to_string(), json!(d));
    }
    if let Some(placement) = &spec.placement {
        let mut placement_map = Map::new();
        if let Some(pool_id) = &placement.pool_id {
            placement_map.insert("poolId".to_string(), json!(pool_id));
        }
        if let Some(namespace) = &placement.kubernetes_namespace {
            placement_map.insert("kubernetesNamespace".to_string(), json!(namespace));
        }
        if let Some(queue_name) = &placement.queue_name {
            placement_map.insert("queueName".to_string(), json!(queue_name));
        }
        if !placement_map.is_empty() {
            m.insert("placement".to_string(), Value::Object(placement_map));
        }
    }
    if let Some(c) = &spec.correlation {
        if let Some(tid) = &c.tenant_id {
            m.insert("tenantId".to_string(), json!(tid));
        }
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.lifecycle.v1.destroyed`.
///
/// Schema: `contracts/schemas/cell-lifecycle-destroyed-data-v1.schema.json`.
///
/// `terminal_state` is `None` for backends that do not own workload execution
/// (host-side spawn path) and `Some(...)` for the in-VM bridge path. Auditors
/// keying on this field can distinguish "supervisor read an authenticated exit
/// code" from "supervisor gave up and SIGKILLed the VMM" — see
/// [`LifecycleTerminalState`] for the distinction. The field is emitted into
/// the JSON only when set, preserving backward-compatibility with v1 consumers.
///
/// F5 (D5 destruction-evidence integration):
///
/// - `evidence_bundle_ref`: URN of the `evidence_bundle` artifact (F1b)
///   that aggregates this run's lifecycle, host-side series, and guest
///   declarations. Auditors reading `cell.destroyed` cold MUST be able to
///   walk this URN to the bundle. See `docs/adr/0006-...` and F1.
/// - `residue_class`: final residue classification from
///   `docs/destruction-semantics.md` (`none` / `documented_exception`).
///
/// Both fields are additive: emitted only when `Some(...)` so existing v1
/// consumers parse the legacy payload unchanged. The supervisor passes
/// `None, None` until F1b wires the evidence-bundle aggregator into the
/// teardown path.
///
/// **A2-03**: like `lifecycle_started_data_v1`, this constructor mirrors
/// `spec.correlation.tenantId` into a top-level `tenantId` field on
/// `data` when set, and omits it entirely otherwise.
///
/// **FC-23 invariant**: this constructor intentionally takes no `exit_code`
/// parameter. The destroyed payload never carries an `exitCode` field. The
/// authenticated workload exit code (if any) is reported on the separate
/// `cell.command.v1.completed` event via [`command_completed_data_v1`], which
/// is only emitted on the in-VM-bridge clean-exit path. Forced terminations
/// (SIGKILL fallback, vsock channel closed) therefore cannot surface an
/// `exitCode` on this event by construction — any synthetic code such as
/// `-1` or `137` stays internal to the supervisor and never reaches auditors.
/// See `Plans/firecracker-release-readiness.md` line 70.
#[allow(clippy::too_many_arguments)]
pub fn lifecycle_destroyed_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    outcome: LifecycleDestroyOutcome,
    reason: Option<&str>,
    terminal_state: Option<LifecycleTerminalState>,
    evidence_bundle_ref: Option<&SubjectUrn>,
    residue_class: Option<ResidueClass>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("ttlSeconds".to_string(), json!(spec.lifetime.ttl_seconds));
    m.insert("outcome".to_string(), serde_json::to_value(outcome)?);
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        if let Some(tid) = &c.tenant_id {
            m.insert("tenantId".to_string(), json!(tid));
        }
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    if let Some(s) = reason {
        m.insert("reason".to_string(), json!(s));
    }
    if let Some(ts) = terminal_state {
        m.insert("terminalState".to_string(), serde_json::to_value(ts)?);
    }
    if let Some(urn) = evidence_bundle_ref {
        m.insert("evidenceBundleRef".to_string(), json!(urn));
    }
    if let Some(rc) = residue_class {
        m.insert("residueClass".to_string(), serde_json::to_value(rc)?);
    }
    Ok(Value::Object(m))
}

/// CloudEvent `type` URN for [`manifest_failed_data_v1`].
///
/// Emitted when pre-boot artifact digest verification fails — the on-disk
/// artifact does not match the digest declared in the host manifest. The
/// emission point lives in the host backend (see
/// `crates/cellos-host-firecracker/src/lib.rs::verify_artifacts`); this
/// constructor only shapes the `data` payload.
pub const LIFECYCLE_MANIFEST_FAILED_TYPE: &str =
    "dev.cellos.events.cell.lifecycle.v1.manifest-failed";

/// `data` for event type `dev.cellos.events.cell.lifecycle.v1.manifest-failed`.
///
/// Surfaces a manifest verification failure: the artifact bound to `role`
/// (e.g. `"kernel"`, `"rootfs"`, `"firecracker"`) hashed to
/// `actual_sha256` on disk, but the declared digest in `manifest_path` was
/// `expected_sha256`. Both digests are emitted as lowercase hex (no
/// `sha256:` prefix), matching the rest of CellOS's audit surface, so
/// downstream taudit consumers can diff the two strings byte-for-byte.
///
/// FC-51 (`Plans/firecracker-release-readiness.md`): integration test
/// replaces the on-disk kernel with a mismatched file and asserts this
/// event is emitted with the `kernel` role and both digests.
pub fn manifest_failed_data_v1(
    role: &str,
    expected_sha256: &str,
    actual_sha256: &str,
    manifest_path: &str,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("role".to_string(), json!(role));
    m.insert("expectedSha256".to_string(), json!(expected_sha256));
    m.insert("actualSha256".to_string(), json!(actual_sha256));
    m.insert("manifestPath".to_string(), json!(manifest_path));
    Ok(Value::Object(m))
}

/// FC-50 typed-reason variant of [`lifecycle_destroyed_data_v1`].
///
/// Identical wire format to the string-based constructor — `reason` is
/// serialized through [`LifecycleReason::as_wire_str`] and threaded into the
/// existing builder via the `Option<&str>` path, so consumers see the same
/// JSON. The typed surface is the preferred entry point for new callers
/// (FC-23, FC-52, FC-59, FC-60, FC-61, FC-63, FC-72 gap-markers); the
/// string-based constructor remains for back-compat until all call sites
/// migrate.
///
/// Adds two F5 destruction-evidence fields not on the legacy constructor:
///
/// - `evidence_bundle_ref`: pointer (URN or CloudEvent id) to the per-cell
///   `evidence_bundle` produced by Phase F (see ADR-0006). Emitted as
///   `evidenceBundleRef` only when `Some`.
/// - `residue_class`: destruction-semantics residue class string (per
///   `docs/destruction-semantics.md`). Emitted as `residueClass` only when
///   `Some`.
///
/// Both are additive and absent from the legacy v1 payload — consumers that
/// do not understand them must ignore unknown fields per the v1 schema's
/// `additionalProperties` posture.
#[allow(clippy::too_many_arguments)]
pub fn lifecycle_destroyed_data_v1_typed(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    outcome: LifecycleDestroyOutcome,
    reason: Option<LifecycleReason>,
    terminal_state: Option<LifecycleTerminalState>,
    evidence_bundle_ref: Option<&SubjectUrn>,
    residue_class: Option<ResidueClass>,
) -> Result<Value, serde_json::Error> {
    let reason_str = reason.as_ref().map(|r| r.as_wire_str());
    lifecycle_destroyed_data_v1(
        spec,
        cell_id,
        run_id,
        outcome,
        reason_str,
        terminal_state,
        evidence_bundle_ref,
        residue_class,
    )
}

/// `data` for event type `dev.cellos.events.cell.identity.v1.materialized`.
///
/// Schema: `contracts/schemas/cell-identity-materialized-data-v1.schema.json`.
pub fn identity_materialized_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    identity: &WorkloadIdentity,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("identity".to_string(), serde_json::to_value(identity)?);
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.identity.v1.revoked`.
///
/// Schema: `contracts/schemas/cell-identity-revoked-data-v1.schema.json`.
///
/// `provenance` (Tranche-1 seam-freeze G2) — when set, points at the parent
/// event that caused this revocation. The supervisor populates it with the
/// `cell.lifecycle.v1.started` envelope so taudit can stitch revoke →
/// lifecycle → spec without operator joins. Omitted from the JSON when
/// `None`, preserving the v1 schema's backward-compat semantics.
pub fn identity_revoked_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    identity: &WorkloadIdentity,
    reason: Option<&str>,
    provenance: Option<&Provenance>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("identity".to_string(), serde_json::to_value(identity)?);
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    if let Some(s) = reason {
        m.insert("reason".to_string(), json!(s));
    }
    if let Some(p) = provenance {
        m.insert("provenance".to_string(), serde_json::to_value(p)?);
    }
    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.identity.v1.failed`.
///
/// Schema: `contracts/schemas/cell-identity-failed-data-v1.schema.json`.
pub fn identity_failed_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    identity: &WorkloadIdentity,
    operation: IdentityFailureOperation,
    reason: &str,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("identity".to_string(), serde_json::to_value(identity)?);
    m.insert("operation".to_string(), serde_json::to_value(operation)?);
    m.insert("reason".to_string(), json!(reason));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.command.v1.completed`.
///
/// Schema: `contracts/schemas/cell-command-completed-data-v1.schema.json`.
pub fn command_completed_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    argv: &[String],
    exit_code: i32,
    duration_ms: u64,
    spawn_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("exitCode".to_string(), json!(exit_code));
    m.insert("durationMs".to_string(), json!(duration_ms));
    m.insert("argv".to_string(), json!(argv));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    if let Some(s) = spawn_error {
        m.insert("spawnError".to_string(), json!(s));
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.network_scope`
///
/// Schema: `contracts/schemas/cell-observability-network-scope-v1.schema.json`.
pub fn observability_network_scope_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    egress_rule_count: usize,
    has_opaque_network_authority: bool,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("egressRuleCount".to_string(), json!(egress_rule_count));
    m.insert(
        "hasOpaqueNetworkAuthority".to_string(),
        json!(has_opaque_network_authority),
    );
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.process_spawned`
///
/// Schema: `contracts/schemas/cell-observability-process-spawned-v1.schema.json`.
pub fn observability_process_spawned_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    program: &str,
    argc: usize,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("program".to_string(), json!(program));
    m.insert("argc".to_string(), json!(argc));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.fs_touch`
///
/// Schema: `contracts/schemas/cell-observability-fs-touch-v1.schema.json`.
pub fn observability_fs_touch_export_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    source_path: &str,
    artifact_name: &str,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("purpose".to_string(), json!("export"));
    m.insert("sourcePath".to_string(), json!(source_path));
    m.insert("artifactName".to_string(), json!(artifact_name));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.export.v1.completed`
///
/// Schema: `contracts/schemas/cell-export-completed-v1.schema.json`.
pub fn export_completed_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    artifact_name: &str,
    bytes_written: u64,
    destination_relative: &str,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("artifactName".to_string(), json!(artifact_name));
    m.insert("bytesWritten".to_string(), json!(bytes_written));
    m.insert(
        "destinationRelative".to_string(),
        json!(destination_relative),
    );
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.export.v2.completed`
///
/// Schema: `contracts/schemas/cell-export-completed-v2.schema.json`.
///
/// `provenance` (Tranche-1 seam-freeze G2) — when set, points at the parent
/// event that caused this export receipt. The supervisor populates it with
/// the `cell.lifecycle.v1.started` envelope of the originating cell run so
/// downstream consumers (tencrypt envelope promotion, taudit graph build)
/// can walk artifact → lifecycle → spec without operator joins. Omitted
/// from the JSON when `None` to preserve v2 schema backward-compat.
pub fn export_completed_data_v2(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    artifact_name: &str,
    receipt: &ExportReceipt,
    provenance: Option<&Provenance>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("artifactName".to_string(), json!(artifact_name));
    m.insert("receipt".to_string(), serde_json::to_value(receipt)?);
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    if let Some(p) = provenance {
        m.insert("provenance".to_string(), serde_json::to_value(p)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.export.v2.failed`
///
/// Schema: `contracts/schemas/cell-export-failed-v2.schema.json`.
///
/// `provenance` (Tranche-1 seam-freeze G2) — when set, points at the parent
/// event that caused this export attempt. The supervisor populates it with
/// the `cell.lifecycle.v1.started` envelope of the originating cell run so
/// downstream consumers (tencrypt envelope promotion, taudit graph build)
/// can walk failed artifact → lifecycle → spec without operator joins.
/// Omitted from the JSON when `None` to preserve v2 schema backward-compat.
#[allow(clippy::too_many_arguments)] // mirrors CloudEvent payload fields
pub fn export_failed_data_v2(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    artifact_name: &str,
    target_kind: crate::ExportReceiptTargetKind,
    target_name: Option<&str>,
    destination: Option<&str>,
    reason: &str,
    provenance: Option<&Provenance>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("artifactName".to_string(), json!(artifact_name));
    m.insert("targetKind".to_string(), serde_json::to_value(target_kind)?);
    m.insert("reason".to_string(), json!(reason));
    if let Some(name) = target_name {
        m.insert("targetName".to_string(), json!(name));
    }
    if let Some(dest) = destination {
        m.insert("destination".to_string(), json!(dest));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    if let Some(p) = provenance {
        m.insert("provenance".to_string(), serde_json::to_value(p)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.network_policy`
///
/// Emitted when `CELLOS_SUBPROCESS_UNSHARE` includes the `net` flag, announcing the
/// network isolation mode and declared egress rules for this cell run. The isolation is
/// enforced by the Linux network namespace (no external connectivity without explicit routing).
/// Optional nftables rules may further filter allowed egress within the namespace.
pub fn observability_network_policy_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    isolation_mode: &str,
    egress_rules: &[crate::EgressRule],
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("isolationMode".to_string(), json!(isolation_mode));
    m.insert("declaredEgressCount".to_string(), json!(egress_rules.len()));
    m.insert(
        "declaredEgress".to_string(),
        serde_json::to_value(egress_rules)?,
    );
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.network_enforcement`
///
/// Emitted after a `spec.run` subprocess exits when the Linux path used `CLONE_NEWNET`, summarizing
/// whether supplementary nftables rules were applied and the command exit code (L2-04).
///
/// Schema: `contracts/schemas/cell-observability-network-enforcement-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_network_enforcement_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    nft_rules_applied: bool,
    declared_egress_rule_count: usize,
    command_exit_code: i32,
    spawn_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let supplementary = nft_rules_applied && declared_egress_rule_count > 0;
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("isolationMode".to_string(), json!("clone_newnet"));
    m.insert("nftRulesApplied".to_string(), json!(nft_rules_applied));
    m.insert(
        "declaredEgressRuleCount".to_string(),
        json!(declared_egress_rule_count),
    );
    m.insert(
        "supplementaryEgressFilterActive".to_string(),
        json!(supplementary),
    );
    m.insert("commandExitCode".to_string(), json!(command_exit_code));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(s) = spawn_error {
        m.insert("spawnError".to_string(), json!(s));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// Default `keysetId` when the operator has not published a [`trust-keyset-v1`] document yet.
///
/// [`trust-keyset-v1`]: https://cellos.dev/schemas/trust-keyset-v1.schema.json
pub const TRUST_PLANE_BUILTIN_KEYSET_ID: &str = "cellos:builtin-v0";

/// Default `issuerKid` for resolver-style observability when no published keyset is wired.
pub const TRUST_PLANE_BUILTIN_RESOLVER_KID: &str = "cellos-local-resolve-v0";

/// Default `issuerKid` for L7 gate observability when no published keyset is wired.
pub const TRUST_PLANE_BUILTIN_L7_KID: &str = "cellos-local-l7-v0";

/// Synthetic FQDN for aggregate declared-egress materialization events (`dns_target_set`).
pub const TRUST_PLANE_AGGREGATE_EGRESS_FQDN: &str = "declared-egress.trust.cellos.internal";

/// `dev.cellos.events.cell.observability.v1.dns_resolution`
///
/// Schema: `contracts/schemas/cell-observability-dns-resolution-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_dns_resolution_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    fqdn: &str,
    resolved_at: &str,
    targets: &[(&str, &str, Option<u16>)],
    ttl_seconds: i64,
    policy_digest: &str,
    keyset_id: &str,
    issuer_kid: &str,
    receipt_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut rows = Vec::with_capacity(targets.len());
    for (addr, family, port) in targets {
        let mut row = Map::new();
        row.insert("address".to_string(), json!(addr));
        row.insert("family".to_string(), json!(family));
        if let Some(p) = port {
            row.insert("port".to_string(), json!(p));
        }
        rows.push(Value::Object(row));
    }
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(rid) = receipt_id {
        m.insert("receiptId".to_string(), json!(rid));
    }
    m.insert("fqdn".to_string(), json!(fqdn));
    m.insert("resolvedAt".to_string(), json!(resolved_at));
    m.insert("targets".to_string(), Value::Array(rows));
    m.insert("ttlSeconds".to_string(), json!(ttl_seconds));
    m.insert("policyDigest".to_string(), json!(policy_digest));
    m.insert("keysetId".to_string(), json!(keyset_id));
    m.insert("issuerKid".to_string(), json!(issuer_kid));
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.dns_target_set`
///
/// Schema: `contracts/schemas/cell-observability-dns-target-set-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_dns_target_set_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    fqdn: &str,
    previous_digest: &str,
    current_digest: &str,
    reason: &str,
    updated_at: &str,
    keyset_id: &str,
    issuer_kid: &str,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    m.insert("fqdn".to_string(), json!(fqdn));
    m.insert("previousDigest".to_string(), json!(previous_digest));
    m.insert("currentDigest".to_string(), json!(current_digest));
    m.insert("reason".to_string(), json!(reason));
    m.insert("updatedAt".to_string(), json!(updated_at));
    m.insert("keysetId".to_string(), json!(keyset_id));
    m.insert("issuerKid".to_string(), json!(issuer_kid));
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.dns_authority_drift`
///
/// Schema: `contracts/schemas/cell-observability-dns-authority-drift-v1.schema.json`.
///
/// Emitted by the SEC-21 host-controlled resolver refresh loop when the
/// resolved target set for a declared FQDN differs from the prior observation.
/// All fields mirror [`DnsAuthorityDrift`] one-for-one; this builder exists so
/// supervisor wiring can emit the payload without re-deriving the canonical
/// JSON shape from the struct.
#[allow(clippy::too_many_arguments)]
pub fn dns_authority_drift_data_v1(drift: &DnsAuthorityDrift) -> Result<Value, serde_json::Error> {
    serde_json::to_value(drift)
}

/// CloudEvent envelope constructor for `dns_authority_drift` (SEC-21).
///
/// Mirrors the supervisor-local `cloud_event(...)` helper but lives in
/// `cellos-core` so library callers (resolver refresh module, taudit) can
/// build the envelope without taking a supervisor-internal dependency.
///
/// `source` should identify the publisher (e.g. `"cellos-supervisor"` or
/// `"cellos-resolver-refresh"`). `time` is the RFC3339 emission timestamp;
/// independent of `drift.observed_at`, which records when the *drift* was
/// observed (the two are typically equal but conceptually distinct).
pub fn cloud_event_v1_dns_authority_drift(
    source: &str,
    time: &str,
    drift: &DnsAuthorityDrift,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.dns_authority_drift".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_authority_drift_data_v1(drift)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.dns_authority_rebind_threshold`
/// (SEC-21 Phase 3e).
///
/// Schema: `contracts/schemas/cell-observability-dns-authority-rebind-threshold-v1.schema.json`.
///
/// Emitted when the SEC-21 host-controlled resolver refresh observes a novel
/// IP for a declared FQDN that pushes the cumulative distinct-IP count past
/// the operator-declared `rebindingPolicy.maxNovelIpsPerHostname` cap. All
/// fields mirror [`DnsAuthorityRebindThreshold`] one-for-one; this builder
/// exists so resolver-refresh wiring can serialize the payload without
/// re-deriving the canonical JSON shape from the struct.
pub fn dns_authority_rebind_threshold_data_v1(
    payload: &DnsAuthorityRebindThreshold,
) -> Result<Value, serde_json::Error> {
    serde_json::to_value(payload)
}

/// CloudEvent envelope constructor for `dns_authority_rebind_threshold`
/// (SEC-21 Phase 3e).
///
/// Mirrors [`cloud_event_v1_dns_authority_drift`] for the rebinding-threshold
/// signal. Lives in `cellos-core` so the resolver-refresh module can build
/// envelopes without taking a supervisor-internal dependency.
///
/// `source` should identify the publisher (e.g. `"cellos-supervisor"` or
/// `"cellos-resolver-refresh"`). `time` is the RFC3339 emission timestamp;
/// independent of `payload.observed_at`, which records when the threshold was
/// observed (the two are typically equal but conceptually distinct).
pub fn cloud_event_v1_dns_authority_rebind_threshold(
    source: &str,
    time: &str,
    payload: &DnsAuthorityRebindThreshold,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.dns_authority_rebind_threshold".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_authority_rebind_threshold_data_v1(payload)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.dns_authority_rebind_rejected`
/// (SEC-21 Phase 3e).
///
/// Schema: `contracts/schemas/cell-observability-dns-authority-rebind-rejected-v1.schema.json`.
///
/// Emitted when the SEC-21 host-controlled resolver refresh observes an IP
/// for a declared FQDN that is NOT in the operator's
/// `rebindingPolicy.responseIpAllowlist`. Only emitted when the allowlist is
/// non-empty for the hostname; one event per offending IP per tick. Combined
/// with `rejectOnRebind=true`, the IP is also dropped from the resolved
/// target set passed to the workload.
pub fn dns_authority_rebind_rejected_data_v1(
    payload: &DnsAuthorityRebindRejected,
) -> Result<Value, serde_json::Error> {
    serde_json::to_value(payload)
}

/// CloudEvent envelope constructor for `dns_authority_rebind_rejected`
/// (SEC-21 Phase 3e).
///
/// Mirrors [`cloud_event_v1_dns_authority_rebind_threshold`] for the
/// allowlist-violation signal. One event per offending IP per tick (so a
/// single response containing 3 disallowed IPs produces 3 rejected events).
pub fn cloud_event_v1_dns_authority_rebind_rejected(
    source: &str,
    time: &str,
    payload: &DnsAuthorityRebindRejected,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.dns_authority_rebind_rejected".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_authority_rebind_rejected_data_v1(payload)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.dns_authority_dnssec_failed`
/// (SEC-21 Phase 3h).
///
/// Schema: `contracts/schemas/cell-observability-dns-authority-dnssec-failed-v1.schema.json`.
///
/// Emitted by the SEC-21 host-controlled resolver-refresh loop when an opt-in
/// DNSSEC-validating resolver returns a response that fails the chain-of-trust
/// check (or when the zone is not signed and the operator has opted into
/// DNSSEC). All fields mirror [`DnsAuthorityDnssecFailed`] one-for-one; this
/// builder exists so resolver-refresh wiring can serialize the payload without
/// re-deriving the canonical JSON shape from the struct.
pub fn dns_authority_dnssec_failed_data_v1(
    payload: &DnsAuthorityDnssecFailed,
) -> Result<Value, serde_json::Error> {
    serde_json::to_value(payload)
}

/// CloudEvent envelope constructor for `dns_authority_dnssec_failed`
/// (SEC-21 Phase 3h).
///
/// Mirrors [`cloud_event_v1_dns_authority_drift`] for the DNSSEC-failure
/// signal. Lives in `cellos-core` so the resolver-refresh module can build
/// envelopes without taking a supervisor-internal dependency.
///
/// `source` should identify the publisher (e.g. `"cellos-supervisor"` or
/// `"cellos-resolver-refresh"`). `time` is the RFC3339 emission timestamp;
/// independent of `payload.observed_at`, which records when the failure
/// was observed (the two are typically equal but conceptually distinct).
pub fn cloud_event_v1_dns_authority_dnssec_failed(
    source: &str,
    time: &str,
    payload: &DnsAuthorityDnssecFailed,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.dns_authority_dnssec_failed".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_authority_dnssec_failed_data_v1(payload)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.dns_query`
///
/// Schema: `contracts/schemas/cell-observability-dns-query-v1.schema.json`.
///
/// Emitted by the SEAM-1 / L2-04 in-netns DNS proxy on every query — allowed,
/// denied, malformed, or upstream-timed-out. All fields mirror [`DnsQueryEvent`]
/// one-for-one; this builder exists so dataplane callers can serialize the
/// payload without re-deriving the canonical JSON shape from the struct.
pub fn dns_query_data_v1(event: &DnsQueryEvent) -> Result<Value, serde_json::Error> {
    serde_json::to_value(event)
}

/// CloudEvent envelope constructor for `dns_query` (SEAM-1 / L2-04).
///
/// Mirrors [`cloud_event_v1_dns_authority_drift`] for the per-query DNS proxy
/// signal. Lives in `cellos-core` so the supervisor's DNS proxy module can
/// build envelopes without taking a supervisor-internal dependency.
///
/// `source` should identify the publisher (e.g. `"cellos-supervisor"` or
/// `"cellos-dns-proxy"`). `time` is the RFC3339 emission timestamp; typically
/// equal to `event.observed_at` but conceptually distinct (the latter is when
/// the proxy *observed* the query).
pub fn cloud_event_v1_dns_query(
    source: &str,
    time: &str,
    event: &DnsQueryEvent,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.dns_query".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_query_data_v1(event)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// SEAM-1 Phase 3 — per-query data payload for
/// `dev.cellos.events.cell.dns.v1.query_permitted`.
///
/// Schema: `contracts/schemas/cell-dns-query-permitted-v1.schema.json`.
///
/// Companion to the existing aggregate `dns_query` event: this is the
/// short-form "the allowlist check accepted this query" signal that fires
/// as soon as the proxy decides to forward, BEFORE the upstream answer
/// arrives. It exists so operators can audit the workload's query
/// intent independently of upstream latency / outcome.
///
/// `qname` is lowercased and trailing-dot-stripped per the upstream
/// parser; `qtype` is the IANA mnemonic (`"A"`, `"AAAA"`, etc); `cell_id`
/// mirrors `lifecycle.started.cellId`; `resolver` mirrors the
/// `dnsAuthority.resolvers[].resolverId` the proxy will forward to.
#[must_use]
pub fn dns_query_permitted_data_v1(
    qname: &str,
    qtype: &str,
    cell_id: &str,
    resolver: &str,
) -> Value {
    json!({
        "schemaVersion": "1.0.0",
        "queryName": qname,
        "queryType": qtype,
        "cellId": cell_id,
        "resolver": resolver,
    })
}

/// CloudEvent envelope constructor for `dns_query_permitted` (SEAM-1 Phase 3).
pub fn cloud_event_v1_dns_query_permitted(
    source: &str,
    time: &str,
    qname: &str,
    qtype: &str,
    cell_id: &str,
    resolver: &str,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.dns.v1.query_permitted".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_query_permitted_data_v1(qname, qtype, cell_id, resolver)),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// SEAM-1 Phase 3 — per-query data payload for
/// `dev.cellos.events.cell.dns.v1.query_refused`.
///
/// Schema: `contracts/schemas/cell-dns-query-refused-v1.schema.json`.
///
/// Emitted alongside the existing aggregate `dns_query{decision:deny}`
/// event when the allowlist check (or query-type gate) short-circuits a
/// workload query with REFUSED. The short-form payload is intended for
/// SIEM rules that want to fan out on refusal without parsing the
/// richer aggregate event.
///
/// `reason` is one of the proxy's `reasonCode` enum values — typically
/// `"denied_not_in_allowlist"` or `"denied_query_type"`.
#[must_use]
pub fn dns_query_refused_data_v1(qname: &str, qtype: &str, cell_id: &str, reason: &str) -> Value {
    json!({
        "schemaVersion": "1.0.0",
        "queryName": qname,
        "queryType": qtype,
        "cellId": cell_id,
        "reason": reason,
    })
}

/// CloudEvent envelope constructor for `dns_query_refused` (SEAM-1 Phase 3).
pub fn cloud_event_v1_dns_query_refused(
    source: &str,
    time: &str,
    qname: &str,
    qtype: &str,
    cell_id: &str,
    reason: &str,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.dns.v1.query_refused".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(dns_query_refused_data_v1(qname, qtype, cell_id, reason)),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// `dev.cellos.events.cell.trust.v1.keyset_verified` (SEC-25 Phase 2).
///
/// Schema: `contracts/schemas/cell-trust-keyset-verified-v1.schema.json`.
///
/// Emitted once per supervisor startup when `CELLOS_TRUST_KEYSET_PATH` points
/// at a `signed-trust-keyset-envelope-v1` document AND
/// `verify_signed_trust_keyset_envelope` accepted at least one signature
/// against the operator-loaded keyring (`CELLOS_TRUST_VERIFY_KEYS_PATH`).
///
/// `correlation_id` is optional; the supervisor passes `None` for the default
/// startup-time emission, but other producers may bind a correlation id when
/// the verification is part of a larger orchestration flow.
pub fn keyset_verified_data_v1(
    keyset_id: &str,
    payload_digest: &str,
    verified_signer_kid: &str,
    verified_at: &str,
    correlation_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("schemaVersion".to_string(), json!("1.0.0"));
    m.insert("keysetId".to_string(), json!(keyset_id));
    m.insert("payloadDigest".to_string(), json!(payload_digest));
    m.insert("verifiedSignerKid".to_string(), json!(verified_signer_kid));
    m.insert("verifiedAt".to_string(), json!(verified_at));
    if let Some(cid) = correlation_id {
        m.insert("correlationId".to_string(), json!(cid));
    }
    Ok(Value::Object(m))
}

/// CloudEvent envelope constructor for `keyset_verified` (SEC-25 Phase 2).
///
/// `source` should typically be `"cellos-supervisor"` for the startup-time
/// emission; sibling tooling (`cellos-trustd` etc.) may publish under a
/// different source identifier when verifying envelopes off-host.
pub fn cloud_event_v1_keyset_verified(
    source: &str,
    time: &str,
    keyset_id: &str,
    payload_digest: &str,
    verified_signer_kid: &str,
    verified_at: &str,
    correlation_id: Option<&str>,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.trust.v1.keyset_verified".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(keyset_verified_data_v1(
            keyset_id,
            payload_digest,
            verified_signer_kid,
            verified_at,
            correlation_id,
        )?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.trust.v1.keyset_verification_failed` (SEC-25 Phase 2).
///
/// Schema: `contracts/schemas/cell-trust-keyset-verification-failed-v1.schema.json`.
///
/// Emitted once per supervisor startup when `CELLOS_TRUST_KEYSET_PATH` is set
/// AND verification fails (file open / JSON parse / digest mismatch / no
/// signature verified). Under `CELLOS_REQUIRE_TRUST_VERIFY_KEYS=1` the
/// supervisor instead returns an error from `build_supervisor` and never
/// emits this event — fail-closed startup is the explicit operator opt-in;
/// fail-open is the default and surfaces this event so degraded trust posture
/// is visible in the audit stream.
///
/// `attempted_keyset_path` MUST be the file's basename (the supervisor's
/// emitter strips the directory portion to avoid leaking deployment-side
/// metadata into the event stream — see the schema description).
pub fn keyset_verification_failed_data_v1(
    attempted_keyset_path: &str,
    reason: &str,
    failed_at: &str,
    correlation_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("schemaVersion".to_string(), json!("1.0.0"));
    m.insert(
        "attemptedKeysetPath".to_string(),
        json!(attempted_keyset_path),
    );
    m.insert("reason".to_string(), json!(reason));
    m.insert("failedAt".to_string(), json!(failed_at));
    if let Some(cid) = correlation_id {
        m.insert("correlationId".to_string(), json!(cid));
    }
    Ok(Value::Object(m))
}

/// CloudEvent envelope constructor for `keyset_verification_failed` (SEC-25 Phase 2).
pub fn cloud_event_v1_keyset_verification_failed(
    source: &str,
    time: &str,
    attempted_keyset_path: &str,
    reason: &str,
    failed_at: &str,
    correlation_id: Option<&str>,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.trust.v1.keyset_verification_failed".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(keyset_verification_failed_data_v1(
            attempted_keyset_path,
            reason,
            failed_at,
            correlation_id,
        )?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.network_flow_decision` (FC-38 Phase 1).
///
/// Schema: `contracts/schemas/cell-observability-network-flow-decision-v1.schema.json`.
///
/// Emitted by the supervisor's post-run nft counter scan
/// (`nft list ruleset --json`) when `CELLOS_PER_FLOW_ENFORCEMENT_EVENTS=1`.
/// scope: honest "policy-applied attribution" — one event per matched or
/// applied rule, NOT a real-time per-packet stream. Future eBPF / nflog
/// work targets real-time per-flow events.
///
/// All fields mirror [`NetworkFlowDecision`] one-for-one; this builder exists
/// so supervisor wiring can emit the payload without re-deriving the canonical
/// JSON shape from the struct.
pub fn network_flow_decision_data_v1(
    decision: &NetworkFlowDecision,
) -> Result<Value, serde_json::Error> {
    serde_json::to_value(decision)
}

/// CloudEvent envelope constructor for `network_flow_decision` (FC-38 Phase 1).
///
/// Mirrors [`cloud_event_v1_dns_authority_drift`] for the per-flow signal.
/// Lives in `cellos-core` so the supervisor's post-run counter-scan path can
/// build envelopes without taking a supervisor-internal dependency.
///
/// `source` should identify the publisher (e.g. `"cellos-supervisor"`).
/// `time` is the RFC3339 emission timestamp; typically equal to
/// `decision.observed_at` but conceptually distinct (the latter is when the
/// supervisor *scraped* the counter, the former when the envelope was built).
pub fn cloud_event_v1_network_flow_decision(
    source: &str,
    time: &str,
    decision: &NetworkFlowDecision,
) -> Result<CloudEventV1, serde_json::Error> {
    Ok(CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.observability.v1.network_flow_decision".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(network_flow_decision_data_v1(decision)?),
        time: Some(time.to_string()),
        traceparent: None,
    })
}

/// `dev.cellos.events.cell.observability.v1.l7_egress_decision`
///
/// Schema: `contracts/schemas/cell-observability-l7-egress-decision-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_l7_egress_decision_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    decision_id: &str,
    action: &str,
    sni_host: &str,
    policy_digest: &str,
    keyset_id: &str,
    issuer_kid: &str,
    reason_code: &str,
    rule_ref: Option<&str>,
    // scope: per-stream correlation id for h2 paths. `None` for
    // SNI / HTTP/1.x / unknown / peek-timeout paths. Additive — the
    // schema's `streamId` field is optional so the field is omitted
    // from the output when `None`.
    stream_id: Option<u32>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    m.insert("decisionId".to_string(), json!(decision_id));
    m.insert("action".to_string(), json!(action));
    m.insert("sniHost".to_string(), json!(sni_host));
    m.insert("policyDigest".to_string(), json!(policy_digest));
    m.insert("keysetId".to_string(), json!(keyset_id));
    m.insert("issuerKid".to_string(), json!(issuer_kid));
    m.insert("reasonCode".to_string(), json!(reason_code));
    if let Some(rr) = rule_ref {
        m.insert("ruleRef".to_string(), json!(rr));
    }
    if let Some(sid) = stream_id {
        m.insert("streamId".to_string(), json!(sid));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.observability.v1.container_security`
///
/// Emitted once per cell run immediately after `lifecycle.started`, recording
/// the Linux capability bitmasks read from `/proc/self/status` at supervisor
/// start time.  This gives the audit trail a concrete answer to "what
/// capabilities did the cell have?" rather than "deepce could not determine
/// capabilities because capsh was not installed."
///
/// Fields:
/// - `capEff`  — effective capability bitmask (hex string, e.g. `"00000000a80425fb"`)
/// - `capPrm`  — permitted capability bitmask
/// - `capBnd`  — bounding set bitmask
/// - `capAmb`  — ambient capability bitmask
/// - `capInh`  — inheritable capability bitmask
/// - `privileged` — `true` when `capEff` equals `0x1ffffffffff` (all 40 caps set)
///
/// All fields are `None`/omitted on non-Linux hosts or when `/proc/self/status`
/// is unreadable.  Consumers should treat absence as "unknown," not "clean."
pub fn observability_container_security_data_v1(
    cell_id: &str,
    run_id: Option<&str>,
    cap_eff: Option<&str>,
    cap_prm: Option<&str>,
    cap_bnd: Option<&str>,
    cap_amb: Option<&str>,
    cap_inh: Option<&str>,
) -> Value {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let (Some(eff), Some(prm), Some(bnd), Some(amb), Some(inh)) =
        (cap_eff, cap_prm, cap_bnd, cap_amb, cap_inh)
    {
        m.insert("capEff".to_string(), json!(eff));
        m.insert("capPrm".to_string(), json!(prm));
        m.insert("capBnd".to_string(), json!(bnd));
        m.insert("capAmb".to_string(), json!(amb));
        m.insert("capInh".to_string(), json!(inh));
        // Full privileged set: all 40 defined capabilities (Linux 5.x bitmask).
        let privileged = eff == "0000001fffffffff";
        m.insert("privileged".to_string(), json!(privileged));
    }
    Value::Object(m)
}

/// `dev.cellos.events.cell.compliance.v1.summary`
///
/// Emitted once per cell run immediately before `lifecycle.destroyed`.
/// Captures the compliance-relevant profile of the run: which policy pack
/// governed it, what security controls were declared, and the final command
/// exit code (when available).
///
/// This event is the canonical compliance receipt — it allows fleet operators
/// and auditors to reconstruct "what policy was in effect and what was
/// observed" for every cell run without replaying the full event stream.
///
/// Schema: `contracts/schemas/cell-compliance-summary-v1.schema.json`.
///
/// Backward-compatible thin delegate to
/// [`compliance_summary_data_v1_with_subjects`] with an empty subject set.
/// Existing callers (supervisor and tests) keep their 4-arg signature; the
/// resulting payload omits `subjectUrns` per the schema's "absent when empty"
/// contract.
pub fn compliance_summary_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    command_exit_code: Option<i32>,
) -> Result<Value, serde_json::Error> {
    compliance_summary_data_v1_with_subjects(spec, cell_id, run_id, command_exit_code, &[])
}

/// Seam-freeze G4 / P0-7 variant of [`compliance_summary_data_v1`] that
/// attaches a typed-URN subject set covered by the compliance receipt.
///
/// `subject_urns` SHOULD be the concrete URNs (cells, leases, exports, …)
/// whose lifecycle this compliance.summary attests to. Callers pass `&[]`
/// for the legacy "no cross-pointer" shape, which is exactly what the
/// thin-delegate [`compliance_summary_data_v1`] does.
///
/// The `subjectUrns` field is **only emitted when non-empty** — schema
/// declares `minItems: 1` and `uniqueItems: true`, so emitting an empty array
/// would fail validation. URN shape validation lives in the schema (regex);
/// this function does not pre-validate to keep the API allocation-free.
///
/// Schema: `contracts/schemas/cell-compliance-summary-v1.schema.json`
/// (`subjectUrns` field).
pub fn compliance_summary_data_v1_with_subjects(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    command_exit_code: Option<i32>,
    subject_urns: &[SubjectUrn],
) -> Result<Value, serde_json::Error> {
    let egress_rule_count = spec
        .authority
        .egress_rules
        .as_ref()
        .map(|v| v.len())
        .unwrap_or(0);
    let export_target_count = spec
        .export
        .as_ref()
        .and_then(|e| e.targets.as_ref())
        .map(|t| t.len())
        .unwrap_or(0);
    let resource_limits_present = spec.run.as_ref().and_then(|r| r.limits.as_ref()).is_some();
    let secret_delivery_mode = spec
        .run
        .as_ref()
        .map(|r| serde_json::to_value(&r.secret_delivery))
        .transpose()?
        .unwrap_or(serde_json::Value::String("env".into()));

    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert(
        "lifetimeTtlSeconds".to_string(),
        json!(spec.lifetime.ttl_seconds),
    );
    m.insert("egressRuleCount".to_string(), json!(egress_rule_count));
    m.insert(
        "resourceLimitsPresent".to_string(),
        json!(resource_limits_present),
    );
    m.insert("secretDeliveryMode".to_string(), secret_delivery_mode);
    m.insert("exportTargetCount".to_string(), json!(export_target_count));

    // Policy attribution — absent when no pack was declared on the spec.
    if let Some(policy) = &spec.policy {
        if let Some(id) = &policy.pack_id {
            m.insert("policyPackId".to_string(), json!(id));
        }
        if let Some(ver) = &policy.pack_version {
            m.insert("policyPackVersion".to_string(), json!(ver));
        }
        if let Some(digest) = &policy.bundle_digest {
            m.insert("policyBundleDigest".to_string(), json!(digest));
        }
    }

    if let Some(placement) = &spec.placement {
        let mut placement_map = Map::new();
        if let Some(pool_id) = &placement.pool_id {
            placement_map.insert("poolId".to_string(), json!(pool_id));
        }
        if let Some(namespace) = &placement.kubernetes_namespace {
            placement_map.insert("kubernetesNamespace".to_string(), json!(namespace));
        }
        if let Some(queue_name) = &placement.queue_name {
            placement_map.insert("queueName".to_string(), json!(queue_name));
        }
        if !placement_map.is_empty() {
            m.insert("placement".to_string(), Value::Object(placement_map));
        }
    }

    if let Some(code) = command_exit_code {
        m.insert("commandExitCode".to_string(), json!(code));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }

    // Seam-freeze G4 / P0-7 cross-pointer. Emit only when non-empty so the
    // legacy 4-arg path (and any future "no subjects" caller) keeps producing
    // a payload that round-trips against the existing valid example.
    if !subject_urns.is_empty() {
        let urns: Vec<Value> = subject_urns.iter().map(|u| json!(u)).collect();
        m.insert("subjectUrns".to_string(), Value::Array(urns));
    }

    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.policy.v1.rejected`.
///
/// Emitted when a policy pack's admission gate rejects a cell before the
/// lifecycle starts.  The `violations` array lists every failed rule, giving
/// operators a complete picture of what must change.
///
/// Schema: `contracts/schemas/cell-policy-rejected-v1.schema.json`.
pub fn policy_rejected_data_v1(
    spec: &ExecutionCellSpec,
    violations: &[PolicyViolation],
) -> Result<Value, serde_json::Error> {
    let violation_values: Vec<Value> = violations
        .iter()
        .map(|v| {
            json!({
                "rule": v.rule,
                "message": v.message,
            })
        })
        .collect();

    let mut m = Map::new();
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("violationCount".to_string(), json!(violations.len()));
    m.insert("violations".to_string(), Value::Array(violation_values));

    // Policy attribution — absent when no pack was declared on the spec.
    if let Some(policy) = &spec.policy {
        if let Some(id) = &policy.pack_id {
            m.insert("policyPackId".to_string(), json!(id));
        }
        if let Some(ver) = &policy.pack_version {
            m.insert("policyPackVersion".to_string(), json!(ver));
        }
    }

    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// T12 RBAC — `data` for event type `dev.cellos.events.cell.authz.v1.rejected`.
///
/// Emitted by the supervisor when the operator's `AuthorizationPolicy`
/// (loaded from `CELLOS_AUTHZ_POLICY_PATH`) rejects a cell spec at
/// admission. Sibling event to `cell.policy.v1.rejected`, with a different
/// rule namespace (authz subject/pool/pack vs policy-pack admission). Both
/// gates can fire independently.
///
/// `reason` is one of the strings declared in the schema:
/// `subject_not_authorized`, `pool_not_allowed`, `policy_pack_not_allowed`,
/// `rate_limit_exceeded`. Schema:
/// `contracts/schemas/cell-authz-rejected-v1.schema.json`.
pub fn authz_rejected_data_v1(
    spec: &ExecutionCellSpec,
    reason: &str,
    message: &str,
    denied_pool_id: Option<&str>,
    denied_policy_pack_id: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("reason".to_string(), json!(reason));
    m.insert("message".to_string(), json!(message));

    let tenant_id = spec
        .correlation
        .as_ref()
        .and_then(|c| c.tenant_id.as_deref());
    if let Some(t) = tenant_id {
        m.insert("tenantId".to_string(), json!(t));
        // 1.0 subject axis: subject == tenantId. Mirrored as a separate field
        // so consumers don't need to reach into correlation, and so future
        // subject axes (oidc, k8s) can replace it without breaking the
        // event shape.
        m.insert("subject".to_string(), json!(t));
    }

    if let Some(p) = denied_pool_id {
        m.insert("deniedPoolId".to_string(), json!(p));
    }
    if let Some(p) = denied_policy_pack_id {
        m.insert("deniedPolicyPackId".to_string(), json!(p));
    }

    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.authority.v1.homeostasis`
///
/// Emitted once per run between `compliance.summary` and `lifecycle.destroyed`.
/// Compares declared vs exercised authority. Aggregation across runs belongs in taudit.
///
/// Schema: `contracts/schemas/cell-authority-homeostasis-v1.schema.json`.
pub fn homeostasis_signal_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    signal: &crate::HomeostasisSignal,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specHash".to_string(), json!(&signal.spec_hash));
    m.insert(
        "declaredEgressRules".to_string(),
        json!(signal.declared_egress_rules),
    );
    // E2-06: exercisedEgressConnections is nullable while real telemetry (L2-04 / L5-15)
    // is wired. When the count is None, emit JSON `null` AND a sibling
    // `exercisedEgressReason` so consumers can distinguish "telemetry pending" from a
    // true zero.
    m.insert(
        "exercisedEgressConnections".to_string(),
        match signal.exercised_egress_connections {
            Some(n) => json!(n),
            None => Value::Null,
        },
    );
    if let Some(reason) = &signal.exercised_egress_reason {
        m.insert("exercisedEgressReason".to_string(), json!(reason));
    }
    m.insert(
        "declaredMountPaths".to_string(),
        json!(signal.declared_mount_paths),
    );
    m.insert(
        "accessedMountPaths".to_string(),
        json!(signal.accessed_mount_paths),
    );
    m.insert(
        "declaredSecretCount".to_string(),
        json!(signal.declared_secret_count),
    );
    m.insert(
        "authorityEfficiency".to_string(),
        json!(signal.authority_efficiency),
    );
    m.insert(
        "recommendedRemovals".to_string(),
        serde_json::to_value(&signal.recommended_removals)?,
    );
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `dev.cellos.events.cell.authority.v1.homeostasis_violation`
///
/// Emitted when exercised egress connections exceed declared authority — a
/// security invariant violation. The workload made connections beyond what
/// it declared it would need, which means either (a) the spec under-declares
/// the workload's real needs, or (b) the nftables/eBPF enforcement layer did
/// not prevent connections that policy rejected.
///
/// Pure JSON constructor (no I/O). Callers compute `overage` outside this
/// helper and pass `exercised`; this builder MUST NOT underflow, so the
/// caller is responsible for guaranteeing `exercised >= declared` before
/// invocation. The supervisor emit site guards on `exercised > declared`.
///
/// Schema: `contracts/schemas/cell-authority-homeostasis-violation-v1.schema.json`.
pub fn homeostasis_violation_data_v1(
    cell_id: &str,
    declared_egress: u64,
    exercised_egress: u64,
    spec_hash: &str,
) -> Value {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert(
        "declaredEgressRuleCount".to_string(),
        json!(declared_egress),
    );
    m.insert(
        "exercisedEgressConnections".to_string(),
        json!(exercised_egress),
    );
    // Caller guarantees exercised >= declared; saturating_sub protects against
    // accidental misuse without panicking.
    m.insert(
        "overage".to_string(),
        json!(exercised_egress.saturating_sub(declared_egress)),
    );
    m.insert("specHash".to_string(), json!(spec_hash));
    m.insert("severity".to_string(), json!("critical"));
    Value::Object(m)
}

// ---------------------------------------------------------------------------
// F1b — Path B host-side observability primitives + evidence_bundle (ADR-0006)
//
// Builders below construct the JSON `data` payload for the new
// `dev.cellos.events.cell.observability.host.v1.*` event types and the
// per-cell `dev.cellos.events.cell.evidence_bundle.v1.emitted` aggregation
// primitive ("the 1.0 deliverable" — ADR-0006 §4). These are pure JSON
// constructors; sampling and emission live in `cellos-host-telemetry` and
// `cellos-supervisor` (slot F1a).
//
// All five host-probe builders carry a `spec_signature_hash` that the
// supervisor host-stamps before emit (ADR-0006 §6). The evidence_bundle
// builder requires both `spec_signature_hash` and `cell_destroyed_event_ref`
// — the latter enforces D5 destruction-evidence integration: a bundle
// without a `cell.lifecycle.v1.destroyed` reference is structurally invalid
// (see schema gate in `contracts/schemas/evidence-bundle-v1.schema.json`).
// ---------------------------------------------------------------------------

/// `dev.cellos.events.cell.observability.host.v1.fc_metrics`
///
/// Per-cell snapshot of Firecracker metrics endpoint counters (KVM exits,
/// vsock bytes, block ops). Path B (ADR-0006).
///
/// Schema: `contracts/schemas/cell-observability-host-fc-metrics-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_host_fc_metrics_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    spec_signature_hash: &str,
    sampled_at_unix_ms: u64,
    fc_socket_path: &str,
    vcpu_exits_total: Option<u64>,
    vsock_tx_bytes: Option<u64>,
    vsock_rx_bytes: Option<u64>,
    block_read_ops: Option<u64>,
    block_write_ops: Option<u64>,
    sample_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specSignatureHash".to_string(), json!(spec_signature_hash));
    m.insert("sampledAtUnixMs".to_string(), json!(sampled_at_unix_ms));
    m.insert("fcSocketPath".to_string(), json!(fc_socket_path));
    if let Some(v) = vcpu_exits_total {
        m.insert("vcpuExitsTotal".to_string(), json!(v));
    }
    if let Some(v) = vsock_tx_bytes {
        m.insert("vsockTxBytes".to_string(), json!(v));
    }
    if let Some(v) = vsock_rx_bytes {
        m.insert("vsockRxBytes".to_string(), json!(v));
    }
    if let Some(v) = block_read_ops {
        m.insert("blockReadOps".to_string(), json!(v));
    }
    if let Some(v) = block_write_ops {
        m.insert("blockWriteOps".to_string(), json!(v));
    }
    if let Some(e) = sample_error {
        m.insert("sampleError".to_string(), json!(e));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// One memory.events / cpu.stat / pids.events sample for
/// [`observability_host_cgroup_data_v1`].
#[derive(Debug, Default, Clone)]
pub struct CgroupSample<'a> {
    pub memory_events: Option<&'a [(&'a str, u64)]>,
    pub cpu_stat: Option<&'a [(&'a str, u64)]>,
    pub pids_events: Option<&'a [(&'a str, u64)]>,
}

/// `dev.cellos.events.cell.observability.host.v1.cgroup`
///
/// Per-cell cgroup v2 counter snapshot (memory.events, cpu.stat,
/// pids.events). Path B (ADR-0006).
///
/// `sample` carries the kernel-reported counter pairs the supervisor read
/// from `/sys/fs/cgroup/<cell-leaf>/`. Field names map directly to the
/// schema's nested objects; unknown keys are silently dropped at emit time
/// because the schema's `additionalProperties: false` would reject them.
///
/// Schema: `contracts/schemas/cell-observability-host-cgroup-v1.schema.json`.
fn cgroup_section(keys: &[&str], pairs: Option<&[(&str, u64)]>) -> Option<Value> {
    let pairs = pairs?;
    let mut section = Map::new();
    for (k, v) in pairs {
        if keys.contains(k) {
            section.insert((*k).to_string(), json!(v));
        }
    }
    if section.is_empty() {
        None
    } else {
        Some(Value::Object(section))
    }
}

/// `dev.cellos.events.cell.observability.host.v1.cgroup` (see [`CgroupSample`]).
#[allow(clippy::too_many_arguments)]
pub fn observability_host_cgroup_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    spec_signature_hash: &str,
    sampled_at_unix_ms: u64,
    cgroup_path: &str,
    sample: &CgroupSample<'_>,
    sample_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    const MEM_KEYS: &[&str] = &["low", "high", "max", "oom", "oomKill"];
    const CPU_KEYS: &[&str] = &[
        "usageUsec",
        "userUsec",
        "systemUsec",
        "nrPeriods",
        "nrThrottled",
        "throttledUsec",
    ];
    const PIDS_KEYS: &[&str] = &["max"];

    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specSignatureHash".to_string(), json!(spec_signature_hash));
    m.insert("sampledAtUnixMs".to_string(), json!(sampled_at_unix_ms));
    m.insert("cgroupPath".to_string(), json!(cgroup_path));
    if let Some(v) = cgroup_section(MEM_KEYS, sample.memory_events) {
        m.insert("memoryEvents".to_string(), v);
    }
    if let Some(v) = cgroup_section(CPU_KEYS, sample.cpu_stat) {
        m.insert("cpuStat".to_string(), v);
    }
    if let Some(v) = cgroup_section(PIDS_KEYS, sample.pids_events) {
        m.insert("pidsEvents".to_string(), v);
    }
    if let Some(e) = sample_error {
        m.insert("sampleError".to_string(), json!(e));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// One nft rule counter row for [`observability_host_nftables_data_v1`].
#[derive(Debug, Clone)]
pub struct NftRuleCounter<'a> {
    pub rule_handle: &'a str,
    pub verdict: Option<&'a str>,
    pub packets: u64,
    pub bytes: u64,
    pub r#match: Option<&'a str>,
}

/// `dev.cellos.events.cell.observability.host.v1.nftables`
///
/// Per-cell nftables counter snapshot scraped from the cell's netns. Path B
/// (ADR-0006).
///
/// Schema: `contracts/schemas/cell-observability-host-nftables-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_host_nftables_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    spec_signature_hash: &str,
    sampled_at_unix_ms: u64,
    table_name: &str,
    rule_counters: &[NftRuleCounter<'_>],
    sample_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specSignatureHash".to_string(), json!(spec_signature_hash));
    m.insert("sampledAtUnixMs".to_string(), json!(sampled_at_unix_ms));
    m.insert("tableName".to_string(), json!(table_name));
    let counters: Vec<Value> = rule_counters
        .iter()
        .map(|c| {
            let mut row = Map::new();
            row.insert("ruleHandle".to_string(), json!(c.rule_handle));
            if let Some(v) = c.verdict {
                row.insert("verdict".to_string(), json!(v));
            }
            row.insert("packets".to_string(), json!(c.packets));
            row.insert("bytes".to_string(), json!(c.bytes));
            if let Some(mt) = c.r#match {
                row.insert("match".to_string(), json!(mt));
            }
            Value::Object(row)
        })
        .collect();
    m.insert("ruleCounters".to_string(), Value::Array(counters));
    if let Some(e) = sample_error {
        m.insert("sampleError".to_string(), json!(e));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// Per-TAP statistics row for [`observability_host_tap_data_v1`].
#[derive(Debug, Default, Clone, Copy)]
pub struct TapStats {
    pub rx_packets: Option<u64>,
    pub tx_packets: Option<u64>,
    pub rx_bytes: Option<u64>,
    pub tx_bytes: Option<u64>,
    pub rx_errors: Option<u64>,
    pub tx_errors: Option<u64>,
    pub rx_dropped: Option<u64>,
    pub tx_dropped: Option<u64>,
}

/// `dev.cellos.events.cell.observability.host.v1.tap`
///
/// Per-cell TAP-link snapshot for the FC microVM tap device. Path B
/// (ADR-0006).
///
/// Schema: `contracts/schemas/cell-observability-host-tap-v1.schema.json`.
#[allow(clippy::too_many_arguments)]
pub fn observability_host_tap_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    spec_signature_hash: &str,
    sampled_at_unix_ms: u64,
    tap_name: &str,
    link_state: &str,
    stats: &TapStats,
    sample_error: Option<&str>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specSignatureHash".to_string(), json!(spec_signature_hash));
    m.insert("sampledAtUnixMs".to_string(), json!(sampled_at_unix_ms));
    m.insert("tapName".to_string(), json!(tap_name));
    m.insert("linkState".to_string(), json!(link_state));
    if let Some(v) = stats.rx_packets {
        m.insert("rxPackets".to_string(), json!(v));
    }
    if let Some(v) = stats.tx_packets {
        m.insert("txPackets".to_string(), json!(v));
    }
    if let Some(v) = stats.rx_bytes {
        m.insert("rxBytes".to_string(), json!(v));
    }
    if let Some(v) = stats.tx_bytes {
        m.insert("txBytes".to_string(), json!(v));
    }
    if let Some(v) = stats.rx_errors {
        m.insert("rxErrors".to_string(), json!(v));
    }
    if let Some(v) = stats.tx_errors {
        m.insert("txErrors".to_string(), json!(v));
    }
    if let Some(v) = stats.rx_dropped {
        m.insert("rxDropped".to_string(), json!(v));
    }
    if let Some(v) = stats.tx_dropped {
        m.insert("txDropped".to_string(), json!(v));
    }
    if let Some(e) = sample_error {
        m.insert("sampleError".to_string(), json!(e));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// Final residue class for the cell after teardown
/// (per `docs/destruction-semantics.md`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResidueClass {
    /// No host- or broker-side residue tracked for the cell after destroy.
    None,
    /// A residue class with a named runbook entry; see
    /// [`EvidenceBundleRefs::residue_exception`] for the runbook id.
    DocumentedException,
}

/// Coarser-grained residue class historically embedded directly in the
/// `lifecycle.v1.destroyed` payload. Retained for back-compat with consumers
/// that read the destruction event directly without joining the
/// `evidence_bundle.v1.emitted` payload. New code should prefer
/// [`ResidueClass`] on the bundle.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum LifecycleResidueClass {
    None,
    MetadataOnly,
    DocumentedException,
    Unknown,
}

/// References the supervisor aggregates into an `evidence_bundle` payload.
///
/// All identifiers are CloudEvent envelope `id` strings (URN preferred).
/// Required fields enforce ADR-0006 §F1: every emitted bundle ties back to
/// a destruction event (D5) and a host-stamped spec hash (the channel's
/// authenticity primitive). Optional refs are populated only when the
/// supervisor actually emitted the corresponding event for this run —
/// builders never fabricate references.
#[derive(Debug, Default, Clone)]
pub struct EvidenceBundleRefs<'a> {
    /// Required: CloudEvent id of `cell.lifecycle.v1.started`.
    pub started_event_ref: &'a str,
    /// Required: CloudEvent id of `cell.lifecycle.v1.destroyed` (D5).
    pub cell_destroyed_event_ref: &'a str,
    pub command_completed_event_ref: Option<&'a str>,
    pub spawned_event_refs: &'a [&'a str],
    pub fc_metrics_event_refs: &'a [&'a str],
    pub cgroup_event_refs: &'a [&'a str],
    pub nftables_event_refs: &'a [&'a str],
    pub tap_event_refs: &'a [&'a str],
    pub homeostasis_event_ref: Option<&'a str>,
    pub compliance_summary_event_ref: Option<&'a str>,
    /// One row per declared `cell.observability.guest.*` event:
    /// `(eventId, eventType, ruleClass)`.
    pub guest_event_refs: &'a [(&'a str, &'a str, &'a str)],
    /// When `residue_class == DocumentedException`, names the runbook entry.
    pub residue_exception: Option<&'a str>,
}

/// `dev.cellos.events.cell.evidence_bundle.v1.emitted`
///
/// The 1.0 per-cell aggregation primitive (ADR-0006 §4) — what the auditor
/// reads cold and what the CI customer pastes into incident review.
/// Carries the spec hash, lifecycle stream refs, Path B host-side resource
/// series refs, declared guest event refs (with ADG rule-class), and the
/// destruction receipt naming the residue class.
///
/// **D5 gate:** `cell_destroyed_event_ref` is required by the schema and by
/// this builder's signature. A bundle without a destruction event reference
/// is rejected by the schema validator and by `tests/residue.rs`
/// (per ADR-0006 §Compliance "destruction gate").
///
/// Schema: `contracts/schemas/evidence-bundle-v1.schema.json`.
pub fn evidence_bundle_emitted_data_v1(
    spec: &ExecutionCellSpec,
    cell_id: &str,
    run_id: Option<&str>,
    spec_signature_hash: &str,
    emitted_at_unix_ms: u64,
    residue_class: ResidueClass,
    refs: &EvidenceBundleRefs<'_>,
) -> Result<Value, serde_json::Error> {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("specId".to_string(), json!(&spec.id));
    m.insert("specSignatureHash".to_string(), json!(spec_signature_hash));
    m.insert("emittedAtUnixMs".to_string(), json!(emitted_at_unix_ms));

    let mut lifecycle = Map::new();
    lifecycle.insert("started".to_string(), json!(refs.started_event_ref));
    lifecycle.insert(
        "destroyed".to_string(),
        json!(refs.cell_destroyed_event_ref),
    );
    if let Some(cc) = refs.command_completed_event_ref {
        lifecycle.insert("commandCompleted".to_string(), json!(cc));
    }
    if !refs.spawned_event_refs.is_empty() {
        lifecycle.insert("spawned".to_string(), json!(refs.spawned_event_refs));
    }
    m.insert("lifecycleEventRefs".to_string(), Value::Object(lifecycle));

    m.insert(
        "cellDestroyedEventRef".to_string(),
        json!(refs.cell_destroyed_event_ref),
    );
    m.insert(
        "residueClass".to_string(),
        serde_json::to_value(residue_class)?,
    );
    if let Some(rx) = refs.residue_exception {
        m.insert("residueException".to_string(), json!(rx));
    }

    let any_host = !refs.fc_metrics_event_refs.is_empty()
        || !refs.cgroup_event_refs.is_empty()
        || !refs.nftables_event_refs.is_empty()
        || !refs.tap_event_refs.is_empty();
    if any_host {
        let mut host = Map::new();
        if !refs.fc_metrics_event_refs.is_empty() {
            host.insert("fcMetrics".to_string(), json!(refs.fc_metrics_event_refs));
        }
        if !refs.cgroup_event_refs.is_empty() {
            host.insert("cgroup".to_string(), json!(refs.cgroup_event_refs));
        }
        if !refs.nftables_event_refs.is_empty() {
            host.insert("nftables".to_string(), json!(refs.nftables_event_refs));
        }
        if !refs.tap_event_refs.is_empty() {
            host.insert("tap".to_string(), json!(refs.tap_event_refs));
        }
        m.insert("hostProbeEventRefs".to_string(), Value::Object(host));
    }

    if !refs.guest_event_refs.is_empty() {
        let rows: Vec<Value> = refs
            .guest_event_refs
            .iter()
            .map(|(id, ty, rc)| {
                let mut row = Map::new();
                row.insert("eventId".to_string(), json!(id));
                row.insert("eventType".to_string(), json!(ty));
                row.insert("ruleClass".to_string(), json!(rc));
                Value::Object(row)
            })
            .collect();
        m.insert("guestEventRefs".to_string(), Value::Array(rows));
    }

    if let Some(h) = refs.homeostasis_event_ref {
        m.insert("homeostasisEventRef".to_string(), json!(h));
    }
    if let Some(c) = refs.compliance_summary_event_ref {
        m.insert("complianceSummaryEventRef".to_string(), json!(c));
    }
    if let Some(r) = run_id {
        m.insert("runId".to_string(), json!(r));
    }
    if let Some(c) = &spec.correlation {
        m.insert("correlation".to_string(), serde_json::to_value(c)?);
    }
    Ok(Value::Object(m))
}

/// `data` for event type `dev.cellos.events.cell.cortex.v1.dispatched`.
///
/// Emitted by `CellosLedgerEmitter` when it processes a Cortex
/// ContextPack dispatch onto a cell. Records the pack id, the cell id,
/// the doctrine refs cited by the pack (subject to ADR-0009 policy), and
/// the Cortex↔CellOS bridge version for downstream auditors.
///
/// Schema: `contracts/schemas/cell-cortex-dispatched-v1.schema.json`.
pub fn cortex_dispatched_data_v1(pack_id: &str, cell_id: &str, doctrine_refs: &[String]) -> Value {
    let mut m = Map::new();
    m.insert("packId".to_string(), json!(pack_id));
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("doctrineRefs".to_string(), json!(doctrine_refs));
    m.insert("bridgeVersion".to_string(), json!("1.0"));
    Value::Object(m)
}

/// `data` for event type `dev.cellos.events.cell.firecracker.v1.pool_checkout`.
///
/// Emitted by `FirecrackerCellBackend` when it satisfies a cell start by
/// either consuming a slot from the warm pool (`poolHit = true`) or
/// falling through to a cold boot (`poolHit = false`). `slotCount` is the
/// number of warm slots available *before* this checkout — useful for
/// detecting pool-exhaustion patterns in audit.
///
/// Schema: `contracts/schemas/cell-firecracker-pool-checkout-v1.schema.json`.
pub fn firecracker_pool_event_data_v1(cell_id: &str, pool_hit: bool, slot_count: usize) -> Value {
    let mut m = Map::new();
    m.insert("cellId".to_string(), json!(cell_id));
    m.insert("poolHit".to_string(), json!(pool_hit));
    m.insert("slotCount".to_string(), json!(slot_count));
    Value::Object(m)
}

/// CloudEvent envelope constructor for `dev.cellos.events.cell.cortex.v1.dispatched`.
///
/// Pairs with [`cortex_dispatched_data_v1`]. `source` is typically the Cortex
/// bridge identifier (e.g. `"cellos-cortex"`); `time` is RFC 3339.
///
/// Schema: `contracts/schemas/cell-cortex-dispatched-v1.schema.json`.
pub fn cloud_event_v1_cortex_dispatched(
    source: &str,
    time: &str,
    pack_id: &str,
    cell_id: &str,
    doctrine_refs: &[String],
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.cortex.v1.dispatched".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(cortex_dispatched_data_v1(pack_id, cell_id, doctrine_refs)),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for `dev.cellos.events.cell.firecracker.v1.pool_checkout`.
///
/// Pairs with [`firecracker_pool_event_data_v1`]. `source` is typically
/// `"cellos-host-firecracker"`; `time` is RFC 3339. `slot_count` is the
/// pool's `Available` count observed *before* the checkout attempt — see
/// the data builder for audit semantics.
///
/// Schema: `contracts/schemas/cell-firecracker-pool-checkout-v1.schema.json`.
pub fn cloud_event_v1_firecracker_pool_checkout(
    source: &str,
    time: &str,
    cell_id: &str,
    pool_hit: bool,
    slot_count: usize,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: "dev.cellos.events.cell.firecracker.v1.pool_checkout".into(),
        datacontenttype: Some("application/json".into()),
        data: Some(firecracker_pool_event_data_v1(
            cell_id, pool_hit, slot_count,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Formation-level lifecycle events (Session 15+16 — Formation model).
//
// The Formation state machine governs a group of related cells managed as a
// single unit. Its transitions are:
//
//   PENDING → LAUNCHING → RUNNING → DEGRADED → COMPLETED / FAILED
//
// Each transition emits a CloudEvent so the formation lifecycle is auditable
// the same way cell lifecycle is auditable. The URN namespace is
// `dev.cellos.events.cell.formation.v1.<phase>`, sharing the `cell.` prefix
// so the FC-74 audit consumer's coverage rules apply uniformly. The shared
// data shape is described by [`FormationEventData`] below.
// ─────────────────────────────────────────────────────────────────────────────

/// CloudEvent `type` URN for [`cloud_event_v1_formation_created`].
pub const FORMATION_CREATED_TYPE: &str = "dev.cellos.events.cell.formation.v1.created";

/// CloudEvent `type` URN for [`cloud_event_v1_formation_launching`].
pub const FORMATION_LAUNCHING_TYPE: &str = "dev.cellos.events.cell.formation.v1.launching";

/// CloudEvent `type` URN for [`cloud_event_v1_formation_running`].
pub const FORMATION_RUNNING_TYPE: &str = "dev.cellos.events.cell.formation.v1.running";

/// CloudEvent `type` URN for [`cloud_event_v1_formation_degraded`].
pub const FORMATION_DEGRADED_TYPE: &str = "dev.cellos.events.cell.formation.v1.degraded";

/// CloudEvent `type` URN for [`cloud_event_v1_formation_completed`].
pub const FORMATION_COMPLETED_TYPE: &str = "dev.cellos.events.cell.formation.v1.completed";

/// CloudEvent `type` URN for [`cloud_event_v1_formation_failed`].
pub const FORMATION_FAILED_TYPE: &str = "dev.cellos.events.cell.formation.v1.failed";

/// Build the canonical `data` payload for every
/// `dev.cellos.events.cell.formation.v1.*` CloudEvent.
///
/// All formation lifecycle events share a single shape so downstream auditors
/// (the FC-74 consumer, `cellos-audit-justification`, SIEM ingest) can join
/// on `formationId` across phases without dispatching per-URN parsers.
///
/// Fields:
/// - `formationId` — stable identifier of the Formation document.
/// - `formationName` — operator-facing label (mirrors `metadata.name` on the
///   FormationDocument).
/// - `cellCount` — total number of cells in the formation at the time of
///   transition. Always present so audit can detect mid-run resize.
/// - `failedCellIds` — concrete cell IDs that contributed to the transition
///   (populated for `degraded` / `failed`, empty for the happy path).
/// - `reason` — short, free-form explanation for `degraded` / `failed`
///   transitions. Omitted on the happy path.
fn formation_data_v1(
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> Value {
    let mut m = Map::new();
    m.insert("formationId".to_string(), json!(formation_id));
    m.insert("formationName".to_string(), json!(formation_name));
    m.insert("cellCount".to_string(), json!(cell_count));
    m.insert("failedCellIds".to_string(), json!(failed_cell_ids));
    if let Some(r) = reason {
        m.insert("reason".to_string(), json!(r));
    }
    Value::Object(m)
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.created` (PENDING phase entry).
///
/// Emitted by the supervisor immediately after a FormationDocument is
/// admitted but before any cell launch has begun. `failed_cell_ids` is
/// expected to be empty on this transition.
pub fn cloud_event_v1_formation_created(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_CREATED_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.launching` (LAUNCHING phase entry).
///
/// Emitted once the supervisor has started attempting to bring up the
/// formation's cells. `failed_cell_ids` is expected to be empty on this
/// transition; transient launch errors that don't fail the whole formation
/// belong on the subsequent `degraded` or `failed` events.
pub fn cloud_event_v1_formation_launching(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_LAUNCHING_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.running` (RUNNING phase entry).
///
/// Emitted once all of the formation's cells reach a healthy steady state.
/// `failed_cell_ids` is expected to be empty on this transition.
pub fn cloud_event_v1_formation_running(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_RUNNING_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.degraded` (DEGRADED phase entry).
///
/// Emitted when at least one but not all of the formation's cells have
/// failed and the formation is continuing to run in a degraded state.
/// `failed_cell_ids` MUST list the affected cells; `reason` SHOULD be set.
pub fn cloud_event_v1_formation_degraded(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_DEGRADED_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.completed` (COMPLETED terminal).
///
/// Emitted when the formation has finished its work successfully and all
/// cells have been torn down cleanly. `failed_cell_ids` is expected to be
/// empty; `reason` MAY carry an operator-facing completion note.
pub fn cloud_event_v1_formation_completed(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_COMPLETED_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

/// CloudEvent envelope constructor for
/// `dev.cellos.events.cell.formation.v1.failed` (FAILED terminal).
///
/// Emitted when the formation has terminated unsuccessfully. `failed_cell_ids`
/// MUST list the cells that drove the failure (callers MAY include the full
/// cell set when the failure is formation-wide); `reason` SHOULD be set.
pub fn cloud_event_v1_formation_failed(
    source: &str,
    time: &str,
    formation_id: &str,
    formation_name: &str,
    cell_count: u32,
    failed_cell_ids: &[String],
    reason: Option<&str>,
) -> CloudEventV1 {
    CloudEventV1 {
        specversion: "1.0".into(),
        id: uuid::Uuid::new_v4().to_string(),
        source: source.to_string(),
        ty: FORMATION_FAILED_TYPE.to_string(),
        datacontenttype: Some("application/json".into()),
        data: Some(formation_data_v1(
            formation_id,
            formation_name,
            cell_count,
            failed_cell_ids,
            reason,
        )),
        time: Some(time.to_string()),
        traceparent: None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        Correlation, ExecutionCellDocument, ExportReceipt, ExportReceiptTargetKind, Lifetime,
        WorkloadIdentity, WorkloadIdentityKind,
    };

    #[test]
    fn lifecycle_started_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-ci-correlation.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-lifecycle-started-data.valid.json"
        ))
        .unwrap();
        let data = lifecycle_started_data_v1(
            &doc.spec,
            "host-cell-abc123",
            Some("run-2026-04-06-001"),
            None,
            None,
            None,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn lifecycle_started_without_correlation() {
        let spec = ExecutionCellSpec {
            id: "s1".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data =
            lifecycle_started_data_v1(&spec, "c1", None, None, None, None, None, None, None, None)
                .unwrap();
        assert!(!data.as_object().unwrap().contains_key("correlation"));
        assert!(!data.as_object().unwrap().contains_key("runId"));
        assert!(!data.as_object().unwrap().contains_key("derivationVerified"));
        assert!(!data.as_object().unwrap().contains_key("roleRoot"));
        assert!(!data.as_object().unwrap().contains_key("parentRunId"));
        assert!(!data.as_object().unwrap().contains_key("kernelDigestSha256"));
        assert!(!data.as_object().unwrap().contains_key("rootfsDigestSha256"));
        assert!(!data
            .as_object()
            .unwrap()
            .contains_key("firecrackerDigestSha256"));
    }

    #[test]
    fn lifecycle_started_partial_correlation_serializes() {
        let spec = ExecutionCellSpec {
            id: "s2".into(),
            correlation: Some(Correlation {
                platform: Some("custom".into()),
                external_run_id: None,
                external_job_id: None,
                tenant_id: None,
                labels: None,
                correlation_id: None,
            }),
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 1 },
            export: None,
            telemetry: None,
        };
        let data =
            lifecycle_started_data_v1(&spec, "c2", None, None, None, None, None, None, None, None)
                .unwrap();
        assert_eq!(data["correlation"]["platform"], "custom");
    }

    #[test]
    fn lifecycle_started_with_derivation_fields_emits_them() {
        let spec = ExecutionCellSpec {
            id: "deriv-1".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = lifecycle_started_data_v1(
            &spec,
            "cell-deriv",
            Some("run-deriv-1"),
            Some(false),
            Some("role-prod-ci"),
            Some("run-parent-001"),
            Some("abc123def456"),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(data["derivationVerified"], false);
        assert_eq!(data["roleRoot"], "role-prod-ci");
        assert_eq!(data["parentRunId"], "run-parent-001");
    }

    #[test]
    fn lifecycle_destroyed_succeeded_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-ci-correlation.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let data = lifecycle_destroyed_data_v1(
            &doc.spec,
            "host-xyz",
            Some("run-test"),
            LifecycleDestroyOutcome::Succeeded,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(data["outcome"], "succeeded");
        assert!(!data.as_object().unwrap().contains_key("reason"));
        assert!(
            !data.as_object().unwrap().contains_key("terminalState"),
            "terminalState must be omitted when None for backward-compat"
        );
        assert!(
            !data.as_object().unwrap().contains_key("evidenceBundleRef"),
            "evidenceBundleRef must be omitted when None for backward-compat"
        );
        assert!(
            !data.as_object().unwrap().contains_key("residueClass"),
            "residueClass must be omitted when None for backward-compat"
        );
        assert_eq!(data["ttlSeconds"], 3600);
    }

    #[test]
    fn lifecycle_destroyed_failed_includes_reason() {
        let spec = ExecutionCellSpec {
            id: "s1".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = lifecycle_destroyed_data_v1(
            &spec,
            "c1",
            None,
            LifecycleDestroyOutcome::Failed,
            Some("secret resolve: denied"),
            None,
            None,
            None,
        )
        .unwrap();
        assert_eq!(data["outcome"], "failed");
        assert_eq!(data["reason"], "secret resolve: denied");
    }

    #[test]
    fn lifecycle_destroyed_terminal_state_clean_serializes() {
        let spec = ExecutionCellSpec {
            id: "term-clean".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = lifecycle_destroyed_data_v1(
            &spec,
            "c-clean",
            None,
            LifecycleDestroyOutcome::Succeeded,
            None,
            Some(LifecycleTerminalState::Clean),
            None,
            None,
        )
        .unwrap();
        assert_eq!(data["terminalState"], "clean");
    }

    #[test]
    fn lifecycle_destroyed_terminal_state_forced_serializes() {
        let spec = ExecutionCellSpec {
            id: "term-forced".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = lifecycle_destroyed_data_v1(
            &spec,
            "c-forced",
            None,
            LifecycleDestroyOutcome::Failed,
            Some("in-VM exit bridge: vsock closed"),
            Some(LifecycleTerminalState::Forced),
            None,
            None,
        )
        .unwrap();
        assert_eq!(data["terminalState"], "forced");
        assert_eq!(data["outcome"], "failed");
    }

    #[test]
    fn lifecycle_destroyed_evidence_bundle_and_residue_class_serialize_when_populated() {
        let spec = ExecutionCellSpec {
            id: "f5-populated".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let bundle = SubjectUrn::parse("urn:cellos:evidence-bundle:run-1").unwrap();
        let data = lifecycle_destroyed_data_v1(
            &spec,
            "c-f5",
            Some("run-1"),
            LifecycleDestroyOutcome::Succeeded,
            None,
            None,
            Some(&bundle),
            Some(ResidueClass::DocumentedException),
        )
        .unwrap();
        assert_eq!(
            data["evidenceBundleRef"],
            "urn:cellos:evidence-bundle:run-1"
        );
        assert_eq!(data["residueClass"], "documented_exception");
    }

    #[test]
    fn lifecycle_destroyed_evidence_bundle_and_residue_class_omitted_when_none() {
        let spec = ExecutionCellSpec {
            id: "f5-omitted".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = lifecycle_destroyed_data_v1(
            &spec,
            "c-f5-omit",
            None,
            LifecycleDestroyOutcome::Succeeded,
            None,
            None,
            None,
            None,
        )
        .unwrap();
        let obj = data.as_object().unwrap();
        assert!(
            !obj.contains_key("evidenceBundleRef"),
            "evidenceBundleRef must be omitted when None"
        );
        assert!(
            !obj.contains_key("residueClass"),
            "residueClass must be omitted when None"
        );
    }

    #[test]
    fn identity_materialized_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-github-oidc-s3.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let identity = doc.spec.identity.as_ref().expect("identity");
        let data = identity_materialized_data_v1(&doc.spec, "host-xyz", Some("run-test"), identity)
            .unwrap();
        assert_eq!(data["identity"]["kind"], "federatedOidc");
        assert_eq!(data["identity"]["provider"], "github-actions");
        assert_eq!(data["identity"]["secretRef"], "AWS_WEB_IDENTITY");
        assert_eq!(data["runId"], "run-test");
    }

    #[test]
    fn identity_revoked_includes_reason() {
        let spec = ExecutionCellSpec {
            id: "s3".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: Some(WorkloadIdentity {
                kind: WorkloadIdentityKind::FederatedOidc,
                provider: "github-actions".into(),
                audience: "sts.amazonaws.com".into(),
                subject: None,
                ttl_seconds: Some(900),
                secret_ref: "AWS_WEB_IDENTITY".into(),
            }),
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 3600 },
            export: None,
            telemetry: None,
        };
        let identity = spec.identity.as_ref().unwrap();
        let data =
            identity_revoked_data_v1(&spec, "c3", None, identity, Some("teardown"), None).unwrap();
        assert_eq!(data["identity"]["audience"], "sts.amazonaws.com");
        assert_eq!(data["reason"], "teardown");
    }

    #[test]
    fn identity_failed_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-github-oidc-s3.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-identity-failed-data.valid.json"
        ))
        .unwrap();
        let identity = doc.spec.identity.as_ref().expect("identity");
        let data = identity_failed_data_v1(
            &doc.spec,
            "host-cell-demo",
            Some("run-001"),
            identity,
            IdentityFailureOperation::Materialize,
            "oidc exchange denied by upstream federation policy",
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn export_completed_v2_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-github-oidc-s3.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let receipt = ExportReceipt {
            target_kind: ExportReceiptTargetKind::S3,
            target_name: Some("artifact-bucket".into()),
            destination: "s3://acme-cellos-artifacts/github/acme/widget/123456789/test-results"
                .into(),
            bytes_written: 1024,
        };
        let data = export_completed_data_v2(
            &doc.spec,
            "host-xyz",
            Some("run-test"),
            "test-results",
            &receipt,
            None,
        )
        .unwrap();
        assert_eq!(data["receipt"]["targetKind"], "s3");
        assert_eq!(data["receipt"]["targetName"], "artifact-bucket");
        assert_eq!(data["receipt"]["bytesWritten"], 1024);
    }

    #[test]
    fn export_completed_v2_http_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/execution-cell-github-oidc-multi-export.valid.json"
        );
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-export-v2-completed-data-http.valid.json"
        ))
        .unwrap();
        let receipt = ExportReceipt {
            target_kind: ExportReceiptTargetKind::Http,
            target_name: Some("artifact-api".into()),
            destination: "https://artifacts.acme.internal/upload/host-cell-demo/coverage-summary"
                .into(),
            bytes_written: 512,
        };
        let data = export_completed_data_v2(
            &doc.spec,
            "host-cell-demo",
            Some("run-002"),
            "coverage-summary",
            &receipt,
            None,
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn export_failed_v2_http_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/execution-cell-github-oidc-multi-export.valid.json"
        );
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-export-v2-failed-data.valid.json"
        ))
        .unwrap();
        let data = export_failed_data_v2(
            &doc.spec,
            "host-cell-demo",
            Some("run-002"),
            "coverage-summary",
            ExportReceiptTargetKind::Http,
            Some("artifact-api"),
            Some("https://artifacts.acme.internal/upload/host-cell-demo/coverage-summary"),
            "http put returned 403 Forbidden",
            None,
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn compliance_summary_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-ci-correlation.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-compliance-summary-data.valid.json"
        ))
        .unwrap();
        let data =
            compliance_summary_data_v1(&doc.spec, "host-cell-demo", Some("run-003"), Some(0))
                .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn compliance_summary_omits_placement_when_absent() {
        let spec = ExecutionCellSpec {
            id: "compliance-no-placement".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = compliance_summary_data_v1(&spec, "cell-001", None, None).unwrap();
        assert!(!data.as_object().unwrap().contains_key("placement"));
    }

    /// P0-7 / G4: empty `subject_urns` slice MUST keep the payload byte-shape
    /// identical to the legacy 4-arg delegate — i.e. `subjectUrns` is omitted.
    /// This is the contract that lets supervisor.rs keep its current call
    /// site unchanged.
    #[test]
    fn compliance_summary_with_empty_subjects_omits_field() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-ci-correlation.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let legacy =
            compliance_summary_data_v1(&doc.spec, "host-cell-demo", Some("run-003"), Some(0))
                .unwrap();
        let with_empty = compliance_summary_data_v1_with_subjects(
            &doc.spec,
            "host-cell-demo",
            Some("run-003"),
            Some(0),
            &[],
        )
        .unwrap();
        assert_eq!(legacy, with_empty);
        assert!(!with_empty.as_object().unwrap().contains_key("subjectUrns"));
    }

    /// P0-7 / G4: non-empty subject set must round-trip against the
    /// `cell-compliance-summary-data-with-subjects.valid.json` golden fixture.
    #[test]
    fn compliance_summary_with_subjects_matches_example_shape() {
        let raw =
            include_str!("../../../contracts/examples/execution-cell-ci-correlation.valid.json");
        let doc: ExecutionCellDocument = serde_json::from_str(raw).unwrap();
        let expected: Value = serde_json::from_str(include_str!(
            "../../../contracts/examples/cell-compliance-summary-data-with-subjects.valid.json"
        ))
        .unwrap();
        let subjects: Vec<SubjectUrn> = vec![
            SubjectUrn::parse("urn:cellos:cell:host-cell-demo").unwrap(),
            SubjectUrn::parse("urn:tsafe:lease:lease-42").unwrap(),
            SubjectUrn::parse("urn:cellos:export:run-003%2Fartifact-1").unwrap(),
        ];
        let data = compliance_summary_data_v1_with_subjects(
            &doc.spec,
            "host-cell-demo",
            Some("run-003"),
            Some(0),
            &subjects,
        )
        .unwrap();
        assert_eq!(data, expected);
        let urns = data["subjectUrns"].as_array().unwrap();
        assert_eq!(urns.len(), 3);
        assert_eq!(urns[0], "urn:cellos:cell:host-cell-demo");
    }

    /// P0-7 / G4 negative fixture: `cell-compliance-summary-data.invalid.json`
    /// is intentionally malformed (URNs that violate the schema regex). The
    /// `scripts/validate_contracts.py` walker only globs `*.valid.json`, so we
    /// load the negative fixture explicitly here and hand-check each entry
    /// against the schema regex shape. If this test ever passes the regex,
    /// the fixture has drifted away from "negative" and must be regenerated.
    #[test]
    fn compliance_summary_invalid_subject_urns_fixture_is_malformed() {
        let raw =
            include_str!("../../../contracts/examples/cell-compliance-summary-data.invalid.json");
        let v: Value = serde_json::from_str(raw).unwrap();
        let urns = v["subjectUrns"]
            .as_array()
            .expect("invalid fixture must carry subjectUrns array");
        assert!(!urns.is_empty(), "negative fixture must have entries");

        // Schema regex from cell-compliance-summary-v1.schema.json. We don't
        // pull in a regex crate just for this — instead we apply a minimal
        // structural decomposition that the schema regex enforces:
        //   urn:<tool>:<kind>:<id>
        //   tool/kind = [a-z0-9][a-z0-9-]*  (lowercase, must start alnum)
        //   id        = non-empty, [A-Za-z0-9._:%-]+
        fn matches_schema_shape(s: &str) -> bool {
            let parts: Vec<&str> = s.splitn(4, ':').collect();
            if parts.len() != 4 {
                return false;
            }
            if parts[0] != "urn" {
                return false;
            }
            let segment_ok = |seg: &str| {
                let mut it = seg.chars();
                match it.next() {
                    Some(c) if c.is_ascii_lowercase() || c.is_ascii_digit() => {}
                    _ => return false,
                }
                it.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
            };
            if !segment_ok(parts[1]) || !segment_ok(parts[2]) {
                return false;
            }
            if parts[3].is_empty() {
                return false;
            }
            parts[3]
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | ':' | '%' | '-'))
        }

        for (i, urn) in urns.iter().enumerate() {
            let s = urn.as_str().unwrap_or("");
            assert!(
                !matches_schema_shape(s),
                "invalid fixture entry [{i}] {s:?} unexpectedly matches the schema URN regex; \
                 fixture must remain a negative case"
            );
        }
    }

    #[test]
    fn network_enforcement_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/cell-observability-network-enforcement-data.valid.json"
        );
        let expected: Value = serde_json::from_str(raw).unwrap();
        let spec = ExecutionCellSpec {
            id: "net-enforcement-demo".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = observability_network_enforcement_data_v1(
            &spec,
            "net-enforcement-demo",
            Some("run-local-001"),
            true,
            1,
            1,
            None,
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn dns_resolution_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/cell-observability-dns-resolution-data.valid.json"
        );
        let expected: Value = serde_json::from_str(raw).unwrap();
        let spec = ExecutionCellSpec {
            id: "demo-cell-dns".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let targets: &[(&str, &str, Option<u16>)] = &[
            ("203.0.113.10", "inet", Some(443)),
            ("2001:db8::1", "inet6", Some(443)),
        ];
        let data = observability_dns_resolution_data_v1(
            &spec,
            "demo-cell-dns",
            Some("run-001"),
            "api.example.com",
            "2026-04-30T12:00:00Z",
            targets,
            300,
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "keyset-demo-001",
            "kid-resolver-01",
            Some("rcpt-demo-0001"),
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn dns_target_set_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/cell-observability-dns-target-set-data.valid.json"
        );
        let expected: Value = serde_json::from_str(raw).unwrap();
        let spec = ExecutionCellSpec {
            id: "demo-cell-dns".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = observability_dns_target_set_data_v1(
            &spec,
            "demo-cell-dns",
            Some("run-001"),
            "cdn.example.com",
            "empty",
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "refresh",
            "2026-04-30T12:05:00Z",
            "keyset-demo-001",
            "kid-resolver-01",
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn dns_query_data_v1_serializes_allow_path() {
        use crate::{DnsQueryDecision, DnsQueryEvent, DnsQueryReasonCode, DnsQueryType};
        let ev = DnsQueryEvent {
            schema_version: "1.0.0".into(),
            cell_id: "demo-cell-dns".into(),
            run_id: "run-2026-05-01-001".into(),
            query_id: "q-3b58b2a4-e4bb-4f89-9c4f-2a0a2c8b6f01".into(),
            query_name: "api.example.com".into(),
            query_type: DnsQueryType::A,
            decision: DnsQueryDecision::Allow,
            reason_code: DnsQueryReasonCode::AllowedByAllowlist,
            response_rcode: Some(0),
            upstream_resolver_id: Some("resolver-do53-internal".into()),
            upstream_latency_ms: Some(4),
            response_target_count: Some(2),
            keyset_id: Some("keyset-demo-001".into()),
            issuer_kid: Some("kid-resolver-01".into()),
            policy_digest: Some(
                "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855".into(),
            ),
            correlation_id: Some("corr-demo-0001".into()),
            observed_at: "2026-05-01T12:34:56Z".into(),
        };
        let v = dns_query_data_v1(&ev).unwrap();
        assert_eq!(v["schemaVersion"], "1.0.0");
        assert_eq!(v["queryName"], "api.example.com");
        assert_eq!(v["queryType"], "A");
        assert_eq!(v["decision"], "allow");
        assert_eq!(v["reasonCode"], "allowed_by_allowlist");
        assert_eq!(v["upstreamResolverId"], "resolver-do53-internal");
        assert_eq!(v["responseTargetCount"], 2);
    }

    #[test]
    fn dns_query_data_v1_omits_optionals_on_deny_path() {
        use crate::{DnsQueryDecision, DnsQueryEvent, DnsQueryReasonCode, DnsQueryType};
        let ev = DnsQueryEvent {
            schema_version: "1.0.0".into(),
            cell_id: "demo-cell-dns".into(),
            run_id: "run-2026-05-01-001".into(),
            query_id: "q-deny-001".into(),
            query_name: "blocked.example.com".into(),
            query_type: DnsQueryType::AAAA,
            decision: DnsQueryDecision::Deny,
            reason_code: DnsQueryReasonCode::DeniedNotInAllowlist,
            response_rcode: Some(5),
            upstream_resolver_id: None,
            upstream_latency_ms: None,
            response_target_count: Some(0),
            keyset_id: None,
            issuer_kid: None,
            policy_digest: None,
            correlation_id: None,
            observed_at: "2026-05-01T12:35:00Z".into(),
        };
        let v = dns_query_data_v1(&ev).unwrap();
        let obj = v.as_object().unwrap();
        assert!(!obj.contains_key("upstreamResolverId"));
        assert!(!obj.contains_key("upstreamLatencyMs"));
        assert!(!obj.contains_key("keysetId"));
        assert!(!obj.contains_key("issuerKid"));
        assert!(!obj.contains_key("policyDigest"));
        assert!(!obj.contains_key("correlationId"));
        assert_eq!(v["decision"], "deny");
        assert_eq!(v["reasonCode"], "denied_not_in_allowlist");
        assert_eq!(v["responseRcode"], 5);
    }

    #[test]
    fn cloud_event_v1_dns_query_envelope() {
        use crate::{DnsQueryDecision, DnsQueryEvent, DnsQueryReasonCode, DnsQueryType};
        let ev = DnsQueryEvent {
            schema_version: "1.0.0".into(),
            cell_id: "c1".into(),
            run_id: "r1".into(),
            query_id: "q1".into(),
            query_name: "api.example.com".into(),
            query_type: DnsQueryType::A,
            decision: DnsQueryDecision::Allow,
            reason_code: DnsQueryReasonCode::AllowedByAllowlist,
            response_rcode: Some(0),
            upstream_resolver_id: Some("r-001".into()),
            upstream_latency_ms: Some(3),
            response_target_count: Some(1),
            keyset_id: None,
            issuer_kid: None,
            policy_digest: None,
            correlation_id: None,
            observed_at: "2026-05-01T12:34:56Z".into(),
        };
        let env =
            cloud_event_v1_dns_query("cellos-dns-proxy", "2026-05-01T12:34:56Z", &ev).unwrap();
        assert_eq!(env.specversion, "1.0");
        assert_eq!(env.ty, "dev.cellos.events.cell.observability.v1.dns_query");
        assert_eq!(env.source, "cellos-dns-proxy");
        assert_eq!(env.datacontenttype.as_deref(), Some("application/json"));
        assert!(env.data.is_some());
    }

    #[test]
    fn qtype_mapping_covers_phase1_set() {
        use crate::{qtype_to_dns_query_type, DnsQueryType};
        assert_eq!(qtype_to_dns_query_type(1), Some(DnsQueryType::A));
        assert_eq!(qtype_to_dns_query_type(2), Some(DnsQueryType::NS));
        assert_eq!(qtype_to_dns_query_type(5), Some(DnsQueryType::CNAME));
        assert_eq!(qtype_to_dns_query_type(12), Some(DnsQueryType::PTR));
        assert_eq!(qtype_to_dns_query_type(15), Some(DnsQueryType::MX));
        assert_eq!(qtype_to_dns_query_type(16), Some(DnsQueryType::TXT));
        assert_eq!(qtype_to_dns_query_type(28), Some(DnsQueryType::AAAA));
        assert_eq!(qtype_to_dns_query_type(33), Some(DnsQueryType::SRV));
        assert_eq!(qtype_to_dns_query_type(64), Some(DnsQueryType::SVCB));
        assert_eq!(qtype_to_dns_query_type(65), Some(DnsQueryType::HTTPS));
        // Unmapped types fall outside the allowlist set.
        assert_eq!(qtype_to_dns_query_type(0), None);
        assert_eq!(qtype_to_dns_query_type(99), None);
        assert_eq!(qtype_to_dns_query_type(255), None); // ANY
    }

    #[test]
    fn l7_egress_decision_matches_example_shape() {
        let raw = include_str!(
            "../../../contracts/examples/cell-observability-l7-egress-decision-data.valid.json"
        );
        let expected: Value = serde_json::from_str(raw).unwrap();
        let spec = ExecutionCellSpec {
            id: "demo-cell-dns".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = observability_l7_egress_decision_data_v1(
            &spec,
            "demo-cell-dns",
            Some("run-001"),
            "l7-demo-0002",
            "deny",
            "blocked.example.com",
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "keyset-demo-001",
            "kid-l7-01",
            "deny_default",
            Some("authority.egressRules.default"),
            None, // streamId omitted on the SNI/HTTP path; Phase 3g.1 only populates for h2.
        )
        .unwrap();
        assert_eq!(data, expected);
    }

    #[test]
    fn l7_egress_decision_with_stream_id_emits_field() {
        let spec = ExecutionCellSpec {
            id: "demo-cell-dns".into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        };
        let data = observability_l7_egress_decision_data_v1(
            &spec,
            "demo-cell-dns",
            Some("run-001"),
            "l7-demo-0003",
            "deny",
            "evil.example.com",
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
            "keyset-demo-001",
            "kid-l7-01",
            "l7_h2_authority_allowlist_miss",
            None,
            Some(3), // h2 stream id
        )
        .unwrap();
        assert_eq!(data["streamId"], serde_json::json!(3));
    }

    // ── Tranche-1 seam-freeze G1 + G2 provenance/correlation tests ───────────

    fn _seam_g1_g2_minimal_spec(id: &str) -> ExecutionCellSpec {
        ExecutionCellSpec {
            id: id.into(),
            correlation: None,
            ingress: None,
            environment: None,
            placement: None,
            policy: None,
            identity: None,
            run: None,
            authority: Default::default(),
            lifetime: Lifetime { ttl_seconds: 60 },
            export: None,
            telemetry: None,
        }
    }

    #[test]
    fn seam_g2_identity_revoked_includes_provenance_when_set() {
        // G2 — provenance.parent on revoke event.
        let mut spec = _seam_g1_g2_minimal_spec("seam-g2-revoke");
        spec.identity = Some(WorkloadIdentity {
            kind: WorkloadIdentityKind::FederatedOidc,
            provider: "github-actions".into(),
            audience: "sts.amazonaws.com".into(),
            subject: None,
            ttl_seconds: Some(900),
            secret_ref: "AWS_WEB_IDENTITY".into(),
        });
        let identity = spec.identity.as_ref().unwrap();
        let prov = Provenance {
            parent: "urn:cellos:event:00000000-0000-0000-0000-00000000abcd".into(),
            parent_type: "dev.cellos.events.cell.lifecycle.v1.started".into(),
        };
        let data = identity_revoked_data_v1(
            &spec,
            "cell-seam-g2",
            Some("run-seam-g2"),
            identity,
            Some("teardown"),
            Some(&prov),
        )
        .unwrap();
        assert_eq!(
            data["provenance"]["parent"],
            "urn:cellos:event:00000000-0000-0000-0000-00000000abcd"
        );
        assert_eq!(
            data["provenance"]["parentType"],
            "dev.cellos.events.cell.lifecycle.v1.started"
        );
    }

    #[test]
    fn seam_g2_identity_revoked_omits_provenance_when_none() {
        // Backward-compat: producers without a parent reference must not
        // emit a provenance key at all.
        let mut spec = _seam_g1_g2_minimal_spec("seam-g2-revoke-no-prov");
        spec.identity = Some(WorkloadIdentity {
            kind: WorkloadIdentityKind::FederatedOidc,
            provider: "github-actions".into(),
            audience: "sts.amazonaws.com".into(),
            subject: None,
            ttl_seconds: Some(900),
            secret_ref: "AWS_WEB_IDENTITY".into(),
        });
        let identity = spec.identity.as_ref().unwrap();
        let data =
            identity_revoked_data_v1(&spec, "cell-x", None, identity, Some("teardown"), None)
                .unwrap();
        assert!(!data.as_object().unwrap().contains_key("provenance"));
    }

    #[test]
    fn seam_g2_export_completed_v2_includes_provenance_when_set() {
        // G2 — provenance.parent on export receipt completed event.
        let spec = _seam_g1_g2_minimal_spec("seam-g2-export");
        let receipt = ExportReceipt {
            target_kind: ExportReceiptTargetKind::Local,
            target_name: None,
            destination: "/tmp/out/run-1/artifact.json".into(),
            bytes_written: 42,
        };
        let prov = Provenance {
            parent: "urn:cellos:event:11111111-1111-1111-1111-111111111111".into(),
            parent_type: "dev.cellos.events.cell.lifecycle.v1.started".into(),
        };
        let data = export_completed_data_v2(
            &spec,
            "cell-export",
            Some("run-export"),
            "artifact",
            &receipt,
            Some(&prov),
        )
        .unwrap();
        assert_eq!(
            data["provenance"]["parent"],
            "urn:cellos:event:11111111-1111-1111-1111-111111111111"
        );
        assert_eq!(
            data["provenance"]["parentType"],
            "dev.cellos.events.cell.lifecycle.v1.started"
        );
    }

    #[test]
    fn seam_g2_export_failed_v2_includes_provenance_when_set() {
        // G2 — provenance.parent on export receipt failed event.
        let spec = _seam_g1_g2_minimal_spec("seam-g2-export-failed");
        let prov = Provenance {
            parent: "urn:cellos:event:22222222-2222-2222-2222-222222222222".into(),
            parent_type: "dev.cellos.events.cell.lifecycle.v1.started".into(),
        };
        let data = export_failed_data_v2(
            &spec,
            "cell-fail",
            Some("run-fail"),
            "artifact",
            ExportReceiptTargetKind::S3,
            Some("bucket"),
            Some("s3://bucket/artifact"),
            "denied by policy",
            Some(&prov),
        )
        .unwrap();
        assert_eq!(
            data["provenance"]["parent"],
            "urn:cellos:event:22222222-2222-2222-2222-222222222222"
        );
        assert_eq!(data["reason"], "denied by policy");
    }

    #[test]
    fn seam_g1_correlation_id_propagates_when_present_in_spec() {
        // G1 — when the broker (or operator) supplies correlation_id,
        // every event that mirrors `Correlation` carries it through into
        // its `data.correlation.correlationId` payload field. We exercise
        // the property on a representative subset of events that share the
        // same `if let Some(c) = &spec.correlation { ... }` pattern.
        let mut spec = _seam_g1_g2_minimal_spec("seam-g1-corr");
        spec.correlation = Some(Correlation {
            platform: None,
            external_run_id: None,
            external_job_id: None,
            tenant_id: None,
            labels: None,
            correlation_id: Some("urn:tsafe:corr:01J".into()),
        });
        spec.identity = Some(WorkloadIdentity {
            kind: WorkloadIdentityKind::FederatedOidc,
            provider: "github-actions".into(),
            audience: "sts.amazonaws.com".into(),
            subject: None,
            ttl_seconds: Some(900),
            secret_ref: "AWS_WEB_IDENTITY".into(),
        });
        let identity = spec.identity.as_ref().unwrap();

        // identity_revoked
        let data =
            identity_revoked_data_v1(&spec, "cell-1", Some("r"), identity, Some("teardown"), None)
                .unwrap();
        assert_eq!(
            data["correlation"]["correlationId"], "urn:tsafe:corr:01J",
            "identity.revoked must mirror correlationId from spec"
        );

        // export_completed v2
        let receipt = ExportReceipt {
            target_kind: ExportReceiptTargetKind::Local,
            target_name: None,
            destination: "/tmp/x".into(),
            bytes_written: 1,
        };
        let data = export_completed_data_v2(&spec, "c", Some("r"), "art", &receipt, None).unwrap();
        assert_eq!(
            data["correlation"]["correlationId"], "urn:tsafe:corr:01J",
            "export.v2.completed must mirror correlationId from spec"
        );

        // export_failed v2
        let data = export_failed_data_v2(
            &spec,
            "c",
            Some("r"),
            "art",
            ExportReceiptTargetKind::Local,
            None,
            None,
            "boom",
            None,
        )
        .unwrap();
        assert_eq!(
            data["correlation"]["correlationId"], "urn:tsafe:corr:01J",
            "export.v2.failed must mirror correlationId from spec"
        );

        // command_completed
        let data =
            command_completed_data_v1(&spec, "c", Some("r"), &["echo".to_string()], 0, 5, None)
                .unwrap();
        assert_eq!(
            data["correlation"]["correlationId"], "urn:tsafe:corr:01J",
            "command.completed must mirror correlationId from spec"
        );

        // compliance_summary
        let data = compliance_summary_data_v1(&spec, "c", Some("r"), Some(0)).unwrap();
        assert_eq!(
            data["correlation"]["correlationId"], "urn:tsafe:corr:01J",
            "compliance.summary must mirror correlationId from spec"
        );
    }

    // ---------------------------------------------------------------------
    // Seam-freeze G3 (P0-6): SubjectUrn validation tests.
    //
    // Every literal `urn:...` / `cell:...` string in this section is for a
    // negative or positive test case and is intentionally allow-listed by
    // `scripts/audit/subject-urn-check.sh` (which excludes `events.rs`).
    // ---------------------------------------------------------------------

    #[test]
    fn subject_urn_accepts_canonical_cell_form() {
        // Positive case: the canonical CellOS cell subject shape.
        let urn = SubjectUrn::parse("urn:cellos:cell:abc-123").expect("must parse");
        assert_eq!(urn.as_str(), "urn:cellos:cell:abc-123");
    }

    #[test]
    fn subject_urn_accepts_id_with_internal_colons() {
        // Forward-compat: <id> may carry colons (e.g. nested identifiers).
        // Validation only constrains tool/kind charset, not <id>.
        let urn = SubjectUrn::parse("urn:cellos:event:abc:01j").expect("must parse");
        assert_eq!(urn.as_str(), "urn:cellos:event:abc:01j");
    }

    #[test]
    fn subject_urn_rejects_when_no_urn_scheme() {
        // Negative #1: legacy `cell:<id>` shape — no `urn:` scheme.
        let err = SubjectUrn::parse("cell:abc-123").unwrap_err();
        assert_eq!(err, SubjectUrnError::MissingUrnScheme);
    }

    #[test]
    fn subject_urn_rejects_three_segment_form() {
        // Negative #2: only three colon-separated segments.
        let err = SubjectUrn::parse("urn:cellos:cell").unwrap_err();
        assert_eq!(err, SubjectUrnError::TooFewSegments);
    }

    #[test]
    fn subject_urn_rejects_empty_id() {
        // Negative #3: trailing empty `<id>`.
        let err = SubjectUrn::parse("urn:cellos:cell:").unwrap_err();
        assert_eq!(err, SubjectUrnError::EmptySegment);
    }

    #[test]
    fn subject_urn_rejects_uppercase_tool_or_kind() {
        // Negative #4: charset [a-z0-9-] excludes uppercase.
        let err = SubjectUrn::parse("urn:CellOS:cell:abc-123").unwrap_err();
        assert_eq!(err, SubjectUrnError::InvalidToolOrKindCharset);
    }

    #[test]
    fn subject_urn_rejects_embedded_whitespace() {
        // Negative #5: any whitespace (including in <id>) is rejected.
        let err = SubjectUrn::parse("urn:cellos:cell:abc 123").unwrap_err();
        assert_eq!(err, SubjectUrnError::ControlOrWhitespace);
    }

    #[test]
    fn subject_urn_rejects_empty_tool_segment() {
        // Defense: `urn::kind:id` (empty <tool>) is empty, not charset.
        let err = SubjectUrn::parse("urn::cell:abc-123").unwrap_err();
        assert_eq!(err, SubjectUrnError::EmptySegment);
    }

    #[test]
    fn cell_subject_urn_helper_round_trips() {
        // Helper must produce a SubjectUrn that parses identically.
        let urn = cell_subject_urn("cell-host-7").expect("helper must accept ASCII id");
        assert_eq!(urn.as_str(), "urn:cellos:cell:cell-host-7");
        // And re-parsing the same string must succeed without normalization.
        let reparsed = SubjectUrn::parse(urn.as_str()).expect("must reparse");
        assert_eq!(reparsed, urn);
    }

    #[test]
    fn cell_subject_urn_helper_rejects_empty_id() {
        let err = cell_subject_urn("").unwrap_err();
        assert_eq!(err, SubjectUrnError::EmptySegment);
    }

    // ── Formation lifecycle events ────────────────────────────────────────

    #[test]
    fn formation_data_v1_shape_happy_path() {
        let data = formation_data_v1("f-123", "demo-formation", 3, &[], None);
        assert_eq!(data["formationId"], json!("f-123"));
        assert_eq!(data["formationName"], json!("demo-formation"));
        assert_eq!(data["cellCount"], json!(3));
        assert_eq!(data["failedCellIds"], json!([] as [String; 0]));
        // `reason` is omitted (not null) when None — auditors check key presence.
        let obj = data.as_object().unwrap();
        assert!(!obj.contains_key("reason"));
    }

    #[test]
    fn formation_data_v1_shape_degraded_path_includes_failed_cells_and_reason() {
        let failed = vec!["cell-a".to_string(), "cell-b".to_string()];
        let data = formation_data_v1(
            "f-123",
            "demo-formation",
            5,
            &failed,
            Some("2/5 cells exited non-zero"),
        );
        assert_eq!(data["failedCellIds"], json!(failed));
        assert_eq!(data["reason"], json!("2/5 cells exited non-zero"));
    }

    #[test]
    fn formation_created_envelope_carries_correct_urn() {
        let ev = cloud_event_v1_formation_created(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            2,
            &[],
            None,
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.created");
        assert_eq!(ev.specversion, "1.0");
        assert_eq!(ev.source, "cellos-supervisor");
        assert!(ev.data.is_some());
    }

    #[test]
    fn formation_launching_envelope_carries_correct_urn() {
        let ev = cloud_event_v1_formation_launching(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            2,
            &[],
            None,
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.launching");
    }

    #[test]
    fn formation_running_envelope_carries_correct_urn() {
        let ev = cloud_event_v1_formation_running(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            2,
            &[],
            None,
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.running");
    }

    #[test]
    fn formation_degraded_envelope_carries_correct_urn_and_failed_cells() {
        let failed = vec!["cell-a".to_string()];
        let ev = cloud_event_v1_formation_degraded(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            3,
            &failed,
            Some("one cell exited 1"),
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.degraded");
        let data = ev.data.unwrap();
        assert_eq!(data["failedCellIds"], json!(failed));
        assert_eq!(data["reason"], json!("one cell exited 1"));
    }

    #[test]
    fn formation_completed_envelope_carries_correct_urn() {
        let ev = cloud_event_v1_formation_completed(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            2,
            &[],
            None,
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.completed");
    }

    #[test]
    fn formation_failed_envelope_carries_correct_urn_and_reason() {
        let failed = vec!["cell-a".to_string(), "cell-b".to_string()];
        let ev = cloud_event_v1_formation_failed(
            "cellos-supervisor",
            "2026-05-16T00:00:00Z",
            "f-1",
            "demo",
            2,
            &failed,
            Some("all cells exited non-zero"),
        );
        assert_eq!(ev.ty, "dev.cellos.events.cell.formation.v1.failed");
        let data = ev.data.unwrap();
        assert_eq!(data["failedCellIds"], json!(failed));
        assert_eq!(data["reason"], json!("all cells exited non-zero"));
    }

    #[test]
    fn formation_type_constants_match_envelope_urns() {
        assert_eq!(
            FORMATION_CREATED_TYPE,
            "dev.cellos.events.cell.formation.v1.created"
        );
        assert_eq!(
            FORMATION_LAUNCHING_TYPE,
            "dev.cellos.events.cell.formation.v1.launching"
        );
        assert_eq!(
            FORMATION_RUNNING_TYPE,
            "dev.cellos.events.cell.formation.v1.running"
        );
        assert_eq!(
            FORMATION_DEGRADED_TYPE,
            "dev.cellos.events.cell.formation.v1.degraded"
        );
        assert_eq!(
            FORMATION_COMPLETED_TYPE,
            "dev.cellos.events.cell.formation.v1.completed"
        );
        assert_eq!(
            FORMATION_FAILED_TYPE,
            "dev.cellos.events.cell.formation.v1.failed"
        );
    }
}