axon-frontend 1.37.0

AXON compiler frontend — lexer, parser, AST, epistemic type system, type checker, IR generator. Zero runtime dependencies. v1.3.0 lowers requires_capabilities into IRAxonEndpoint (the PCC capability-containment property, §Fase 51.x.1). v1.2.0 added PRIMITIVE_REGISTRY — closed catalogue of every named language construct (45 entries) with PrimitiveInfo / DocStatus / CoverageSummary types + helpers. v1.1.0 introduced session-types + multiparty projection. See https://github.com/Bemarking/axon-lang.
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
//! AXON IR node definitions — direct port of axon/compiler/ir_nodes.py.
//!
//! All nodes serialize to JSON matching the Python IR output format exactly.

#![allow(dead_code)]

use serde::Serialize;

// ── Program root ─────────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
pub struct IRProgram {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub personas: Vec<IRPersona>,
    pub contexts: Vec<IRContext>,
    pub anchors: Vec<IRAnchor>,
    pub tools: Vec<IRToolSpec>,
    pub memories: Vec<IRMemory>,
    pub types: Vec<IRType>,
    pub flows: Vec<IRFlow>,
    pub runs: Vec<IRRun>,
    pub imports: Vec<IRImport>,
    pub agents: Vec<IRAgent>,
    pub shields: Vec<IRShield>,
    /// §Fase 71.a — temporal execution-window guards.
    pub windows: Vec<IRWindow>,
    pub daemons: Vec<IRDaemon>,
    pub ots_specs: Vec<IROts>,
    pub pix_specs: Vec<IRPix>,
    /// §Fase 62.0 — audit-chain (`ledger`) declarations. Distinct from
    /// `pix_specs` (the retrieval navigator); a ledger binds a hash-linked
    /// recorder to an audited surface.
    pub ledger_specs: Vec<IRLedger>,
    pub corpus_specs: Vec<IRCorpus>,
    pub psyche_specs: Vec<IRPsyche>,
    pub mandate_specs: Vec<IRMandate>,
    pub lambda_data_specs: Vec<IRLambdaData>,
    pub compute_specs: Vec<IRCompute>,
    pub axonstore_specs: Vec<IRAxonStore>,
    pub endpoints: Vec<IRAxonEndpoint>,
    /// §Fase 53 — closed-catalog extension declarations (compiled).
    /// `#[serde(skip)]` so the field is NOT emitted into the IR JSON —
    /// this keeps the static IR-JSON drift-gate fixtures green without
    /// regenerating them (same established pattern as `dataspace_specs`).
    /// The in-memory field feeds the §53.c type-checker + §53.d PCC (both
    /// read `&IRProgram`); soundness invariant #1 holds via SOURCE
    /// re-derivation — both the prover and the verifier read the
    /// source-derived IR, which carries the extensions. §53.x hardening
    /// (optional): un-skip + regenerate fixtures + bind extensions into
    /// the PCC `artifact_digest` (today the digest omits them; the
    /// witness still binds them by re-derivation). Deterministically
    /// sorted by `name` at the end of IR generation (§53.b founder
    /// refinement B) so multi-file declaration order can never perturb
    /// the proof-bundle hash.
    #[serde(skip)]
    pub extensions: Vec<IRExtension>,
    /// Local-only: IRDataspace specs are computed during IR generation so
    /// the cost estimator and inspectors can reach them, but Python's
    /// reference IRProgram does not serialise this field. Hidden from JSON
    /// output for byte-identical parity (§8.2.h.1).
    #[serde(skip)]
    pub dataspace_specs: Vec<IRDataspace>,
    /// §λ-L-E Fase 1 — I/O cognitivo primitives (compiled).
    pub resources: Vec<IRResource>,
    pub fabrics: Vec<IRFabric>,
    pub manifests: Vec<IRManifest>,
    pub observations: Vec<IRObserve>,
    /// §λ-L-E Fase 1 (Free Monad root) — populated when the program
    /// declares manifests/observes. `None` ⇒ serialises as `null`
    /// (matches Python when the field is `None`).
    pub intention_tree: Option<IRIntentionTree>,
    /// §λ-L-E Fase 3 — Control cognitivo primitives (compiled).
    pub reconciles: Vec<IRReconcile>,
    pub leases: Vec<IRLease>,
    pub ensembles: Vec<IREnsemble>,
    /// §λ-L-E Fase 4 — Topology + Session (compiled).
    pub sessions: Vec<IRSession>,
    pub topologies: Vec<IRTopology>,
    /// §λ-L-E Fase 5 — Immune system (compiled).
    pub immunes: Vec<IRImmune>,
    pub reflexes: Vec<IRReflex>,
    pub heals: Vec<IRHeal>,
    /// §λ-L-E Fase 9 — UI cognitiva declarativa (compiled).
    pub components: Vec<IRComponent>,
    pub views: Vec<IRView>,
    /// §λ-L-E Fase 13 — Mobile typed channels (compiled).
    pub channels: Vec<IRChannel>,
    /// §Fase 41.b — typed WebSocket transports (compiled). Each carries its
    /// referenced `session` protocol + the credit-window backpressure so
    /// axon-rs can realise the typed endpoint over a `tokio` WebSocket.
    pub sockets: Vec<IRSocket>,
    /// §Fase 51.c.2 — Pauli-sum observable declarations (compiled). Each carries
    /// its real-coefficient × Pauli-string terms so axon-rs can build the
    /// Hermitian measurement operator `M = Σ cₖ Pₖ` a `quant` block measures
    /// against. `#[serde(skip)]` (like `extensions` / `dataspace_specs`) so the
    /// static IR-JSON drift fixtures stay green; the in-memory field feeds the
    /// §51.c.2 checker + the §51.d/e runtime. The checker resolves
    /// `quant(observable: …)` against the AST symbol table, not this field.
    #[serde(skip)]
    pub observables: Vec<IRObservable>,
    /// §Fase 69.a — Advantage-Witness declarations. `skip_serializing_if = empty`
    /// keeps a witness-less program's IR JSON byte-identical (zero IR-SHA drift,
    /// the §52/§67 pattern); when present it rides the IR to the enterprise
    /// deploy/runtime evaluator (§69.b+).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub witnesses: Vec<IRWitness>,
    /// §Fase 80.b — outbound vendor connections (compiled). Each carries its
    /// axon-facing session binding (`protocol`/`role`), the per-tenant config
    /// keys (`resolve`/`secret`), the auth handshake, the total wire↔session
    /// projection (`map`) and the reconnect/overflow policies, so axon-rs can
    /// dial + transcode without vendor-specific code. `skip_serializing_if =
    /// empty` keeps an upstream-less program's IR JSON byte-identical (zero
    /// IR-SHA drift — the standing §76.d discipline).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub upstreams: Vec<IRUpstream>,
    /// §Fase 83.a — named, referenced browser-origin policies. `skip_serializing_if
    /// = empty` keeps a cors-less program's IR JSON byte-identical (zero IR-SHA
    /// drift — the standing §76.d discipline).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cors_policies: Vec<IRCors>,
    /// §Fase 85.b — named, referenced result-memoization policies. Same
    /// `skip_serializing_if = empty` IR-SHA discipline as `cors_policies`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub caches: Vec<IRCache>,
    /// §Fase 87.a — long-horizon autonomous research primitives (compiled). Each
    /// carries its domain, cognition params, memory binding, compute budget and
    /// mandates so the enterprise engine (§87.h+) can drive the active-inference
    /// loop. Same `skip_serializing_if = empty` IR-SHA discipline as `caches`
    /// (a savant-less program's IR JSON stays byte-identical — zero drift).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub savants: Vec<IRSavant>,
    /// §Fase 87.d — dynamic tool-synthesis policies (compiled). Same
    /// `skip_serializing_if = empty` IR-SHA discipline as `savants`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub synths: Vec<IRSynth>,
    /// §Fase 88.a — authorization-scope policies (compiled). Same
    /// `skip_serializing_if = empty` IR-SHA discipline as `synths`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub scopes: Vec<IRScope>,
    /// §Fase 23 — algebraic effect declarations (compiled).
    /// Each declared effect persists into IR so axon-rs can build the
    /// per-effect operation table at startup. The CPS state graph for
    /// perform/handle sites lives inline within IRFlow.steps (each
    /// IRPerform / IRHandlerFrame carries its assigned state_id /
    /// frame_id).
    ///
    /// This Rust port mirrors the Python-side
    /// `IRProgram.effects: tuple[IREffectDeclaration, ...]` field so
    /// the byte-identical structural-parity gate stays green. The Rust
    /// frontend (axon-frontend) does not yet emit Fase 23 IR itself —
    /// the field exists to preserve serialization shape; the actual
    /// algebraic-effects compiler lives on the Python side, and the
    /// Rust runtime (axon-rs/src/effects/) consumes the JSON IR
    /// emitted by Python.
    pub effects: Vec<IREffectDeclaration>,
}

impl IRProgram {
    pub fn new() -> Self {
        IRProgram {
            node_type: "program",
            source_line: 1,
            source_column: 1,
            personas: Vec::new(),
            contexts: Vec::new(),
            anchors: Vec::new(),
            tools: Vec::new(),
            memories: Vec::new(),
            types: Vec::new(),
            flows: Vec::new(),
            runs: Vec::new(),
            imports: Vec::new(),
            agents: Vec::new(),
            shields: Vec::new(),
            windows: Vec::new(),
            daemons: Vec::new(),
            ots_specs: Vec::new(),
            pix_specs: Vec::new(),
            ledger_specs: Vec::new(),
            corpus_specs: Vec::new(),
            psyche_specs: Vec::new(),
            mandate_specs: Vec::new(),
            lambda_data_specs: Vec::new(),
            compute_specs: Vec::new(),
            axonstore_specs: Vec::new(),
            endpoints: Vec::new(),
            extensions: Vec::new(),
            dataspace_specs: Vec::new(),
            resources: Vec::new(),
            fabrics: Vec::new(),
            manifests: Vec::new(),
            observations: Vec::new(),
            intention_tree: None,
            reconciles: Vec::new(),
            leases: Vec::new(),
            ensembles: Vec::new(),
            sessions: Vec::new(),
            topologies: Vec::new(),
            immunes: Vec::new(),
            reflexes: Vec::new(),
            heals: Vec::new(),
            components: Vec::new(),
            views: Vec::new(),
            channels: Vec::new(),
            sockets: Vec::new(),
            observables: Vec::new(),
            witnesses: Vec::new(),
            upstreams: Vec::new(),
            cors_policies: Vec::new(),
            caches: Vec::new(),
            savants: Vec::new(),
            synths: Vec::new(),
            scopes: Vec::new(),
            effects: Vec::new(),
        }
    }
}

/// §Fase 51.d.2 — IR for the `yield <expr>` measurement point.
#[derive(Debug, Clone, Serialize)]
pub struct IRYield {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub value_expr: String,
    pub value_kind: String,
}

/// §Fase 51.c.2 — one term `cₖ · Pₖ` of a Pauli-sum observable (compiled).
#[derive(Debug, Clone, Serialize)]
pub struct IRPauliTerm {
    pub coefficient: f64,
    pub pauli: String,
}

/// §Fase 51.c.2 — IR for a Pauli-sum observable `M = Σ cₖ Pₖ`.
#[derive(Debug, Clone, Serialize)]
pub struct IRObservable {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub qubits: Option<i64>,
    pub terms: Vec<IRPauliTerm>,
}

/// §Fase 69.a — IR for an Advantage Witness. The deploy/runtime evaluator reads
/// `metric` + `threshold` + `baseline`, computes the metric over `data`, and
/// emits the verdict; a `holds == false` verdict is the honest fail-closed
/// signal (`axon-W007`/`W008`). `claim`/`data` are references resolved per domain.
#[derive(Debug, Clone, Serialize)]
pub struct IRWitness {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub claim: String,
    pub baseline: String,
    pub metric: String,
    pub threshold: f64,
    pub data: String,
}

// ── §Fase 23 — Algebraic effect declarations ─────────────────────────────────
//
// Mirror of Python's `IREffectDeclaration` and `IREffectOperation`
// dataclasses. The Rust frontend (axon-frontend) does not yet emit
// Fase 23 IR itself — these structs exist so the byte-identical
// structural-parity gate stays green when Python emits an empty
// `effects: []` field. The actual algebraic-effects compiler lives on
// the Python side; the Rust runtime (axon-rs/src/effects/) consumes
// the JSON IR via its own deserialize structs.

#[derive(Debug, Serialize, Default)]
pub struct IREffectDeclaration {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub operations: Vec<IREffectOperation>,
}

impl IREffectDeclaration {
    pub fn new() -> Self {
        Self {
            node_type: "effect_declaration",
            source_line: 0,
            source_column: 0,
            name: String::new(),
            operations: Vec::new(),
        }
    }
}

#[derive(Debug, Serialize, Default)]
pub struct IREffectOperation {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub type_parameters: Vec<String>,
    pub parameter_names: Vec<String>,
    pub parameter_types: Vec<String>,
    pub return_type: String,
}

impl IREffectOperation {
    pub fn new() -> Self {
        Self {
            node_type: "effect_operation",
            source_line: 0,
            source_column: 0,
            name: String::new(),
            type_parameters: Vec::new(),
            parameter_names: Vec::new(),
            parameter_types: Vec::new(),
            return_type: String::new(),
        }
    }
}

// ── §λ-L-E Fase 1 — IRResource ──────────────────────────────────────────────

/// Compiled resource declaration — linear/affine infrastructure token.
///
/// Python counterpart: `axon.compiler.ir_nodes.IRResource`.
#[derive(Debug, Clone, Serialize)]
pub struct IRResource {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub kind: String,
    pub endpoint: String,
    pub capacity: Option<i64>,
    pub lifetime: String,             // linear | affine | persistent
    pub certainty_floor: Option<f64>, // c ∈ [0.0, 1.0]
    pub shield_ref: String,
}

impl IRResource {
    pub fn new(name: String, line: u32, column: u32) -> Self {
        IRResource {
            node_type: "resource",
            source_line: line,
            source_column: column,
            name,
            kind: String::new(),
            endpoint: String::new(),
            capacity: None,
            lifetime: "affine".to_string(),
            certainty_floor: None,
            shield_ref: String::new(),
        }
    }
}

// ── §λ-L-E Fase 1 — IRFabric ────────────────────────────────────────────────

/// Compiled fabric declaration — topological substrate for resources.
#[derive(Debug, Clone, Serialize)]
pub struct IRFabric {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub provider: String,
    pub region: String,
    pub zones: Option<i64>,
    pub ephemeral: Option<bool>,
    pub shield_ref: String,
}

// ── §λ-L-E Fase 1 — IRManifest ──────────────────────────────────────────────

/// Compiled manifest declaration — declarative belief about desired shape.
#[derive(Debug, Clone, Serialize)]
pub struct IRManifest {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub resources: Vec<String>,
    pub fabric_ref: String,
    pub region: String,
    pub zones: Option<i64>,
    pub compliance: Vec<String>,
}

// ── §λ-L-E Fase 1 — IRObserve ───────────────────────────────────────────────

// ── §λ-L-E Fase 1 — IRIntentionTree (Free Monad root) ──────────────────────

/// A single operation node in the intention tree.
///
/// Operations are heterogeneous IR nodes (manifests, observes) that the
/// Handler layer (Fase 2) interprets via CPS. The enum is `#[serde(untagged)]`
/// so JSON output is just the inner struct — matching Python's `asdict`
/// behaviour on a polymorphic `tuple[IRNode, ...]`.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum IRIntentionOperation {
    Manifest(IRManifest),
    Observe(IRObserve),
}

/// The Free Monad F_Σ(X) — a pure description of I/O intentions. Flat in
/// Fase 1; nested continuations arrive with handlers + reconcile loops.
#[derive(Debug, Clone, Serialize)]
pub struct IRIntentionTree {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub operations: Vec<IRIntentionOperation>,
}

/// Compiled observe declaration — quorum-gated observation with lag τ.
#[derive(Debug, Clone, Serialize)]
pub struct IRObserve {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub target: String,
    pub sources: Vec<String>,
    pub quorum: Option<i64>,
    pub timeout: String,
    pub on_partition: String,
    pub certainty_floor: Option<f64>,
}

// ── §λ-L-E Fase 3 — IRReconcile / IRLease / IREnsemble ──────────────────────

/// Compiled reconcile declaration — free-energy minimizing control loop.
#[derive(Debug, Clone, Serialize)]
pub struct IRReconcile {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub observe_ref: String,
    pub threshold: Option<f64>,
    pub tolerance: Option<f64>,
    pub on_drift: String,
    pub shield_ref: String,
    pub mandate_ref: String,
    pub max_retries: i64,
}

/// Compiled lease declaration — τ-decaying affine resource token.
#[derive(Debug, Clone, Serialize)]
pub struct IRLease {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub resource_ref: String,
    pub duration: String,
    pub acquire: String,
    pub on_expire: String,
}

/// Compiled ensemble declaration — Byzantine quorum aggregator.
#[derive(Debug, Clone, Serialize)]
pub struct IREnsemble {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub observations: Vec<String>,
    pub quorum: Option<i64>,
    pub aggregation: String,
    pub certainty_mode: String,
}

// ── §λ-L-E Fase 4 — IRSession / IRTopology ──────────────────────────────────

/// One operation in a compiled session protocol
/// (send / receive / loop / end / select / branch — §Fase 41.b adds the choices).
#[derive(Debug, Clone, Serialize)]
pub struct IRSessionStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub op: String,
    pub message_type: String,
    /// §Fase 41.b — labelled branches (only for `op == "select" | "branch"`;
    /// §Fase 79.b reuses them for `op == "interrupt"`: `body` + `handler` arms).
    #[serde(skip_serializing_if = "Vec::is_empty", default)]
    pub branches: Vec<IRSessionBranch>,
    /// §Fase 79.b — `op == "interrupt"` only: the handler's signal binder
    /// (`... as <sig> ...`). Skip-if-empty ⇒ zero IR-SHA drift for every
    /// non-interrupt step (the §76.d/§77.a additive-only discipline).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub binder: String,
    /// §Fase 79.b — `op == "interrupt"` only: the block declares a `resumable`
    /// handler. Skip-if-false ⇒ byte-identical IR for every other op.
    #[serde(skip_serializing_if = "std::ops::Not::not", default)]
    pub resumable: bool,
}

/// §Fase 41.b — one labelled arm of a compiled `select`/`branch` choice.
#[derive(Debug, Clone, Serialize)]
pub struct IRSessionBranch {
    pub node_type: &'static str,
    pub label: String,
    pub steps: Vec<IRSessionStep>,
}

/// A role's name and its ordered protocol steps.
#[derive(Debug, Clone, Serialize)]
pub struct IRSessionRole {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub steps: Vec<IRSessionStep>,
}

/// Compiled binary session — exactly two dual roles (verified at type-check).
#[derive(Debug, Clone, Serialize)]
pub struct IRSession {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub roles: Vec<IRSessionRole>,
}

/// Directed, session-typed edge between two topology nodes.
#[derive(Debug, Clone, Serialize)]
pub struct IRTopologyEdge {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub source: String,
    pub target: String,
    pub session_ref: String,
}

/// Compiled topology — typed graph over Axon entities.
#[derive(Debug, Clone, Serialize)]
pub struct IRTopology {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub nodes: Vec<String>,
    pub edges: Vec<IRTopologyEdge>,
}

// ── §λ-L-E Fase 5 — IRImmune / IRReflex / IRHeal ────────────────────────────

/// Compiled immune sensor — KL+FEP anomaly detector descriptor.
#[derive(Debug, Clone, Serialize)]
pub struct IRImmune {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub watch: Vec<String>,
    pub sensitivity: Option<f64>,
    pub baseline: String,
    pub window: i64,
    pub scope: String,
    pub tau: String,
    pub decay: String,
}

/// Compiled reflex — deterministic O(1) motor response descriptor.
#[derive(Debug, Clone, Serialize)]
pub struct IRReflex {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub trigger: String,
    pub on_level: String,
    pub action: String,
    pub scope: String,
    pub sla: String,
}

/// Compiled heal — Linear-Logic one-shot patch kernel descriptor.
#[derive(Debug, Clone, Serialize)]
pub struct IRHeal {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub source: String,
    pub on_level: String,
    pub mode: String,
    pub scope: String,
    pub review_sla: String,
    pub shield_ref: String,
    pub max_patches: i64,
}

// ── §λ-L-E Fase 9 — IRComponent / IRView ────────────────────────────────────

/// Compiled UI component — reusable fragment over a typed data source.
#[derive(Debug, Clone, Serialize)]
pub struct IRComponent {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub renders: String,
    pub via_shield: String,
    pub on_interact: String,
    pub render_hint: String,
}

/// Compiled UI view — top-level screen composing declared components.
#[derive(Debug, Clone, Serialize)]
pub struct IRView {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub title: String,
    pub components: Vec<String>,
    pub route: String,
}

// ── Import ───────────────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
pub struct IRImport {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub module_path: Vec<String>,
    pub names: Vec<String>,
}

// ── Persona ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRPersona {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub domain: Vec<String>,
    pub tone: String,
    pub confidence_threshold: Option<f64>,
    pub cite_sources: Option<bool>,
    pub refuse_if: Vec<String>,
    pub language: String,
    pub description: String,
}

// ── Context ──────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRContext {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub memory_scope: String,
    pub language: String,
    pub depth: String,
    pub max_tokens: Option<i64>,
    pub temperature: Option<f64>,
    pub cite_sources: Option<bool>,
}

// ── Anchor ───────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRAnchor {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub description: String,
    pub require: String,
    pub reject: Vec<String>,
    pub enforce: String,
    pub confidence_floor: Option<f64>,
    pub unknown_response: String,
    pub on_violation: String,
    pub on_violation_target: String,
}

// ── Tool ─────────────────────────────────────────────────────────────────────

/// §Fase 58.c — one typed parameter of a tool's input schema (the IR mirror of
/// the AST `Parameter`). `type_name` is the flattened BASE type string
/// (`String`, `List<String>`); optionality (`T?`) is carried in `optional`, so
/// `required` is derivable with no parallel bool (§58 D1, single source of
/// truth). Lossless round-trip is gated in §58.i.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct IRToolParam {
    pub name: String,
    pub type_name: String,
    pub optional: bool,
}

/// §Fase 58.c — one bound keyword argument of a `use Tool(k = v, …)` call (the
/// IR mirror of `UseArgs::Named`). `value` is an expression string (the
/// frontend has no structured `Expr`). The runtime (§58.e) assembles these into
/// the structured JSON request body.
#[derive(Debug, Clone, Serialize, PartialEq)]
pub struct IRNamedArg {
    pub name: String,
    pub value: String,
    /// §Fase 60 — `"literal"` or `"reference"` (classified by `parse_let_atom`).
    /// A `"reference"` value (a bare identifier or `Step.output`) is resolved at
    /// runtime against the bindings (flow-param / `let` / step output), like a
    /// `let` reference — instead of being passed as the literal name (the pre-60
    /// bug). `"literal"` values keep `${…}` interpolation + typed coercion.
    pub value_kind: String,
}

#[derive(Debug, Serialize)]
pub struct IRToolSpec {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub provider: String,
    pub max_results: Option<i64>,
    pub filter_expr: String,
    pub timeout: String,
    pub runtime: String,
    pub sandbox: Option<bool>,
    pub input_schema: Vec<String>,
    pub output_schema: String,
    /// §Fase 58.c — the tool's typed INPUT SCHEMA (D1). Distinct from the §32
    /// `input_schema`/`output_schema` validation hints (those say HOW to
    /// validate raw output: JSON/number/…); these are the caller↔tool TYPE
    /// contract the type-checker enforces (§58.d) and the runtime binds
    /// structured args against (§58.e). Empty for a schema-less tool (D5).
    pub parameters: Vec<IRToolParam>,
    /// §Fase 58.c — the tool's declared OUTPUT type (D8), so `${Step.output}`
    /// is typed. `None` when undeclared. Single source of truth (lives here,
    /// not denormalised onto each call site).
    pub output_type: Option<String>,
    pub effect_row: Vec<String>,
    /// §Fase 84.b — Remote Hands. All three fields are `skip_serializing_if`
    /// so a program using none of them serialises **byte-identically** to the
    /// pre-§84 IR (the §76.d IR-SHA / additive-only gate — no drift for the
    /// entire existing corpus).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub risk: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub argv: Vec<String>,
    /// §Fase 85.b — the cache-policy reference (a declared `cache` name, or the
    /// `none` opt-out sentinel). Empty ⇒ module-default-governed. Elided when
    /// empty (IR-SHA stable for cache-less programs).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub cache: String,
}

// ── Memory ───────────────────────────────────────────────────────────────────

#[derive(Debug, Serialize)]
pub struct IRMemory {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub store: String,
    pub backend: String,
    pub retrieval: String,
    pub decay: String,
}

// ── Type ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRTypeField {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub type_name: String,
    pub generic_param: String,
    pub optional: bool,
}

#[derive(Debug, Serialize)]
pub struct IRType {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub fields: Vec<IRTypeField>,
    pub range_min: Option<f64>,
    pub range_max: Option<f64>,
    pub where_expression: String,
    /// §ESK Fase 6.1 — κ regulatory class.
    pub compliance: Vec<String>,
}

// ── Flow ─────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRParameter {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub type_name: String,
    pub generic_param: String,
    pub optional: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDataEdge {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub source_step: String,
    pub target_step: String,
    pub type_name: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub persona_ref: String,
    pub given: String,
    pub ask: String,
    pub use_tool: Option<serde_json::Value>,
    pub probe: Option<serde_json::Value>,
    pub reason: Option<serde_json::Value>,
    pub weave: Option<serde_json::Value>,
    pub output_type: String,
    pub confidence_floor: Option<f64>,
    pub navigate_ref: String,
    pub apply_ref: String,
    /// §Fase 68.b — the step's model-capability requirement (context window in
    /// tokens). `skip_serializing_if = Option::is_none` keeps every pre-§68 step's
    /// IR JSON byte-identical (no IR-SHA drift, D68.4); a legacy IR deserialises
    /// to `None` → the §68.c resolver picks the backend default exactly as today.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub requires_context: Option<u32>,
    pub body: Vec<serde_json::Value>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRFlow {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub parameters: Vec<IRParameter>,
    pub return_type_name: String,
    pub return_type_generic: String,
    pub return_type_optional: bool,
    pub steps: Vec<IRFlowNode>,
    pub edges: Vec<IRDataEdge>,
    pub execution_levels: Vec<Vec<String>>,
}

// ── Run ──────────────────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRRun {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub flow_name: String,
    pub arguments: Vec<String>,
    pub persona_name: String,
    pub context_name: String,
    pub anchor_names: Vec<String>,
    pub on_failure: String,
    pub on_failure_params: Vec<Vec<String>>,
    pub output_to: String,
    pub effort: String,
    pub resolved_flow: Option<IRFlow>,
    pub resolved_persona: Option<IRPersona>,
    pub resolved_context: Option<IRContext>,
    pub resolved_anchors: Vec<IRAnchor>,
}

// ── Lambda Data (ΛD) — Epistemic State Vectors ─────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRLambdaData {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub ontology: String,             // T — ontological type
    pub certainty: f64,               // c ∈ [0,1]
    pub temporal_frame_start: String, // τ_start
    pub temporal_frame_end: String,   // τ_end
    pub provenance: String,           // ρ — EntityRef origin
    pub derivation: String,           // δ ∈ Δ
}

#[derive(Debug, Clone, Serialize)]
pub struct IRLambdaDataApply {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub lambda_data_name: String, // reference to declared ΛD
    pub target: String,           // expression being bound
    pub output_type: String,      // result type after binding
}

// ── Flow step IR nodes ──────────────────────────────────────────────────────

/// Polymorphic flow body node — serializes via #[serde(untagged)] so each
/// variant emits its inner struct's JSON (with its own `node_type` field).
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum IRFlowNode {
    Step(IRStep),
    Probe(IRProbe),
    Reason(IRReasonStep),
    Validate(IRValidateStep),
    Refine(IRRefineStep),
    Weave(IRWeaveStep),
    UseTool(IRUseToolStep),
    Remember(IRRememberStep),
    Recall(IRRecallStep),
    Conditional(IRConditional),
    ForIn(IRForIn),
    Let(IRLetBinding),
    Return(IRReturnStep),
    /// Fase 19.e — exit the enclosing for-in body. Payload-free;
    /// the runner translates it into a sentinel that terminates the
    /// loop. Parser scope check guarantees this only appears inside
    /// a for-in body.
    Break(IRBreakStep),
    /// Fase 19.e — skip to the next iteration of the enclosing for-in
    /// body. Same shape as Break — payload-free, sentinel-driven at
    /// runtime.
    Continue(IRContinueStep),
    LambdaDataApply(IRLambdaDataApply),
    Par(IRParallelBlock),
    Hibernate(IRHibernateStep),
    Deliberate(IRDeliberateBlock),
    Consensus(IRConsensusBlock),
    Forge(IRForgeBlock),
    Focus(IRFocusStep),
    Associate(IRAssociateStep),
    Aggregate(IRAggregateStep),
    Explore(IRExploreStep),
    Ingest(IRIngestStep),
    ShieldApply(IRShieldApplyStep),
    Stream(IRStreamBlock),
    Navigate(IRNavigateStep),
    Drill(IRDrillStep),
    Trail(IRTrailStep),
    Corroborate(IRCorroborateStep),
    OtsApply(IROtsApplyStep),
    MandateApply(IRMandateApplyStep),
    ComputeApply(IRComputeApplyStep),
    Listen(IRListenStep),
    DaemonStep(IRDaemonStepNode),
    /// §λ-L-E Fase 13 — π-calc output prefix (Chan-Output / Chan-Mobility).
    Emit(IREmit),
    /// §λ-L-E Fase 13 — capability extrusion (Publish-Ext).
    Publish(IRPublish),
    /// §λ-L-E Fase 13 — dual of publish (typed handle import).
    Discover(IRDiscover),
    Persist(IRPersistStep),
    Retrieve(IRRetrieveStep),
    Mutate(IRMutateStep),
    Purge(IRPurgeStep),
    Transact(IRTransactBlock),
    /// §Fase 88.a — the `warden` adversarial security-analysis block.
    Warden(IRWarden),
    /// §Fase 51.a — the `quant` cognitive block (Hilbert-space projection).
    Quant(IRQuant),
    /// §Fase 51.d.2 — the `yield` measurement point inside a `quant` block.
    Yield(IRYield),
    /// §Fase 52.c — `run <Flow>(args)` flow-step: invoke a declared flow from a
    /// body (a daemon listen handler). Reuses [`IRRun`] (the top-level run IR).
    Run(IRRun),
}

#[derive(Debug, Clone, Serialize)]
pub struct IRProbe {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRReasonStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub strategy: String,
    pub target: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRValidateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub rule: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRRefineStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub strategy: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRWeaveStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub sources: Vec<String>,
    pub target: String,
    pub format_type: String,
    pub priority: Vec<String>,
    pub style: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRUseToolStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub tool_name: String,
    pub argument: String,
    /// §Fase 58.c — the bound keyword args of `use Tool(k = v, …)` (W1: the
    /// structured args survive to the IR, no longer collapsed to one opaque
    /// string). Empty for the legacy single-`on <arg>` form (`argument`
    /// carries that, D5).
    pub named_args: Vec<IRNamedArg>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRRememberStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub expression: String,
    pub memory_target: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRRecallStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub query: String,
    pub memory_source: String,
}

/// §Fase 70.a — the lowered form of a pure expression (`Expr`). Carried in the
/// IR for conditions the legacy `(condition, op, value)` triple cannot express.
/// Operators are canonical lowercase strings so the JSON is stable + readable;
/// the runtime evaluator (§70.f) matches on them. Externally-tagged by `kind`.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum IRExpr {
    /// A typed literal.
    Lit { lit: IRExprLit },
    /// A reference to a binding / dotted path.
    Ref { path: String },
    /// Unary op — `op ∈ {neg, not}`.
    Unary { op: String, operand: Box<IRExpr> },
    /// Binary op — `op ∈ {add,sub,mul,div,mod,eq,ne,lt,le,gt,ge,and,or}`.
    Binary {
        op: String,
        lhs: Box<IRExpr>,
        rhs: Box<IRExpr>,
    },
    /// §Fase 70.c — a closed-catalog builtin call. `args[0]` is the receiver.
    /// `builtin ∈ {length,count,is_empty,is_null,contains,starts_with,ends_with}`.
    Call {
        builtin: String,
        args: Vec<IRExpr>,
    },
    /// §Fase 70.d — field access on a non-reference base (the JSONB seam).
    Field {
        base: Box<IRExpr>,
        field: String,
    },
    /// §Fase 70.d — index access `base[index]`.
    Index {
        base: Box<IRExpr>,
        index: Box<IRExpr>,
    },
}

/// §Fase 70.a — a literal inside an [`IRExpr`].
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "ty", rename_all = "snake_case")]
pub enum IRExprLit {
    Int { value: i64 },
    Float { value: f64 },
    Bool { value: bool },
    Str { value: String },
}

#[derive(Debug, Clone, Serialize)]
pub struct IRConditional {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub condition: String,
    pub comparison_op: String,
    pub comparison_value: String,
    pub then_body: Vec<IRFlowNode>,
    pub else_body: Vec<IRFlowNode>,
    pub conditions: Vec<(String, String, String)>,
    pub conjunctor: String,
    /// §Fase 70.a — the lowered expression form, present only for conditions
    /// the legacy triple cannot express. `skip_serializing_if` keeps the IR
    /// JSON (and its SHA) byte-identical for every pre-§70 program.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cond: Option<IRExpr>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRForIn {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub variable: String,
    pub iterable: String,
    pub body: Vec<IRFlowNode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRLetBinding {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub value: String,
    /// Fase 17.a — preserves parser tokenization intent.
    /// One of "literal" | "reference" | "expression".
    pub value_kind: String,
    /// §Fase 70.f — the lowered expression form of the value, present only for
    /// `value_kind == "expression"`. The runtime evaluates it instead of
    /// treating the value string as an opaque literal. `skip_serializing_if`
    /// keeps the IR byte-identical for every literal / reference let.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub value_ast: Option<IRExpr>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRReturnStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub value_expr: String,
}

/// Fase 19.e — `break` keyword IR node. Payload-free (the runner
/// raises a sentinel; no value is carried). Mirrors Python's
/// ``IRBreak`` (axon/compiler/ir_nodes.py).
#[derive(Debug, Clone, Serialize)]
pub struct IRBreakStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

/// Fase 19.e — `continue` keyword IR node. Same shape as
/// ``IRBreakStep``; the runner uses a different sentinel type to
/// distinguish loop-exit (break) from iteration-skip (continue).
#[derive(Debug, Clone, Serialize)]
pub struct IRContinueStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRParallelBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    /// §Fase 65 — the concurrent branches lowered from the AST `par { … }`.
    /// Each branch is a flow-IR body run concurrently by the dispatcher's
    /// `run_branches_concurrently`. `skip_serializing_if = "Vec::is_empty"` so a
    /// payload-free / empty `par` serializes byte-identically to the pre-§65
    /// shape (D5 back-compat); a `par` with real branches carries them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub branches: Vec<Vec<IRFlowNode>>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRHibernateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub event_name: String,
    pub timeout: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDeliberateBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRConsensusBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

/// §Fase 86 — the compiled Directed Creative Synthesis block. This IS the
/// "structured IR metadata that the runtime executes as an orchestrated
/// pipeline" the README always claimed — pre-§86 it carried only a source
/// location. New fields are `skip_serializing_if`-elided so a program with no
/// `forge` stays IR-SHA stable.
#[derive(Debug, Clone, Serialize, Default)]
pub struct IRForgeBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub name: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub seed: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub output_type: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub mode: String,
    #[serde(default, skip_serializing_if = "is_default_novelty")]
    pub novelty: f64,
    #[serde(default, skip_serializing_if = "is_one_i64")]
    pub depth: i64,
    #[serde(default, skip_serializing_if = "is_one_i64")]
    pub branches: i64,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub constraints_ref: String,
}

fn is_default_novelty(v: &f64) -> bool {
    (*v - 0.5).abs() < f64::EPSILON
}
fn is_one_i64(v: &i64) -> bool {
    *v == 1
}

#[derive(Debug, Clone, Serialize)]
pub struct IRFocusStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub expression: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRAssociateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub left: String,
    pub right: String,
    pub using_field: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRAggregateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub group_by: Vec<String>,
    pub alias: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRExploreStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub limit: Option<i64>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRIngestStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub source: String,
    pub target: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRShieldApplyStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub shield_name: String,
    pub target: String,
    pub output_type: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRStreamBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRNavigateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub pix_ref: String,
    pub corpus_ref: String,
    pub query: String,
    pub trail_enabled: bool,
    pub output_name: String,
    /// §Fase 63.B — MDN corpus-graph navigation: the seed document (`from:`).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub seed: String,
    /// §Fase 63.B — MDN navigation budget (`budget:` = max documents).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<i64>,
    /// §Fase 66 (Q2) — column-scope filter for a `corpus from axonstore`. A raw
    /// filter expr threaded to `read_all_store_rows` → `stream_retrieve` for
    /// BOTH the documents and edges stores, so the sourced MDN graph is scoped
    /// to a sub-tenant column (`where: "tenant_id == '${tenant_id}'"`). The
    /// §37.d filter compiler resolves `${name}` → `$N` bind params (injection-
    /// safe). Empty = no column filter (axon-tenant RLS scope only).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub where_expr: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDrillStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub pix_ref: String,
    pub subtree_path: String,
    pub query: String,
    pub output_name: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRTrailStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub navigate_ref: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRCorroborateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub navigate_ref: String,
    pub output_name: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IROtsApplyStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub ots_name: String,
    pub target: String,
    pub output_type: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRMandateApplyStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub mandate_name: String,
    pub target: String,
    pub output_type: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRComputeApplyStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub compute_name: String,
    pub arguments: Vec<String>,
    pub output_name: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRListenStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub channel: String,
    /// §λ-L-E Fase 13 D4 — true ⇒ `channel` is a declared
    /// `IRChannel` ref; false ⇒ legacy string topic.
    pub channel_is_ref: bool,
    pub event_alias: String,
    /// §Fase 52.a — the handler body's lowered flow-steps, executed per event /
    /// scheduled tick by the §52.c runtime. `skip_serializing_if` keeps a
    /// bodyless `listen`'s JSON byte-identical to the pre-§52.a shape (D8).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub body: Vec<IRFlowNode>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDaemonStepNode {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub daemon_ref: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRPersistStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub store_name: String,
    /// §Fase 35.o — declared `{ col: value }` field block (value
    /// expressions kept raw; interpolated at runtime). Empty ⇒ the
    /// runtime writes the flow's user bindings (v1.30.0 fallback).
    pub fields: Vec<(String, String)>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRRetrieveStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub store_name: String,
    pub where_expr: String,
    pub alias: String,
    /// §Fase 67.b — `order_by:` clause (raw `"col [asc|desc], …"`).
    /// `skip_serializing_if` empty so a store that doesn't order never
    /// perturbs the serialized IR bytes (the §52 brief-#33 /
    /// [[feedback-boot-hydrate-self-heal]] no-drift discipline).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub order_by: String,
    /// §Fase 67.b — `limit:` clause (raw `"100"` or `"${max}"`).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub limit_expr: String,
    /// §Fase 76.d — `aggregate:` clause (raw, closed catalog: `count` /
    /// `sum(col)` / `avg(col)` / `min(col)` / `max(col)`).
    /// `skip_serializing_if` empty so a non-aggregating retrieve never
    /// perturbs the serialized IR bytes (the same §67.b no-drift
    /// discipline — zero IR-SHA drift for existing programs).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub aggregate: String,
    /// §Fase 76.d — `group_by:` clause (raw `"col, col2"`).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub group_by: String,
    /// §Fase 85.b — `cache:` reference (a declared `cache` name). Empty ⇒
    /// uncached. Elided when empty (IR-SHA stable for cache-less retrieves).
    #[serde(skip_serializing_if = "String::is_empty", default)]
    pub cache: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRMutateStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub store_name: String,
    pub where_expr: String,
    /// §Fase 35.p — declared `{ col: value }` SET assignments (value
    /// expressions kept raw; interpolated at runtime). Empty ⇒ the
    /// runtime writes the flow's user bindings (v1.31.0 fallback).
    pub fields: Vec<(String, String)>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRPurgeStep {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub store_name: String,
    pub where_expr: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRTransactBlock {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
}

/// §Fase 88.a — IR for the `warden` adversarial-analysis block. Carries the
/// target, the mandatory `scope_ref`, and the recursively-lowered body so the
/// enterprise engine (§88.f) can drive the analysis and §88.c can enforce the
/// authorization discipline.
#[derive(Debug, Clone, Serialize)]
pub struct IRWarden {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub target: String,
    pub scope_ref: String,
    /// Nested flow-body IR (recursively lowered).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub body: Vec<IRFlowNode>,
}

/// §Fase 88.a — IR for a `scope` authorization-policy declaration.
#[derive(Debug, Clone, Serialize)]
pub struct IRScope {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub targets: Vec<String>,
    pub depth: String,
    pub approver: String,
}

/// §Fase 51.a — IR for the `quant` cognitive block (Hilbert-space projection).
/// Mirrors `ast::QuantBlock`. Optional attributes serialize only when present
/// (`skip_serializing_if`) so a bare `quant {}` lowers to a minimal node and
/// the JSON stays diff-stable. The body lowers recursively, like `par` branches.
#[derive(Debug, Clone, Serialize)]
pub struct IRQuant {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    /// Encoding scheme surface spelling (`amplitude` | `angle`); `None` = default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub encoding: Option<String>,
    /// Referenced `Observable` (Pauli-sum) name; `None` if unspecified.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub observable: Option<String>,
    /// Register width n; `None` = inferred.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub qubits: Option<i64>,
    /// Variational circuit depth L; `None` = backend default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub depth: Option<i64>,
    /// Projected-kernel bandwidth γ (D7); `None` = backend default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub bandwidth: Option<f64>,
    /// §Fase 69.c — data re-uploading layers L (`None`/`1` = no re-uploading).
    /// `skip_serializing_if` keeps a non-re-uploading block's IR byte-identical.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reupload: Option<i64>,
    /// Algebraic-effect backend tag (`quant_sim` | `qpu_native`).
    pub effect: String,
    /// Nested flow-body IR (recursively lowered).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub body: Vec<IRFlowNode>,
}

// ── Tier 2 IR nodes ─────────────────────────────────────────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct IRAgent {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub goal: String,
    pub tools: Vec<String>,
    pub memory_ref: String,
    pub strategy: String,
    pub on_stuck: String,
    pub shield_ref: String,
    pub max_iterations: Option<i64>,
    pub max_tokens: Option<i64>,
    pub max_time: String,
    pub max_cost: Option<f64>,
}

/// §Fase 71.a — the lowered temporal execution-window guard. The runtime
/// (§71.b) evaluates `is_in_window(now, tz, allow)`; the daemon binding +
/// coalesced defer ledger are §71.c/d.
#[derive(Debug, Clone, Serialize)]
pub struct IRWindow {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub timezone: String,
    pub allow: Vec<IRWindowSpan>,
    /// §Fase 71.e — excluded dates (holidays): ISO `YYYY-MM-DD` literals. A tick
    /// whose local date is in this set is OUTSIDE regardless of the hour spans.
    /// `skip_serializing_if` keeps a holiday-less window's JSON byte-identical.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub exclude: Vec<String>,
    pub on_outside: String,
}

/// §Fase 71.a — one allowed day/hour span.
#[derive(Debug, Clone, Serialize)]
pub struct IRWindowSpan {
    pub day_start: String,
    pub day_end: String,
    pub hour_start: i64,
    pub hour_end: i64,
}

/// §Fase 72.a — the `budget { … }` linear-effect rate limit lowered to IR. Each
/// quota gates a declared tool's dispatch on a renewable token bucket (the §72.b
/// `RateLease`); `on_exhausted` is the exhaustion policy.
#[derive(Debug, Clone, Serialize)]
pub struct IRBudget {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub quotas: Vec<IRBudgetQuota>,
    /// `block` (fail-closed) | `defer` (reschedule via the §71 defer ledger) |
    /// `shed` (skip the call). An omitted policy lowers to `block` (the safe
    /// fail-closed default).
    pub on_exhausted: String,
}

/// §Fase 72.a — one quota: `<kind>: <limit> per <period> on Tool(<effect>)`.
#[derive(Debug, Clone, Serialize)]
pub struct IRBudgetQuota {
    /// `rate` (renewable bucket) | `max` (windowed hard cap, no intra-window refill).
    pub kind: String,
    /// Token allowance per period (> 0, validated by `axon-T831`).
    pub limit: i64,
    /// `second` | `minute` | `hour` | `day` (closed catalog, `axon-T832`).
    pub period: String,
    /// The declared tool this quota governs (`on Tool(X)`; resolved by `axon-T830`).
    pub effect: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRShield {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub scan: Vec<String>,
    pub strategy: String,
    pub on_breach: String,
    pub severity: String,
    pub quarantine: String,
    /// §8.2.h.3 — Python emits concrete 0, not null. AST keeps `Option<i64>`
    /// so the parser can distinguish "not set"; IR lowering collapses.
    pub max_retries: i64,
    pub confidence_threshold: f64,
    pub allow_tools: Vec<String>,
    pub deny_tools: Vec<String>,
    pub sandbox: bool,
    pub redact: Vec<String>,
    pub log: String,
    pub deflect_message: String,
    // `taint` exists on `ShieldDefinition` (AST) but Python's reference
    // IRShield doesn't emit it. Hidden from JSON output for §8.2.h parity.
    #[serde(skip)]
    pub taint: String,
    /// §ESK Fase 6.1 — covered regulatory classes for this shield.
    pub compliance: Vec<String>,
    /// §Fase 77.a — egress signing algorithm (`hmac_sha256`; empty = the
    /// shield does not sign). Elided from JSON when empty so every pre-§77
    /// program's IR stays byte-identical (zero IR-SHA drift).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub sign: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRPix {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub source: String,
    pub depth: Option<i64>,
    pub branching: Option<i64>,
    pub model: String,
}

/// §Fase 62.0 — the audit-chain (`ledger`) IR node. Same shape as [`IRPix`]
/// but a DISTINCT node (`node_type: "ledger"`): a ledger binds a hash-linked
/// recorder to an audited surface (`source`), retaining `depth` rows under a
/// `branching`-factor Merkle tree, hashed with `model`. Kept separate from
/// `IRPix` so the navigator and the audit chain never alias on the wire.
#[derive(Debug, Clone, Serialize)]
pub struct IRLedger {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub source: String,
    pub depth: Option<i64>,
    pub branching: Option<i64>,
    pub model: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRPsyche {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub dimensions: Vec<String>,
    pub manifold_noise: Option<f64>,
    pub manifold_momentum: Option<f64>,
    pub safety_constraints: Vec<String>,
    pub quantum_enabled: Option<bool>,
    pub inference_mode: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRCorpus {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub documents: Vec<String>,
    /// §Fase 63.A — typed weighted edges. Non-empty ⇒ this corpus is an MDN
    /// graph `C = (D, R, τ, ω, σ)`; the runtime builds an `mdn::Corpus` from it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub relations: Vec<IRCorpusRelation>,
    /// §Fase 63.C — `adaptive: true` enables the memory endofunctor on this
    /// corpus's navigations.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub adaptive: bool,
    pub mcp_server: String,
    pub mcp_resource_uri: String,
    /// §Fase 64.A — when present, this is a DYNAMIC store-sourced MDN graph: the
    /// documents and typed edges are rows in two declared `axonstore`s and the
    /// runtime builds the `mdn::Corpus` from the live rows at navigate-time
    /// (per-tenant, growing). Absent ⇒ the static §63 corpus (byte-identical IR).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub store_source: Option<IRCorpusStoreSource>,
}

/// §Fase 63.A — a lowered MDN corpus-graph edge `(from, to, τ, ω)`.
#[derive(Debug, Clone, Serialize)]
pub struct IRCorpusRelation {
    pub etype: String,
    pub from: String,
    pub to: String,
    pub weight: f64,
}

/// §Fase 64.A — the lowered store-mapping of a dynamic, `axonstore`-sourced MDN
/// corpus graph. `doc_store(doc_id, doc_title)` maps rows → nodes;
/// `edge_store(edge_from, edge_to, edge_type, edge_weight)` maps rows → typed
/// weighted edges. The runtime (§64.B) reads these stores tenant-scoped at
/// navigate-time to build the `mdn::Corpus`.
#[derive(Debug, Clone, Serialize)]
pub struct IRCorpusStoreSource {
    pub doc_store: String,
    pub doc_id: String,
    pub doc_title: String,
    pub edge_store: String,
    pub edge_from: String,
    pub edge_to: String,
    pub edge_type: String,
    pub edge_weight: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDataspace {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IROts {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub teleology: String,
    pub homotopy_search: String,
    pub loss_function: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRMandate {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub constraint: String,
    pub kp: Option<f64>,
    pub ki: Option<f64>,
    pub kd: Option<f64>,
    pub tolerance: Option<f64>,
    pub max_steps: Option<i64>,
    pub on_violation: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRCompute {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub shield_ref: String,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRDaemon {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub goal: String,
    pub tools: Vec<String>,
    pub memory_ref: String,
    pub strategy: String,
    pub on_stuck: String,
    pub shield_ref: String,
    /// §Fase 71.c — the `window:` temporal binding (a `window` primitive name).
    /// Empty ⇒ no temporal guard; `skip_serializing_if` keeps a windowless
    /// daemon's JSON byte-identical (D8 zero-drift).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub window_ref: String,
    /// §Fase 72.a — the `budget { … }` linear-effect rate limit. `None` ⇒ no
    /// budget; `skip_serializing_if` keeps a budgetless daemon's JSON
    /// byte-identical (D8 zero-drift).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<IRBudget>,
    pub max_tokens: Option<i64>,
    pub max_time: String,
    pub max_cost: Option<f64>,
    /// §Fase 52.a — the daemon's `listen` listeners (channel + alias + handler
    /// body). Pre-§52.a these were DROPPED at lowering (the IR daemon carried no
    /// listeners at all); now they survive so the §52.c runtime can mount + run
    /// them and the §52.d enterprise supervisor can extract them per-tenant.
    /// `skip_serializing_if` keeps a listenerless daemon's JSON unchanged (D8).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub listeners: Vec<IRListenStep>,
    /// §Fase 52.d — the capability scope the daemon's runs are confined to
    /// (`requires: [cap, …]`). The enterprise supervisor mints a per-run
    /// principal scoped to exactly these. `skip_serializing_if` keeps a
    /// requires-less daemon's JSON byte-identical (D8).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_capabilities: Vec<String>,
}

// ── §Fase 87 — the long-horizon autonomous research primitive ────────────────

/// §Fase 87.a — a compiled `savant` (long-horizon autonomous research
/// primitive). A governed orchestrator: the IR carries the declared surface so
/// the enterprise active-inference engine (§87.h+) can drive the FEP loop, and
/// the §87.c checker can bind `memory` to a declared store, `budget` to a §72
/// linear budget, and the body to a §79 interruptible session.
#[derive(Debug, Clone, Serialize)]
pub struct IRSavant {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub domain: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cognition: Option<IRSavantCognition>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub memory: Option<IRSavantMemory>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub budget: Option<IRSavantBudget>,
    pub mandates: Vec<IRSavantMandate>,
}

/// §Fase 87.a — the compiled `cognition { … }` sub-block (active-inference
/// engine parameters).
#[derive(Debug, Clone, Serialize)]
pub struct IRSavantCognition {
    /// `standard | deep | hyper` — HRR dimensionality tier (validated §87.b).
    pub depth: String,
    /// Expected-Free-Energy convergence bound (`> 0`, §87.b). `None` ⇒ default.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub entropic_threshold: Option<f64>,
    /// `low | med | high` — explore/exploit balance (validated §87.b).
    pub divergence: String,
}

/// §Fase 87.a — the compiled `memory { … }` sub-block (retention binding).
#[derive(Debug, Clone, Serialize)]
pub struct IRSavantMemory {
    /// A declared `memory`/`corpus` name (resolved §87.c). Empty ⇒ ephemeral.
    pub backend: String,
    /// Whether to index the corpus as a simplicial-complex graph (topological
    /// β_n reading).
    pub corpus_graph: bool,
    /// Per-tenant tensor partitioning level (enforced by the enterprise engine).
    pub isolation_level: String,
}

/// §Fase 87.a — the compiled `budget { … }` sub-block (compute ceiling, bound to
/// a §72 linear budget in §87.c).
#[derive(Debug, Clone, Serialize)]
pub struct IRSavantBudget {
    /// Hard ceiling on FEP-loop iterations before the savant pauses.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_iterations: Option<i64>,
    /// Hard ceiling on `synth` (§87.d) tool-creation events per mandate.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_tool_synth: Option<i64>,
}

/// §Fase 87.a — a compiled `mandate <Name> { … }` sub-block (one research goal).
#[derive(Debug, Clone, Serialize)]
pub struct IRSavantMandate {
    pub name: String,
    pub objective: String,
    pub output_type: String,
}

/// §Fase 87.d — a compiled `synth` dynamic tool-synthesis policy. The IR carries
/// the safety envelope so the enterprise Extism/WASM executor (§87.j) enforces
/// it; OSS ships a deny-by-default `SynthBackend` that refuses execution.
#[derive(Debug, Clone, Serialize)]
pub struct IRSynth {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub target: String,
    pub risk: String,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub language: String,
    pub sandbox: String,
    /// `required | none`; an omitted policy lowers to `required` (fail-closed).
    pub review: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_lines: Option<i64>,
}

// ── §Fase 53 — Closed-catalog extension mechanism ────────────────────────────

/// §Fase 53 — one compiled member of an `extension`. For `effects`
/// the `name` is a provenance base; `default_confidence` is a CEILING
/// (§53.d tainted-overriding). Metadata is elided from JSON when absent
/// so the serialised shape stays minimal once the `extensions` field is
/// un-skipped alongside the Python IR mirror.
#[derive(Debug, Clone, Serialize)]
pub struct IRExtensionMember {
    pub name: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub semantics: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default_confidence: Option<f64>,
}

/// §Fase 53 — a compiled `extension` declaration. Rides in the IR (and,
/// once un-skipped, the proof bundle) so an independent PCC verifier
/// re-derives `is_known_base` against the artifact's own extensions
/// (soundness invariant #1). `category` ∈ {`effects`, `scan`} — the
/// type-checker (§53.c) enforces the closed category + no-shadowing +
/// provenance-class invariants before this IR is trusted.
#[derive(Debug, Clone, Serialize)]
pub struct IRExtension {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub category: String,
    pub members: Vec<IRExtensionMember>,
}

#[derive(Debug, Clone, Serialize)]
pub struct IRAxonStore {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub backend: String,
    pub connection: String,
    pub confidence_floor: Option<f64>,
    pub isolation: String,
    pub on_breach: String,
    /// §Fase 35.j (D11) — Pillar IV: the capability slug required to
    /// access this store (empty = no gate).
    pub capability: String,
    /// §Fase 38.b (D1) — the OPTIONAL column-schema declaration. Three
    /// closed forms (inline / manifest-ref / env-var). `None` means the
    /// 37.x runtime+deploy path applies verbatim (D5 absolute). The
    /// §38.d / §38.e type-checker proves every store reference against
    /// this when present.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub column_schema: Option<IRStoreColumnSchema>,
}

/// §Fase 38.b (D1) — IR mirror of [`crate::store_schema::StoreColumnSchema`].
/// Serializes as a tagged union: `{"form": "inline" | "manifest_ref" |
/// "env_var", …}`.
#[derive(Debug, Clone, Serialize)]
#[serde(tag = "form", rename_all = "snake_case")]
pub enum IRStoreColumnSchema {
    Inline { columns: Vec<IRStoreColumn> },
    ManifestRef { qualified_name: String },
    EnvVar { var_name: String },
}

/// §Fase 38.b (D1) — IR mirror of [`crate::store_schema::StoreColumn`].
/// The serialized `col_type` is the canonical PascalCase name (e.g.
/// `"Uuid"`, `"Int"`, `"Timestamptz"`).
#[derive(Debug, Clone, Serialize)]
pub struct IRStoreColumn {
    pub name: String,
    pub col_type: String,
    #[serde(default, skip_serializing_if = "is_false")]
    pub primary_key: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub auto_increment: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub not_null: bool,
    #[serde(default, skip_serializing_if = "is_false")]
    pub unique: bool,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub default_value: String,
    /// §Fase 38.x.c (D2, D5) — `true` iff the column is declared with
    /// `GENERATED ALWAYS AS IDENTITY` or `GENERATED BY DEFAULT AS
    /// IDENTITY`. Distinct from `auto_increment` (legacy SERIAL via
    /// `nextval(...)` default). `skip_serializing_if` keeps IR JSON
    /// byte-identical to v1.38.2 for any column where `identity = false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub identity: bool,
    /// §Fase 73.f (D1) — `true` iff the column carries the `index`
    /// declaration. Surfaced into the IR so the deployment layer (the
    /// enterprise deploy gate) SEES the index as a declared capability and
    /// can materialize it (a GIN path index for a `Json`/`Jsonb` column, a
    /// b-tree otherwise) — never a silent out-of-band DBA action.
    /// `skip_serializing_if` keeps IR JSON byte-identical for any column
    /// where `indexed = false`.
    #[serde(default, skip_serializing_if = "is_false")]
    pub indexed: bool,
    /// §Fase 73.g (D1) — the OPTIONAL `Json<T>` shape-lens struct name on a
    /// `Json`/`Jsonb` column (`payload: Json<UserEvent>` → `Some("UserEvent")`).
    /// Surfaced into the IR so the PCC `JsonShapeSoundness` proof can
    /// RE-DERIVE, from the artifact alone, that every lens shape resolves
    /// to a declared struct `type` — the §73.a/§73.e lens well-formedness
    /// made an independently-verifiable proof object. `skip_serializing_if`
    /// keeps IR JSON byte-identical for any column with no shape lens.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub json_shape: Option<String>,
}

#[inline]
fn is_false(b: &bool) -> bool {
    !*b
}

#[derive(Debug, Clone, Serialize)]
pub struct IRAxonEndpoint {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub method: String,
    pub path: String,
    pub body_type: String,
    pub execute_flow: String,
    pub output_type: String,
    pub shield_ref: String,
    /// §8.2.h.3 — Python emits concrete `0`; AST stays `Option<i64>`.
    pub retries: i64,
    pub timeout: String,
    /// §ESK Fase 6.1 — κ regulatory class on the boundary.
    pub compliance: Vec<String>,
    /// §Fase 37.y (D1) — Path parameter names extracted from the
    /// `path:` string. Mirrors `AxonEndpointDefinition.path_params`.
    /// **`skip_serializing_if = Vec::is_empty`** so a pre-v1.38.5 IR
    /// JSON snapshot (without the field) is byte-identical to a
    /// v1.38.5 IR JSON for the same endpoint — D5 backwards-compat
    /// absolute. The runtime + adopter tools that consume the IR
    /// JSON parse `path_params` as an absent key → empty Vec via
    /// serde's `default` semantics.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub path_params: Vec<String>,
    /// §Fase 37.y (D2) — Query parameters from the inline
    /// `query: { … }` block. Mirrors `AxonEndpointDefinition.query_params`
    /// using `IRTypeField` (shared with body type fields → uniform
    /// downstream tooling). **`skip_serializing_if = Vec::is_empty`**
    /// — same D5 IR-JSON byte-identity guarantee as `path_params`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub query_params: Vec<IRTypeField>,
    /// §Fase 51.x — capability scopes the request bearer must hold
    /// (the `requires: [scope.dotted]` declaration, §Fase 32.g). Mirror
    /// of `AxonEndpointDefinition.requires_capabilities`, lowered into
    /// the IR so the PCC CapabilityContainment property can prove that
    /// the stores this endpoint's flow reaches are all covered by the
    /// declared requires. **`skip_serializing_if = Vec::is_empty`** so a
    /// pre-§51.x IR-JSON snapshot (no `requires:`) stays byte-identical
    /// (D5 backwards-compat — empty key parses back to empty Vec).
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub requires_capabilities: Vec<String>,
    /// §Fase 83.a — the `cors: <Name>` reference, or `""` when absent
    /// (D83.5: no CORS headers, ever). NEW field on an EXISTING struct —
    /// `skip_serializing_if` (not `shield_ref`'s bare/always-emitted
    /// historical shape) so a cors-less endpoint's IR stays byte-identical
    /// to pre-§83 (zero IR-SHA drift — the standing §76.d discipline).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub cors_ref: String,
    /// §Fase 89.a — the explicit authorization-coverage opt-out lowered into
    /// the IR so the enterprise runtime (§89.d) and the PCC
    /// `AuthorizationCoverage` witness (§89.c) can read it. `false` (the
    /// default + the common case) elides from JSON via `is_false` so a
    /// pre-§89 IR-JSON snapshot stays byte-identical (zero IR-SHA drift —
    /// the standing §76.d discipline).
    #[serde(default, skip_serializing_if = "is_false")]
    pub public: bool,
}

// ── §λ-L-E Fase 13 — Mobile Typed Channels IR ───────────────────────────────

/// Compiled `channel Name { … }` declaration.
///
/// Direct port of `axon.compiler.ir_nodes.IRChannel`.  Lives in
/// `IRProgram.channels`; emit/publish/discover reductions embed in
/// their containing flow/listener (paper §3 + §4 — π-calc prefix
/// discipline preserved structurally, not lifted to top-level ops).
#[derive(Debug, Clone, Serialize)]
pub struct IRChannel {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub message: String, // surface spelling — Order | Channel<Order> | …
    pub qos: String,
    pub lifetime: String,
    pub persistence: String,
    pub shield_ref: String,
    /// §Fase 77.b — non-empty ⇒ some `publish <this> within <Shield>` site
    /// referenced a SIGNING shield: the channel is an EGRESS channel and
    /// its durable events are signed-deliverable to registered external
    /// subscribers under this algorithm (first publish site wins;
    /// deterministic — the catalog has one algorithm in v1). Elided from
    /// JSON when empty (zero IR-SHA drift for pre-§77 programs).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub egress_sign: String,
}

/// §Fase 41.b — compiled typed WebSocket transport. `protocol` names the
/// `session` it carries; `backpressure_credit` is the typed-resource window
/// (`null` if unspecified). axon-rs realises the endpoint over a `tokio` WS,
/// crediting/decrementing the window per §4.2 of the paper.
#[derive(Debug, Clone, Serialize)]
pub struct IRSocket {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub protocol: String,
    pub backpressure_credit: Option<i64>,
    pub reconnect: bool,
    pub legal_basis: Option<String>,
}

/// §Fase 80.b — compiled outbound vendor connection (the client dual of
/// [`IRSocket`]). `protocol`/`role` bind the axon-facing session interface;
/// `resolve`/`secret` are per-tenant config keys (never literals — T850);
/// `map` is the compile-time-total wire↔session projection (T849). Optional
/// fields elide when absent so the IR shape is purely additive.
#[derive(Debug, Clone, Serialize)]
pub struct IRUpstream {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub transport: String,
    pub protocol: String,
    pub role: String,
    pub resolve: String,
    pub secret: String,
    pub auth_kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_name: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub auth_prefix: Option<String>,
    pub map: Vec<IRUpstreamMapRule>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub reconnect: Option<IRUpstreamReconnect>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub overflow: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub backpressure_credit: Option<i64>,
    /// §80.f — the `Preset@vN` reference this declaration was expanded from
    /// (provenance for the compliance reviewer); absent for hand-written ones.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub preset: Option<String>,
}

/// §Fase 80.b — one compiled `map:` projection rule.
#[derive(Debug, Clone, Serialize)]
pub struct IRUpstreamMapRule {
    pub node_type: &'static str,
    pub direction: String,
    pub message: String,
    pub framing: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when_field: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub when_value: Option<String>,
}

/// §Fase 80.b — compiled reconnect policy (all three fields required by the
/// parser — a reconnection policy with a hole is not a policy).
#[derive(Debug, Clone, Serialize)]
pub struct IRUpstreamReconnect {
    pub backoff_ms: i64,
    pub max_attempts: i64,
    pub on_exhausted: String,
}

/// §Fase 83.a — a named, referenced browser-origin policy. Mirrors
/// `IRShield`'s field-for-field shape; consumed by `IRAxonEndpoint.cors_ref`.
/// Wildcard+credentials (T853), origin-glob shape (T854), and closed-method
/// (T855) violations are all rejected before this node is ever lowered — the
/// checker re-derives the same closed catalogs at deploy time (§83.c,
/// `CorsPolicyConsistency`), so an IR that reaches the runtime is already
/// proven consistent.
#[derive(Debug, Clone, Serialize)]
pub struct IRCors {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    pub allow_origins: Vec<String>,
    pub allow_methods: Vec<String>,
    pub allow_headers: Vec<String>,
    pub allow_credentials: bool,
    /// Duration literal (`"3600s"`) — same string-carries-the-unit
    /// convention as `axonendpoint.timeout`; the consumer (enterprise's
    /// dynamic CORS middleware) parses it into seconds at request time.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_age: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub expose_headers: Vec<String>,
}

/// §Fase 85.b — compiled `cache` policy. The checker (§85.c) re-derives the
/// same laws at the deploy gate (`CacheSoundness`), so an IR that reaches the
/// runtime is already proven sound (one default max, non-pure ⇒ finite ttl,
/// references resolve). Every optional field is `skip_serializing_if` so a
/// bundle using `cache` only pays IR bytes for what it declares, and a bundle
/// with no `cache` never emits a `caches` key (IR-SHA stable, §76.d).
#[derive(Debug, Clone, Serialize)]
pub struct IRCache {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub name: String,
    /// `"redis"` | `"in_process"`; empty ⇒ runtime default (`in_process`).
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub backend: String,
    /// Duration literal (`"10s"`) — same string-carries-the-unit convention as
    /// `cors.max_age`. `None` ⇒ cache-forever (sound only for a `pure` cache).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub ttl: Option<String>,
    /// The parameter-name subset forming the key; empty ⇒ all bound params.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub key_params: Vec<String>,
    /// `true` ⇒ auto-covers every eligible tool (at most one per module).
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub default_policy: bool,
    /// Effect classes this cache memoises; empty ⇒ `["pure"]`.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub apply_to_effects: Vec<String>,
    /// Channel names whose `emit` flushes this cache's namespace.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub invalidate_on: Vec<String>,
}

/// Compiled emit step — `c⟨v⟩.P` (Chan-Output / Chan-Mobility).
///
/// `value_is_channel = true` ⇒ resolved at lowering time as a channel
/// handle (second-order mobility, paper §3.2); the runtime dispatches
/// on this flag without re-resolving symbols.
#[derive(Debug, Clone, Serialize)]
pub struct IREmit {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub channel_ref: String,
    pub value_ref: String,
    pub value_is_channel: bool,
}

/// Compiled publish step — capability extrusion (Publish-Ext, paper §4.3).
#[derive(Debug, Clone, Serialize)]
pub struct IRPublish {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub channel_ref: String,
    pub shield_ref: String,
    /// §Fase 77.b — the referenced shield's `sign:` algorithm, RESOLVED at
    /// lowering (order-independent pre-pass over every declared shield).
    /// Non-empty ⇒ this publish is an EGRESS declaration: the channel's
    /// events are signed-deliverable to registered external subscribers.
    /// Elided from JSON when empty (zero IR-SHA drift for pre-§77 programs).
    #[serde(skip_serializing_if = "String::is_empty")]
    pub sign: String,
}

/// Compiled discover step — dual of publish.
#[derive(Debug, Clone, Serialize)]
pub struct IRDiscover {
    pub node_type: &'static str,
    pub source_line: u32,
    pub source_column: u32,
    pub capability_ref: String,
    pub alias: String,
}