earthsci-ast 0.6.0

Rust implementation of EarthSciML Abstract Syntax Tree Format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
//! Coupled system flattening per spec §4.7.5 + §4.7.6 (Rust Core tier).
//!
//! This module implements [`flatten`] — the canonical pipeline that turns an
//! [`EsmFile`] with multiple coupled components into a single [`FlattenedSystem`]
//! with dot-namespaced variables and real [`Expr`]-tree equations.
//!
//! The Rust implementation targets the **Core tier** only. It does NOT inspect
//! `dimension_mapping` declarations at all: there is no `slice` / `project` /
//! `regrid` handling, and no dimension-promotion graph is built. The removed
//! Interface construct (v0.8.0) means dimension-mapping validation via an
//! Interface does not exist, so [`FlattenError::UnsupportedMapping`],
//! [`FlattenError::UnmappedDomain`], [`FlattenError::DomainExtentMismatch`], and
//! [`DimensionPromotionRecord`] stay reserved for cross-language parity —
//! defined so a sibling binding (or a future Rust tier) can raise / populate
//! them under the same names, but never currently constructed by this crate.
//! Two of the former "reserved" variants ARE now raised for cross-binding
//! parity, independent of the removed Interface machinery:
//! [`FlattenError::DomainUnitMismatch`] is the `variable_map` `identity`-transform
//! unit check (mirrors Julia's `_check_variable_map_units`), and
//! [`FlattenError::DimensionPromotion`] is raised by the pointwise spatial lift
//! (esm-spec §10.5) when the grid loop variables cannot be determined (mirrors
//! Julia / Python `DimensionPromotionError`).
//! **Flattening does not refuse a PDE.** An undiscretized spatial operator (the
//! sugar ops `grad` / `div` / `laplacian` / `curl` / `∇`, or a spatial `D` with
//! `wrt != "t"`) flattens like any other, and the spatial axes it names are
//! recorded in [`FlattenedSystem::independent_variables`] by §4.7.6's
//! independent-variable derivation — which is precisely what decides whether a
//! downstream constructor builds an `ODESystem` or a `PDESystem`, and what makes
//! esm-spec §6.3.1's `"pde"` `system_kind` reachable. This module used to raise
//! [`FlattenError::UnloweredOperator`] here instead; that was this binding's own
//! stricter behaviour, not the format's, and it put Rust alone against Python,
//! Go, TypeScript and §4.7.6 itself.
//!
//! The `unlowered_operator` gate (esm-spec §4.2 / §9.6.8) still applies where
//! discretization is genuinely required: such an operator must be lowered to an
//! `faq` stencil by a `match` rewrite rule (an `expression_templates`
//! discretization applied during the load-time rewrite fixpoint) before it can
//! be EVALUATED, and the scalar and array simulators reject a survivor at
//! compile time with [`crate::compile_error::CompileError::UnloweredOperatorError`].
//! Once discretized, the spatial axis folds into the array index (so §4.7.6
//! derives `["t"]` again) and the system simulates natively through the array-op
//! backend — Rust runs discretized PDEs alongside Julia and Python
//! (CONFORMANCE_SPEC §5.9). A consumer that needs a discretized system up front
//! can demand one with [`reject_unlowered_operators`].

use crate::types::{
    AffectEquation, ContinuousEvent, CouplingEntry, DiscreteEvent, DiscreteEventTrigger, Domain,
    Equation, EsmFile, Expr, ExpressionNode, IndexSet, InlineValue, JoinClause, Model,
    ModelVariable, OverlapClause, RangeSpec, ReactionSystem, VariableMapTransform, VariableType,
};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::{BTreeSet, HashMap, HashSet};
use thiserror::Error;

// ============================================================================
// Error taxonomy — spec §4.7.6 conflict-detection errors
// ============================================================================

/// Errors raised by [`flatten`] and [`flatten_model`] during spec-compliant
/// coupled-system flattening.
///
/// Variant names are deliberately cross-language-compatible so Julia, Python,
/// and Rust agents can report the same failure using the same error name.
#[derive(Error, Debug)]
pub enum FlattenError {
    /// A species participates in a reaction AND has an explicit `D(X, t)`
    /// equation — the two derivative sources would need to be merged by an
    /// explicit `operator_compose`, and no such rule was supplied.
    #[error(
        "Conflicting derivative for species {species:?}: explicit D(X, t) equation and reaction participation both present without an operator_compose rule to merge them"
    )]
    ConflictingDerivative { species: Vec<String> },

    /// Dimension promotion failed.
    ///
    /// Raised by the pointwise spatial lift (esm-spec §10.5) when a lifted
    /// species' operator `makearray` carries no full-rank interior-stencil
    /// `index(...)` gather, so the grid loop variables cannot be determined and
    /// the merged reaction/operator ODE cannot be array-ified onto the operator
    /// grid. Mirrors the Julia / Python `DimensionPromotionError` raised for the
    /// same case (pointwise_lift.jl / shape_promotion.jl, flatten.py). The
    /// removed Interface / `dimension_mapping` promotion graph (v0.8.0) never
    /// raised it; this crate still builds no such graph.
    #[error("Dimension promotion failed: {message}")]
    DimensionPromotion { message: String },

    /// Two systems of differing dimensionality were coupled without an
    /// `Interface` naming their dimension mapping.
    ///
    /// **Reserved / parity-only — never currently raised.** This crate does not
    /// compare system dimensionality or resolve Interfaces, so it never
    /// constructs this variant; defined for cross-language parity.
    #[error(
        "Unmapped domain: systems {systems:?} have different dimensionality but no Interface defines their dimension mapping; candidate target domains: {candidate_targets:?}"
    )]
    UnmappedDomain {
        systems: Vec<String>,
        candidate_targets: Vec<String>,
    },

    /// The channel for a `dimension_mapping` type unsupported at the current
    /// (Rust Core) tier — e.g. `"slice"`, `"project"`, `"regrid"`.
    ///
    /// **Reserved / parity-only — never currently raised.** This crate never
    /// inspects `dimension_mapping` declarations, so it does not construct this
    /// variant; it exists so a sibling binding (or a future Rust tier) reports
    /// the same failure under the same name. An unlowered spatial operator is
    /// not rejected by [`flatten`] at all — §4.7.6 records the axis it names in
    /// [`FlattenedSystem::independent_variables`] instead.
    #[error(
        "Unsupported mapping type '{mapping_type}' at Rust Core tier (supported: broadcast, identity). Reason: {reason}"
    )]
    UnsupportedMapping {
        mapping_type: String,
        reason: String,
    },

    /// A rewrite-target operator (a spatial / right-hand-side `D`, or the
    /// optional sugar ops `grad` / `div` / `laplacian` / `curl` / `∇`) survived
    /// into a position that REQUIRES it to have been lowered to a stencil by a
    /// `match` rewrite rule (esm-spec §4.2 / §9.6.8).
    ///
    /// [`flatten`] does not raise this: a PDE is a legitimate flattened system
    /// (§4.7.6 records its spatial axes in
    /// [`FlattenedSystem::independent_variables`]). It is raised by
    /// [`reject_unlowered_operators`], the explicit check a consumer that needs
    /// a DISCRETIZED system runs; the scalar / array simulators enforce the same
    /// rule at compile time and surface the same uniform `unlowered_operator`
    /// code via [`crate::compile_error::CompileError::UnloweredOperatorError`].
    #[error(
        "unlowered_operator: rewrite-target operator '{op}' reached compilation without being \
         lowered to a stencil by a rewrite rule (esm-spec §4.2 / §9.6.8). Discretization rules \
         live in EarthSciDiscretizations, not this format."
    )]
    UnloweredOperator { op: String },

    /// A `variable_map` `identity` transform bridges two variables that carry
    /// declared, non-empty, and DIFFERING unit strings (esm-spec §10.4).
    ///
    /// Raised by the identity-transform unit check (mirrors Julia's
    /// `_check_variable_map_units`, coupling_apply.jl): an `identity` map asserts
    /// the `from` and `to` variables are the same quantity, so incompatible
    /// declared units are a modeling error. `param_to_var` / `conversion_factor`
    /// / expression transforms are exempt, and a missing or empty unit on either
    /// side is the valid (unchecked) case. `variable` names the entry's `from`.
    #[error(
        "Domain unit mismatch on variable '{variable}': source units '{source_units}' vs target units '{target_units}'"
    )]
    DomainUnitMismatch {
        variable: String,
        source_units: String,
        target_units: String,
    },

    /// Coordinate extent mismatch on a shared independent variable under the
    /// `identity` mapping.
    ///
    /// **Reserved / parity-only — never currently raised.** This crate performs
    /// no coordinate-extent checking; defined for cross-language parity.
    #[error("Domain extent mismatch on independent variable '{variable}' under identity mapping")]
    DomainExtentMismatch { variable: String },

    /// A slice coordinate lies outside the source domain.
    ///
    /// Defined for cross-language parity; only raised if `slice` is ever
    /// implemented in a future Rust tier upgrade.
    #[error(
        "Slice out of domain: slice coordinate '{coordinate}' = {value} lies outside the source domain extent"
    )]
    SliceOutOfDomain { coordinate: String, value: String },

    /// A cyclic promotion graph was detected (A promotes to B, B promotes
    /// back to A on a different axis).
    ///
    /// Defined for cross-language parity. Not raised by Core-tier Rust
    /// because no promotion graph is built.
    #[error("Cyclic promotion detected involving variables {variables:?}")]
    CyclicPromotion { variables: Vec<String> },

    /// A `variable_map` expression transform carries a `factor` — the
    /// expression spells its own arithmetic, so a separate scaling slot is a
    /// modeling error (esm-spec §10.4). Mirrors the Julia / Python
    /// construction-time rejection.
    #[error(
        "variable_map({from} -> {to}): an expression `transform` takes no `factor` (fold the scaling into the expression)"
    )]
    VariableMapFactorWithExpression { from: String, to: String },

    /// A `variable_map` expression transform does not reference the entry's
    /// `from` variable — the data-flow edge the entry declares (esm-spec
    /// §10.4).
    #[error(
        "variable_map({from} -> {to}): expression transform does not reference the entry's 'from' variable '{from}' (esm-spec §10.4)"
    )]
    VariableMapExpressionMissingFrom { from: String, to: String },

    /// A `variable_map` endpoint names nothing the flattened system carries
    /// (esm-spec §4.6, §10.4).
    ///
    /// Both halves of the entry are load-bearing and both used to fail
    /// SILENTLY. A `to` that resolves to no parameter is simply never
    /// promoted: the document declares a coupling, the target keeps its
    /// declared default, and nothing downstream can tell "applied" from
    /// "ignored". A `from` that resolves to nothing is worse — the
    /// substitution still runs, so every consumer of `to` is rewritten to a
    /// name no table binds, and the run produces NaN instead of a diagnostic.
    ///
    /// Same reasoning as [`FlattenError::CoupleMultiplicativeNoTendency`]: a
    /// coupling mis-specification must not have the one outcome that looks
    /// like success.
    ///
    /// A `from` whose owning system is a top-level `data_sources` key is
    /// exempt — such a producer is served through the forcing seam rather than
    /// as a declared variable (see [`apply_variable_map_removals`]).
    #[error(
        "variable_map({from} -> {to}): the '{side}' endpoint '{endpoint}' resolves to no variable, \
         parameter or observed in the flattened system (esm-spec §4.6, §10.4). A scoped reference \
         walks EVERY dot-separated segment, so a subsystem endpoint is spelled \
         '<Model>.<Subsystem>.<name>'."
    )]
    VariableMapUnresolvedEndpoint {
        from: String,
        to: String,
        side: String,
        endpoint: String,
    },

    /// Wrapped reaction-lowering failure.
    #[error("Reaction lowering failed: {0}")]
    Reaction(#[from] crate::reactions::DeriveError),

    /// A `coupling_import` entry failed to resolve or expand (esm-spec
    /// §10.9–§10.11). Carries the stable diagnostic `code` + message.
    #[error("{0}")]
    CouplingImport(#[from] crate::diagnostic::DiagnosticError),

    /// A `couple` connector equation carried an `lhs`/`rhs` that was absent or
    /// failed to deserialize as an [`Expr`] (esm-spec §4.7.2). Rather than
    /// silently dropping the malformed equation, flattening reports it so the
    /// coupling is not quietly degraded.
    #[error(
        "Malformed connector equation in couple({systems}): '{side}' is absent or did not deserialize as an expression"
    )]
    MalformedConnectorEquation { systems: String, side: String },

    /// A `couple` connector equation applies the `multiplicative` transform to
    /// a `to` target that has NO `D(to)` tendency in the flattened system — a
    /// parameter, an observed, an algebraic unknown, or an undefined name
    /// (esm-spec §10.3, esm-libraries-spec §4.7.2).
    ///
    /// Both sections define `multiplicative` against the target's EXISTING ODE
    /// right-hand side, so with no tendency there is nothing to multiply and
    /// the operation has no meaning. Rust used to SKIP the connector equation
    /// in that case, which is the one outcome a coupling mis-specification must
    /// not have: the document declares a coupling, the flattened system carries
    /// no trace of it, and nothing downstream can distinguish "applied" from
    /// "ignored".
    ///
    /// `additive` deliberately has no counterpart error — zero is the additive
    /// identity, so an additive term against an absent tendency simply BECOMES
    /// the tendency. There is no multiplicative identity that would do the same.
    #[error(
        "couple_multiplicative_no_tendency: couple connector 'multiplicative' transform targets \
         '{target}', which has no tendency (D({target})) to multiply (esm-spec §10.3). To scale a \
         constant parameter by a factor, use a variable_map entry with an Expression transform \
         (esm-spec §10.4) instead."
    )]
    CoupleMultiplicativeNoTendency { target: String },

    /// A [`FlattenedSystem`]'s per-equation list
    /// ([`FlattenedSystem::equation_contributions`] or
    /// [`FlattenedSystem::equation_lifted`]) has a different number of entries
    /// than [`FlattenedSystem::equations`]. The lists are paired by position, so
    /// one out of step cannot say which equation an entry belongs to.
    #[error(
        "contributions_out_of_step: FlattenedSystem.{field} has {entries} entries but the system \
         has {equations} equations (esm-libraries-spec §4.7.5). Add or remove the entry alongside \
         its equation, or clear the list to treat every right-hand side as one contribution of \
         unknown origin."
    )]
    ContributionsOutOfStep {
        field: &'static str,
        entries: usize,
        equations: usize,
    },

    /// An `operator_compose` entry merged NOTHING (esm-libraries-spec §4.7.1
    /// step 5).
    ///
    /// Such an entry is indistinguishable from one that is not there: the
    /// operator integrates a private, decoupled system from its own defaults,
    /// the other system receives no contribution at all, and the only evidence
    /// is a state count one too high. That is the one outcome a coupling
    /// mis-specification must not have, so it is refused rather than reported.
    ///
    /// An operator that genuinely contributes only states of its own — a
    /// transport operator whose single equation defines its own wind field, say
    /// — says so with `require_match: false`, and is then permitted.
    #[error(
        "operator_compose_no_merge: operator_compose({a} + {b}) merged NONE of the {authored} \
         equations '{b}' authored; no equation of '{a}' matches: {unmatched}. The entry is \
         indistinguishable from one that is not there — '{b}' would integrate decoupled from its \
         own defaults and '{a}' would receive no contribution. If '{b}' really does contribute \
         only states of its own, declare it with `require_match: false` on this entry."
    )]
    OperatorComposeNoMerge {
        a: String,
        b: String,
        authored: usize,
        unmatched: String,
    },

    /// An `operator_compose` entry declared `require_match: true` and one of
    /// `systems[1]`'s equations found no equation of `systems[0]` to land on
    /// (esm-libraries-spec §4.7.1 step 5).
    ///
    /// Step 5 otherwise preserves an unmatched equation unchanged, and a PARTIAL
    /// shortfall is only a warning by default; `require_match` is the author's
    /// opt-in to make it fatal. A PARTIAL match raises here — there is no "some
    /// is enough" reading an author could rely on: the seven-of-twelve-species
    /// case is exactly the defect the flag exists to catch.
    #[error(
        "operator_compose_require_match_unmatched: operator_compose({a} + {b}) declares \
         `require_match` and merged {merged} of {authored} equations '{b}' authored; no equation \
         of '{a}' matches: {unmatched}"
    )]
    OperatorComposeRequireMatchUnmatched {
        a: String,
        b: String,
        merged: usize,
        authored: usize,
        unmatched: String,
    },

    /// The bare-name fallback would unify two STATE variables and the document
    /// has not said which spelling survives (esm-libraries-spec §4.7.1 step 3).
    ///
    /// The fallback binds `A.x` to `B.x` on the strength of a shared local name
    /// alone. When both are states, each carries its own INITIAL CONDITION, and
    /// the merge has to delete one of them — so the choice decides which IC the
    /// flattened system integrates from. Nothing in the document expresses that
    /// choice, and picking one silently is how flipping the entry's `systems`
    /// order came to change the answer.
    ///
    /// A match where only ONE side is a state is NOT ambiguous: the other
    /// carries no initial condition, so the state is the owner and the merge
    /// renames onto it.
    #[error(
        "operator_compose_ambiguous_bare_name: operator_compose({a} + {b}) matched '{b_dep}' to \
         '{target}' on their shared local name alone, but BOTH are state variables and the merge \
         keeps only one. Each carries its own initial condition, so the choice decides which the \
         flattened system integrates from, and the document does not express it. Name the \
         surviving spelling with a `translate` entry ({{'{target}': '{b_dep}'}}), or rename one \
         of them."
    )]
    OperatorComposeAmbiguousBareName {
        a: String,
        b: String,
        b_dep: String,
        target: String,
    },

    /// A model subsystem that structurally declares itself a [`DataSource`](crate::DataSource) —
    /// it carries the discriminating `kind` / `source` keys — failed to
    /// deserialize as one. Distinguished from a nested model or a
    /// `{ "ref": … }` reference, which are legitimately not loaders and are
    /// left for the array runtime (esm-spec §4.6; RFC `pure-io-data-loaders`
    /// §4.3).
    #[error(
        "Malformed data-loader subsystem '{subsystem}' in model '{system}': carries loader keys but did not deserialize as a DataSource: {reason}"
    )]
    MalformedLoaderSubsystem {
        system: String,
        subsystem: String,
        reason: String,
    },

    /// A SURVIVING `expression_templates` registry body names a variable a
    /// coupling rule rewrote out of the flattened equations (esm-spec §9.6.4,
    /// CONFORMANCE_SPEC §5.35).
    ///
    /// Carries the stable `template_body_references_coupling_rewritten_variable`
    /// diagnostic code. Not `#[from]`: [`FlattenError::CouplingImport`] already
    /// owns the blanket conversion from [`crate::diagnostic::DiagnosticError`],
    /// and a §9.6.4 refusal is not a §10.11 import failure.
    #[error("{0}")]
    ExpressionTemplate(crate::diagnostic::DiagnosticError),

    /// The file contains no models or reaction systems to flatten.
    #[error("No models or reaction systems to flatten")]
    Empty,
}

// ============================================================================
// Output types — spec §4.7.5 FlattenedSystem shape
// ============================================================================

/// Record of a dimension promotion applied during flattening.
///
/// **Reserved / parity-only — never currently populated.** [`flatten`] always
/// emits an empty [`FlattenMetadata::dimension_promotions_applied`]: this crate
/// inspects no `dimension_mapping` declarations and rewrites no variable onto a
/// different spatial domain. The struct is defined so the metadata shape matches
/// the sibling bindings (which may populate it) and so a future Rust tier can
/// fill it without a wire-format change.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct DimensionPromotionRecord {
    pub variable: String,
    pub source_domain: String,
    pub target_domain: String,
    /// `"broadcast"` | `"identity"` (parity value set). Never recorded in
    /// practice — see the struct-level note.
    pub mapping_type: String,
}

/// Provenance metadata for a flattening pipeline run.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FlattenMetadata {
    /// Names of every component system that contributed equations.
    pub source_systems: Vec<String>,
    /// Human-readable descriptions of the coupling rules applied, in order.
    pub coupling_rules_applied: Vec<String>,
    /// Every dimension promotion applied during flattening. Always empty at the
    /// Rust Core tier — see [`DimensionPromotionRecord`] (reserved / parity-only).
    pub dimension_promotions_applied: Vec<DimensionPromotionRecord>,
    /// Whether the pipeline had to synthesize an implicit Interface because
    /// the source file didn't declare one. Always `false` at Rust Core tier.
    pub implicit_interface_inferred: bool,
    /// Every state spelling an `operator_compose` renaming match DELETED,
    /// mapped onto the survivor it was folded into (issue #230).
    ///
    /// The flattener's own retarget ([`retarget_merged_names`]) reaches equation
    /// ASTs; this is the map a CONSUMER that addresses a state by NAME needs — a
    /// `parameter_overrides` / `initial_conditions` key, an output selection — to
    /// resolve a spelling the merge moved out from under it. Empty for a
    /// document with no renaming merge, which is the overwhelming majority.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub merged_variable_renames: IndexMap<String, String>,
    /// Every name a COUPLING rule rewrote OUT of the flattened equations: a
    /// NAMED-transform `variable_map`'s substituted `to`, and every merged-away
    /// spelling of [`FlattenMetadata::merged_variable_renames`].
    ///
    /// Only the registry guard reads it
    /// ([`check_registry_coupling_rewrites`]): a surviving
    /// `expression_templates` body is authored source no substitution reaches,
    /// so a body naming one of these is REFUSED rather than resolved
    /// (CONFORMANCE_SPEC §5.35). Not a consumer-facing map, unlike
    /// `merged_variable_renames`: it says a name is GONE, not where it went.
    /// The Rust twin of Python's `FlattenMetadata.coupling_rewritten_names` and
    /// Julia's local `map_rewritten_names`.
    #[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
    pub coupling_rewritten_names: BTreeSet<String>,
}

/// Who authored one [`Contribution`] to a flattened equation
/// (esm-libraries-spec §4.7.5, "Per-term provenance").
///
/// Serialized untagged, as `{"component": "<dotted path>"}` or
/// `{"coupling": <k>}`.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(untagged)]
pub enum TermOrigin {
    /// The full dotted path of the model, subsystem or reaction system whose
    /// equation contained the expression (`"Atmosphere.Chemistry"`).
    Component { component: String },
    /// The 0-based index of the coupling entry that wrote the expression
    /// itself, counted in the coupling sequence AFTER `coupling_import`
    /// expansion. Entries of every type count, including the ones that write
    /// nothing.
    Coupling { coupling: usize },
}

/// One summand of a flattened equation's right-hand side, with its authors
/// (esm-libraries-spec §4.7.5, "Per-term provenance").
///
/// `origins` is deduplicated in first-appearance order, and non-empty except
/// on an equation assembled without provenance (origin unknown). It has more
/// than one entry only where several contributions collapsed into one
/// indivisible expression: a non-additive merge (a multiplicative `couple`, or
/// an `operator_compose` `translate` factor applied to a multi-contribution
/// equation), or a caller's edit to a right-hand side the list no longer sums
/// to ([`FlattenedSystem::equation_contributions`]). Provenance lives here,
/// beside the expression tree, never on a node, so `expr` compares, hashes and
/// interns as any expression.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Contribution {
    pub expr: Expr,
    pub origins: Vec<TermOrigin>,
}

/// Spec-compliant flattened coupled system (§4.7.5).
///
/// The shape matches the Julia and Python flattened systems:
/// real [`Expr`]-tree equations (not strings), ordered variable maps for
/// deterministic iteration, and full provenance metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlattenedSystem {
    /// Independent variables, derived per esm-libraries-spec §4.7.6
    /// "Independent-variable computation": `["t"]` for a 0-D system or a
    /// DISCRETIZED one (whose spatial axes have been folded into `faq`
    /// dimensions and so name no axis any more), and `["t", <spatial axes>]`
    /// for a system still carrying undiscretized spatial differentials.
    ///
    /// This is what decides whether a downstream constructor builds an
    /// `ODESystem` or a `PDESystem`, so an undiscretized spatial operator must
    /// REACH this struct rather than be rejected before it. `t` comes first;
    /// the spatial axes follow in DOCUMENT ORDER — the order the equation scan
    /// first encounters them, which is the order the document names them and
    /// the order a downstream array layout follows.
    pub independent_variables: Vec<String>,
    /// The SOLVED-FOR VECTOR, dot-namespaced and with full metadata: the
    /// differential unknowns, PLUS [`Self::algebraic_variables`], PLUS any
    /// arrayed observed that materializes into a buffer
    /// (esm-libraries-spec §4.7.5 step 4).
    pub state_variables: IndexMap<String, ModelVariable>,
    /// Dot-namespaced parameters. `variable_map` with `param_to_var` or
    /// `conversion_factor` transform removes entries from this map.
    pub parameters: IndexMap<String, ModelVariable>,
    /// The dot-namespaced unknowns an equation DEFINES, at either LHS spelling
    /// (esm-spec §6.3.1). NOT disjoint from [`Self::state_variables`]: a scalar
    /// observed is eliminated by substitution and is in this map alone, while an
    /// arrayed one materializes into a buffer and is in both.
    pub observed_variables: IndexMap<String, ModelVariable>,
    /// Unknowns constrained ONLY by an expression-LHS equation (`H*H*SO4 ~ Ksp`,
    /// esm-spec §6.3.1). A **SUBSET** of [`Self::state_variables`], not a
    /// sibling bucket: `state_variables` is the SOLVED-FOR VECTOR and a DAE
    /// solves for its algebraic unknowns, so removing them from that map would
    /// emit a `u` vector that silently omits them
    /// (esm-libraries-spec §4.7.5 step 4).
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub algebraic_variables: IndexMap<String, ModelVariable>,
    /// Dot-namespaced Brownian noise sources — parameters whose `update.kind`
    /// is `"wiener"`. A **SUBSET** of [`Self::parameters`]: esm-spec §6.3.1 says
    /// the four parameter sets *partition the parameters*, so a wiener entry IS
    /// a parameter and also appears here. Excluding it from `parameters` would
    /// make the parameter vector's LENGTH depend on whether the model happens
    /// to be stochastic, and leave the four sets partitioning nothing.
    /// Non-empty is exactly what §6.3.1's `system_kind` derivation tests FIRST,
    /// so carrying this map is what keeps the flattened form able to report
    /// `"sde"`.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub brownian_parameters: IndexMap<String, ModelVariable>,
    /// Dot-namespaced DISCRETE parameters — any OTHER `update`, i.e.
    /// piecewise-constant between refreshes. Likewise a **SUBSET** of
    /// [`Self::parameters`].
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub discrete_parameters: IndexMap<String, ModelVariable>,
    /// Deferred scoped-reference / array `ic` equations (esm-spec §11.4.1),
    /// classified out of `equations` by [`flatten`]. Each entry is
    /// `(target_state, rhs)` where `target_state` names the (post-lift, grid-
    /// shaped) state variable and `rhs` is the initial-field expression — a bare
    /// reference to a provider-served loaded field (e.g. `InitialConditions.O3_init`)
    /// or a broadcast constant. The array simulator folds these into `u0` cell-by-
    /// cell at build time, reading the loaded field from the data-Provider seam
    /// (DESIGN pde_simulation_pipeline §2 R2). Empty for a system with no `ic`
    /// equations, so the ordinary ODE path is unaffected.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub field_ics: Vec<(String, Expr)>,
    /// Flattened equations in processing order. Every variable reference is
    /// dot-namespaced.
    pub equations: Vec<Equation>,
    /// Per-term provenance (esm-libraries-spec §4.7.5): one entry per entry of
    /// [`Self::equations`], in the same order. Entry `i` lists the summands
    /// whose LEFT-FOLD sum is `equations[i]`'s right-hand side (or, for an
    /// equation the pointwise lift wrapped in a `faq`, that `faq`'s body), each
    /// with the component or coupling entry that authored it. [`flatten`]
    /// builds every right-hand side from this list. Empty only on a system
    /// assembled by hand rather than by [`flatten`].
    ///
    /// A public pass that rebuilds a right-hand side from this list first
    /// checks that the list still sums to it; a caller who edited `rhs` after
    /// flatten keeps the edit, and that equation's list collapses to one
    /// contribution carrying every origin the list named.
    #[serde(default)]
    pub equation_contributions: Vec<Vec<Contribution>>,
    /// One entry per entry of [`Self::equations`]: `true` where the pointwise
    /// lift (esm-spec §10.5) wrapped the equation in an `faq` over the grid, so
    /// that [`Self::equation_contributions`] sums to the `faq` body rather than
    /// to the right-hand side. An authored `faq` right-hand side is `false`.
    /// Empty (and omitted when serialized) when nothing was lifted.
    #[serde(default, skip_serializing_if = "none_lifted")]
    pub equation_lifted: Vec<bool>,
    /// Continuous events from every component, LHS rewritten to namespaced form.
    pub continuous_events: Vec<ContinuousEvent>,
    /// Discrete events from every component, LHS rewritten to namespaced form.
    pub discrete_events: Vec<DiscreteEvent>,
    /// The file's single shared domain, passed through (v0.8.0).
    pub domain: Option<Domain>,
    /// The document-scoped `index_sets` registry (esm-spec v0.8.0), passed
    /// through verbatim from the source [`EsmFile`]. Carried so a coupled
    /// (multi-model) array system reaching the array runtime via
    /// [`crate::simulate_array::ArrayCompiled::from_flattened`] can resolve
    /// `faq` `ranges` `{ "from": <set> }`, `join.on` gates, and
    /// derived-set references against it — exactly as the single-model
    /// `from_file` path resolves them against `file.index_sets`. Empty for a
    /// file that declares no index sets, so the ordinary ODE path is unaffected.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub index_sets: IndexMap<String, IndexSet>,
    /// The document-scoped `function_tables` registry (esm-spec §9.5), copied
    /// from the source [`EsmFile`] in document order. Carried so a surviving
    /// `table_lookup` node resolves without re-reading the source document
    /// (esm-libraries-spec §4.7.5 step 4).
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub function_tables: IndexMap<String, crate::types::FunctionTable>,
    /// The MERGED expression-template registry (esm-spec §9.6.4 rule 7, §10.7;
    /// esm-libraries-spec §4.7.5 step 4): the union of the per-component
    /// registries with each model's carried bodies component-SCOPED first,
    /// deep-equal same-name entries deduplicated at first occurrence, and a
    /// non-deep-equal same-name collision renamed to `<ComponentPath>.<name>`
    /// in every owning component with the rename propagated along the
    /// reference DAG. See [`merged_template_registry`].
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub template_registry: IndexMap<String, serde_json::Value>,
    /// The provider-served loaded fields this system consumes (esm-spec §8.5):
    /// one descriptor per PARAMETER carrying a `data`-kind `update`, in the
    /// document order of [`Self::parameters`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub loader_fields: Vec<LoaderField>,
    /// Concrete integer grid shapes assigned by the pointwise spatial lift
    /// (esm-spec §10.5) to each lifted state variable, e.g.
    /// `{"Chemistry.O3": [4, 2]}`. Empty when no lift ran.
    #[serde(default, skip_serializing_if = "IndexMap::is_empty")]
    pub lifted_shapes: IndexMap<String, Vec<i64>>,
    /// Provenance metadata.
    pub metadata: FlattenMetadata,
}

impl FlattenedSystem {
    /// The flattened system's DERIVED kind (esm-spec §6.3.1) — `"sde"` /
    /// `"pde"` / `"nonlinear"` / `"ode"`, tested in that order.
    ///
    /// Available on the flattened form precisely because
    /// [`Self::brownian_parameters`] survives flattening: the derivation's first
    /// row is "any parameter in `brownian_parameters`", so a `FlattenedSystem`
    /// that dropped the bucket could not report `"sde"` and a consumer would
    /// integrate a stochastic system as a deterministic one
    /// (esm-libraries-spec §4.7.5 step 4).
    pub fn system_kind(&self) -> crate::classification::SystemKind {
        let mut view: IndexMap<String, ModelVariable> = IndexMap::new();
        for (name, var) in &self.state_variables {
            view.insert(name.clone(), var.clone());
        }
        for (name, var) in &self.observed_variables {
            view.entry(name.clone()).or_insert_with(|| var.clone());
        }
        for (name, var) in &self.parameters {
            view.entry(name.clone()).or_insert_with(|| var.clone());
        }
        crate::classification::Classification::from_parts(&view, &self.equations).system_kind
    }

    /// Rewrite every equation's right-hand side with `f` INSIDE each of its
    /// contributions, origins unchanged, and rebuild the right-hand side from
    /// the rewritten list (esm-libraries-spec §4.7.5: a pass over flattened
    /// equations never moves a term across a contribution boundary).
    /// Left-hand sides are not touched.
    ///
    /// The system may have been edited by its caller since [`flatten`], so the
    /// list is not trusted to match: an equation whose list no longer sums to
    /// its right-hand side (or `faq` body) has the list collapsed to ONE
    /// contribution — the current right-hand side, with the union of the
    /// list's origins — before `f` runs, so the caller's edit survives. An
    /// equation with no list (a system assembled by hand) is one contribution
    /// with no origins. A non-empty list whose length differs from
    /// [`Self::equations`]' is refused rather than paired up by position.
    pub(crate) fn map_rhs_per_contribution(
        &mut self,
        mut f: impl FnMut(&Expr) -> Expr,
    ) -> Result<(), FlattenError> {
        let n = self.equations.len();
        for (field, entries) in [
            ("equation_contributions", self.equation_contributions.len()),
            ("equation_lifted", self.equation_lifted.len()),
        ] {
            if entries != 0 && entries != n {
                return Err(FlattenError::ContributionsOutOfStep {
                    field,
                    entries,
                    equations: n,
                });
            }
        }
        if self.equation_contributions.is_empty() {
            self.equation_contributions = vec![Vec::new(); n];
        }
        for (i, eq) in self.equations.iter_mut().enumerate() {
            let lifted = self.equation_lifted.get(i).copied().unwrap_or(false);
            let wrapper = lift_wrapper(&eq.rhs, lifted).cloned();
            let body = wrapper
                .as_ref()
                .and_then(|node| node.expr.as_deref())
                .unwrap_or(&eq.rhs);
            let contributions = &mut self.equation_contributions[i];
            if contributions.is_empty() || fold_contributions(contributions) != *body {
                *contributions = vec![Contribution {
                    expr: body.clone(),
                    origins: union_origins(contributions, None),
                }];
            }
            for c in contributions.iter_mut() {
                c.expr = f(&c.expr);
            }
            eq.rhs = rebuild_body(wrapper, fold_contributions(contributions));
        }
        Ok(())
    }
}

/// Serde skip predicate for [`FlattenedSystem::equation_lifted`].
fn none_lifted(flags: &[bool]) -> bool {
    !flags.contains(&true)
}

/// The `faq` the pointwise lift wrapped around `rhs`, when `lifted` says it
/// did (esm-libraries-spec §4.7.5: `body(eq)` is that `faq`'s body).
pub(crate) fn lift_wrapper(rhs: &Expr, lifted: bool) -> Option<&ExpressionNode> {
    match rhs {
        Expr::Operator(node) if lifted => Some(node),
        _ => None,
    }
}

/// `body`, re-wrapped in the lift's `faq` when the equation carried one.
pub(crate) fn rebuild_body(wrapper: Option<ExpressionNode>, body: Expr) -> Expr {
    match wrapper {
        Some(mut node) => {
            node.expr = Some(Box::new(body));
            Expr::operator(node)
        }
        None => body,
    }
}

/// The right-hand side a contribution list stands for: the LEFT fold of the
/// contribution expressions under binary `+` (esm-libraries-spec §4.7.5, the
/// provenance invariant).
pub(crate) fn fold_contributions(contributions: &[Contribution]) -> Expr {
    let mut iter = contributions.iter();
    let Some(first) = iter.next() else {
        return zero();
    };
    iter.fold(first.expr.clone(), |acc, c| sum_exprs(acc, c.expr.clone()))
}

/// Every origin of `contributions`, then `extra`, deduplicated in
/// first-appearance order.
fn union_origins(contributions: &[Contribution], extra: Option<TermOrigin>) -> Vec<TermOrigin> {
    let mut out: Vec<TermOrigin> = Vec::new();
    for origin in contributions
        .iter()
        .flat_map(|c| c.origins.iter().cloned())
        .chain(extra)
    {
        if !out.contains(&origin) {
            out.push(origin);
        }
    }
    out
}

/// A flattened equation in the making: the equation, its contribution list,
/// and whether the pointwise lift wrapped its right-hand side in a `faq`.
///
/// Every flatten pass edits `contributions` and rebuilds `eq.rhs` from them
/// ([`Self::set_contributions`]), never the other way round, so the
/// right-hand side is always the left fold of the list.
#[derive(Debug, Clone)]
struct FlatEq {
    eq: Equation,
    contributions: Vec<Contribution>,
    lifted: bool,
}

impl FlatEq {
    /// `eq` as written by `origin`: one contribution, its right-hand side.
    fn authored(eq: Equation, origin: TermOrigin) -> Self {
        let contributions = vec![Contribution {
            expr: eq.rhs.clone(),
            origins: vec![origin],
        }];
        FlatEq {
            eq,
            contributions,
            lifted: false,
        }
    }

    /// The sum the contributions stand for: `rhs`, or the lift's `faq` body.
    fn body(&self) -> &Expr {
        lift_wrapper(&self.eq.rhs, self.lifted)
            .and_then(|node| node.expr.as_deref())
            .unwrap_or(&self.eq.rhs)
    }

    /// Replace the contribution list and rebuild the right-hand side from it.
    fn set_contributions(&mut self, contributions: Vec<Contribution>) {
        let body = fold_contributions(&contributions);
        self.eq.rhs = rebuild_body(lift_wrapper(&self.eq.rhs, self.lifted).cloned(), body);
        self.contributions = contributions;
    }

    /// Apply `f` inside every contribution, origins unchanged, and rebuild.
    fn map_contributions(&mut self, mut f: impl FnMut(&Expr) -> Expr) {
        let mapped = self
            .contributions
            .iter()
            .map(|c| Contribution {
                expr: f(&c.expr),
                origins: c.origins.clone(),
            })
            .collect();
        self.set_contributions(mapped);
    }
}

/// One provider-served loaded field the flattened system consumes
/// (esm-spec §8.5; esm-libraries-spec §4.7.5 step 4 `loader_fields`).
///
/// From esm 1.0.0 a data source is not a component: there is no loader
/// subsystem and no coupling edge. A model consumes a source by declaring a
/// PARAMETER whose `update` is `{kind: "data", source: <key>, from:
/// {file_variable}}` — the parameter IS the loaded field and owns the units.
/// Flatten records this descriptor per such parameter so a consumer can
/// execute the source at its cadence and bind the resulting array into the RHS
/// as a read-only input, without re-reading the source document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LoaderField {
    /// The namespaced parameter symbol, e.g. `"Advection.u_wind"`.
    pub name: String,
    /// The owning component's namespace prefix, e.g. `"Advection"`.
    pub owner: String,
    /// The `data_sources` key the parameter's `update` names.
    pub source: String,
    /// The source-file variable the binding names.
    pub file_variable: String,
    /// `"const"` (the source declares no `temporal` block — read once before
    /// integration) or `"discrete"` (time-varying — refreshed at its cadence).
    /// The source-seeded cadence refinement of CONFORMANCE_SPEC §5.7.2.
    pub cadence: String,
}

// ============================================================================
// Public entry points
// ============================================================================

/// Flatten a coupled [`EsmFile`] into a single unified [`FlattenedSystem`].
///
/// Implements spec §4.7.5 + §4.7.6 at the Core tier. Pipeline:
///
/// 1. Lower every reaction system to ODE equations ([`crate::reactions::lower_reactions_to_equations`]).
/// 2. Namespace every variable, parameter, and equation by dot-notation.
/// 3. Derive [`FlattenedSystem::independent_variables`] from the flattened
///    equations (§4.7.6) — an undiscretized spatial operator names an axis
///    here, it is NOT rejected. No `dimension_mapping` inspection is performed:
///    `slice` / `project` / `regrid` are not checked at this tier.
/// 4. Apply coupling rules in order: `operator_compose`, `couple`,
///    `variable_map` (see §4.7.1–§4.7.4).
/// 5. Detect [`FlattenError::ConflictingDerivative`] — species that end up
///    with both an explicit `D(X, t)` equation and reaction-derived rate
///    without an explicit `operator_compose` to merge them.
/// 6. Collect into [`FlattenedSystem`] with metadata provenance.
///
/// # Errors
///
/// Returns [`FlattenError`] per §4.7.6.10 error taxonomy.
pub fn flatten(file: &EsmFile) -> Result<FlattenedSystem, FlattenError> {
    flatten_with_options(
        file,
        &crate::coupling_imports::CouplingImportOptions::default(),
    )
}

/// Flatten with explicit [`CouplingImportOptions`](crate::CouplingImportOptions) controlling how
/// `coupling_import` `ref`s resolve (esm-spec §10.10.3). When the file carries
/// no `coupling_import` entry this is identical to [`flatten`]; otherwise the
/// import entries are expanded into concrete edges — spliced in position — as a
/// §4.7.5 sub-step *before* the coupling-rule step, and flattening proceeds over
/// the expanded coupling sequence. The `coupling_import` source entry is not
/// mutated on the caller's `file`; the expansion operates on an internal clone.
///
/// # Errors
///
/// Returns [`FlattenError::CouplingImport`] (carrying a stable §10.11
/// diagnostic code) if any `coupling_import` fails to resolve or expand;
/// otherwise the [`FlattenError`] taxonomy of [`flatten`].
pub fn flatten_with_options(
    file: &EsmFile,
    options: &crate::coupling_imports::CouplingImportOptions,
) -> Result<FlattenedSystem, FlattenError> {
    // §4.7.5 expansion sub-step: expand `coupling_import` edges before the
    // coupling-rule step. Only clone the file when an import is actually
    // present, so the common (no-import) path is untouched.
    if crate::coupling_imports::has_coupling_import(file) {
        let expanded = crate::coupling_imports::expand_coupling_imports(file, options)?;
        let mut cloned = file.clone();
        cloned.coupling = expanded;
        flatten_impl(&cloned)
    } else {
        flatten_impl(file)
    }
}

/// The core flattening algorithm, operating over an already-`coupling_import`-
/// expanded [`EsmFile`] (see [`flatten_with_options`]).
fn flatten_impl(file: &EsmFile) -> Result<FlattenedSystem, FlattenError> {
    let has_models = file.models.as_ref().is_some_and(|m| !m.is_empty());
    let has_rs = file
        .reaction_systems
        .as_ref()
        .is_some_and(|rs| !rs.is_empty());

    if !has_models && !has_rs {
        return Err(FlattenError::Empty);
    }

    // Preflight (esm-spec §10.4): a `variable_map` `identity` transform must not
    // bridge two variables carrying declared, non-empty, and differing units.
    // Mirrors Julia's `_check_variable_map_units` (coupling_apply.jl), run before
    // collection so an incoherent identity map fails fast.
    check_variable_map_units(file)?;

    // Phase 1: collect per-system lowered equations and namespaced variables.
    let (source_systems, mut per_system) = collect_component_systems(file)?;

    // Phase 2 preflight (esm-spec §4.6 / §10.4): every `variable_map` endpoint
    // must name something the collected system carries. Run against the
    // PRE-coupling tables so an `operator_compose` `translate` merge (§10.2,
    // which legitimately consumes one of the two spellings) cannot make a
    // well-formed endpoint look unresolvable.
    check_variable_map_endpoints(file, &per_system)?;

    // NOTE: flatten does NOT reject an undiscretized spatial operator. It used
    // to, and that was this binding's own stricter behaviour rather than the
    // format's: esm-libraries-spec §4.7.6 "Independent-variable computation" is
    // a normative algorithm that DERIVES `[:t, :x, :y, …]` from exactly those
    // operators, and says the result "is what determines whether the downstream
    // constructor produces an ODESystem or a PDESystem" — which refusing makes
    // unreachable, along with §6.3.1's `"pde"` `system_kind`. Python, Go and
    // TypeScript all flatten such a document and agree on the ordered lists.
    // See `derive_independent_variables` below.
    //
    // The `unlowered_operator` gate still fires where discretization is
    // genuinely required — the scalar and array simulators reject a surviving
    // rewrite-target op at COMPILE time via
    // [`crate::compile_error::CompileError::UnloweredOperatorError`] — and a
    // consumer that needs a discretized system can demand one explicitly with
    // [`reject_unlowered_operators`].

    // Phase 3: apply coupling rules, collecting rule descriptions and the
    // document-wide map of the state names the merges DELETED (issue #230).
    let CouplingOutcome {
        rules_applied: coupling_rules_applied,
        merged_variable_renames,
        coupling_rewritten_names,
    } = apply_coupling_entries(file, &mut per_system)?;

    // Phase 4: conflict detection after coupling.
    detect_conflicts(file, &per_system)?;

    // Phase 5: collect into the final FlattenedSystem shape.
    let mut parts = assemble_output(per_system);

    // Phase 5a: post-collection variable_map parameter removals, plus the
    // source-fed array parameters that replace them from esm 1.0.0.
    let mut loaded_producers =
        apply_variable_map_removals(file, &mut parts, &merged_variable_renames);
    loaded_producers.extend(source_fed_producers(&parts));

    // Phase 5b: pointwise spatial lift (esm-spec §10.5).
    maybe_apply_pointwise_lift(file, &mut parts, &loaded_producers)?;

    // Phase 5b′ (esm-libraries-spec §4.7.5 step 3a): resolve a right-hand-side
    // STRUCTURAL time derivative to the tendency this system defines for it
    // (esm-spec §4.2). Runs after the lift so it sees the equations the lift
    // produced, after reaction lowering (phase 1) so a mechanism's mass-action
    // tendency is available to a sibling model's scoped `D(Chem.O3, t)`, and
    // after coupling (phase 4) so a state merged by `operator_compose` yields
    // its WHOLE tendency rather than the first contributing term.
    let time_invariant: HashSet<String> = parts.parameters.keys().cloned().collect();
    resolve_rhs_time_derivatives_per_contribution(&mut parts.equations, &time_invariant);

    // Phase 5b″: classify the `ic` equations OUT of `equations` into
    // `field_ics` (esm-libraries-spec §4.7.5 step 4). After 5b′, so an
    // `ic(y) ~ D(x, t)` reaches `field_ics` as `x`'s resolved tendency (step
    // 3a), and before 5c, so classification never sees an `ic` equation.
    extract_field_ics(&mut parts);

    // Phase 5c: the §6.3.1 SUBSET maps, re-derived over the FINISHED system so
    // they see the equations coupling and the pointwise lift actually produced
    // rather than the ones the document declared. Each is a subset of the map
    // it classifies, in that map's document order.
    let class = flattened_classification(&parts);
    let algebraic_variables = in_document_order(
        &class.algebraic_unknowns,
        &[&parts.state_variables, &parts.observed_variables],
    );
    let brownian_parameters = in_document_order(&class.brownian_parameters, &[&parts.parameters]);
    let discrete_parameters = in_document_order(&class.discrete_parameters, &[&parts.parameters]);

    // Phase 5d: the provider-served loaded fields (esm-spec §8.5).
    let loader_fields = collect_loader_fields(file, &parts.parameters);

    // Phase 5e: the §4.7.6 independent-variable derivation, over the FINISHED
    // equation set (post-coupling, post-lift) plus the `ic` equations that were
    // classified out of it — the oracle derives before splitting `field_ics`
    // off, so scanning both keeps the two passes seeing the same expressions.
    let independent_variables = derive_independent_variables(&parts);

    // Phase 5g: bring a scaled ANGLE argument of `sin`/`cos`/`tan` to radians
    // (esm-spec §4.8.3, issue #409). See [`normalize_angle_arguments`].
    normalize_angle_arguments(&mut parts);

    let AssembledParts {
        state_variables,
        parameters,
        observed_variables,
        field_ics,
        equations,
        continuous_events,
        discrete_events,
        lifted_shapes,
    } = parts;

    // Phase 5f: the MERGED expression-template registry (esm-spec §9.6.4 rule 7)
    // ...and the ONE place a coupling-rewritten name is REFUSED rather than
    // resolved. See [`check_registry_coupling_rewrites`].
    let template_registry = merged_template_registry(file);
    check_registry_coupling_rewrites(&template_registry, &coupling_rewritten_names)?;

    let equation_lifted: Vec<bool> = if equations.iter().any(|fe| fe.lifted) {
        equations.iter().map(|fe| fe.lifted).collect()
    } else {
        Vec::new()
    };
    let (equations, equation_contributions): (Vec<Equation>, Vec<Vec<Contribution>>) = equations
        .into_iter()
        .map(|fe| (fe.eq, fe.contributions))
        .unzip();

    Ok(FlattenedSystem {
        independent_variables,
        state_variables,
        parameters,
        observed_variables,
        algebraic_variables,
        brownian_parameters,
        discrete_parameters,
        field_ics,
        equations,
        equation_contributions,
        equation_lifted,
        continuous_events,
        discrete_events,
        domain: file.domain.clone(),
        index_sets: file
            .index_sets
            .as_ref()
            .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default(),
        function_tables: file
            .function_tables
            .as_ref()
            .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
            .unwrap_or_default(),
        template_registry,
        loader_fields,
        lifted_shapes,
        metadata: FlattenMetadata {
            source_systems,
            coupling_rules_applied,
            dimension_promotions_applied: Vec::new(),
            implicit_interface_inferred: false,
            merged_variable_renames,
            coupling_rewritten_names,
        },
    })
}

/// Fold the declared angle scale into every circular-trig argument, so the
/// evaluator receives RADIANS (esm-spec §4.8.3 "Angles are the ONE exception").
///
/// `deg` is a registry unit at scale π/180, so `sin(theta [deg])` is a
/// CONFORMING document — and before this it handed the stored number straight to
/// `sin`, returning `sin(90) = 0.894` where 1 was meant, with no diagnostic
/// (issue #409). The conversion is exact and has exactly one reading, which is
/// why this half converts where the dimensionless-but-scaled half refuses.
///
/// **Why here.** `flatten` is the single funnel every evaluator in this crate
/// draws from — the array oracle, the vectorized overlay, the tape and the XLA
/// emitter all consume a [`FlattenedSystem`] — so
/// one phase here converts for all of them, and they cannot diverge. It is NOT
/// on the validation path (`validate` never flattens), so the checker keeps
/// seeing the authored spelling: a rewrite visible to the checker would turn
/// `sin(theta [deg])` into `sin(theta * 0.01745…)`, whose bare literal makes the
/// product UNDETERMINABLE (§4.8.4) and silently disables the very check this
/// change strengthens.
///
/// Each equation is rewritten inside each of its contributions, and its
/// right-hand side rebuilt from them (esm-libraries-spec §4.7.5).
fn normalize_angle_arguments(flat: &mut AssembledParts) {
    let mut vars: IndexMap<String, ModelVariable> = IndexMap::new();
    for m in [
        &flat.state_variables,
        &flat.parameters,
        &flat.observed_variables,
    ] {
        for (k, v) in m {
            vars.entry(k.clone()).or_insert_with(|| v.clone());
        }
    }
    // A document that declares no angle at a scale other than 1 cannot be
    // rewritten, so decide that from the DECLARATIONS and walk nothing.
    let (env, _) = crate::units::build_unit_env(&vars);
    if !env
        .values()
        .any(|u| crate::units::angle_normalization_factor(u).is_some())
    {
        return;
    }

    let rewrite = |e: &mut Expr| {
        if let Some(next) = crate::units::normalize_angle_arguments(e, &env) {
            *e = next;
        }
    };
    for fe in &mut flat.equations {
        // Rebuild only an equation whose contributions the rewrite changed.
        let rewritten: Vec<Option<Expr>> = fe
            .contributions
            .iter()
            .map(|c| crate::units::normalize_angle_arguments(&c.expr, &env))
            .collect();
        if rewritten.iter().all(Option::is_none) {
            continue;
        }
        let contributions = std::mem::take(&mut fe.contributions)
            .into_iter()
            .zip(rewritten)
            .map(|(c, next)| match next {
                Some(expr) => Contribution { expr, ..c },
                None => c,
            })
            .collect();
        fe.set_contributions(contributions);
    }
    for (_, e) in &mut flat.field_ics {
        rewrite(e);
    }
    // Events are rewritten too, although no evaluator in THIS crate runs one
    // (`unsupported_construct`, esm-spec §9.6.6). The flattened form is a
    // cross-binding artefact — the Julia binding exports it to
    // ModelingToolkit, which does run events — so leaving a `sin(theta [deg])`
    // in an event condition unconverted would put the defect back in the one
    // place a binding still evaluates it, and would make the five flattened
    // forms disagree.
    for ev in &mut flat.continuous_events {
        for c in &mut ev.conditions {
            rewrite(c);
        }
        for a in &mut ev.affects {
            rewrite(&mut a.rhs);
        }
        for a in ev.affect_neg.iter_mut().flatten() {
            rewrite(&mut a.rhs);
        }
    }
    for ev in &mut flat.discrete_events {
        if let DiscreteEventTrigger::Condition { expression } = &mut ev.trigger {
            rewrite(expression);
        }
        for a in ev.affects.iter_mut().flatten() {
            rewrite(&mut a.rhs);
        }
    }
}

/// Keys of an expression node whose STRING value names something other than a
/// variable, so a raw-body walk must not read them as references.
const TEMPLATE_BODY_NON_OPERAND_KEYS: &[&str] = &[
    "op", "wrt", "dim", "fn", "table", "id", "manifold", "name", "semiring", "reduce",
];

/// Every variable name a RAW (unparsed) template body references.
///
/// The registry holds bodies as JSON rather than as [`Expr`], so this walks the
/// JSON: a bare string in an OPERAND position is a variable reference. A
/// structural key (`op`, `wrt`, `fn`, …) names an operator, an axis or a
/// registry id and is skipped. Mirrors Python
/// `flatten.py::_template_body_var_names`.
fn template_body_var_names(body: &serde_json::Value) -> BTreeSet<String> {
    fn walk(node: &serde_json::Value, operand: bool, out: &mut BTreeSet<String>) {
        match node {
            serde_json::Value::String(name) if operand => {
                out.insert(name.clone());
            }
            serde_json::Value::Array(items) => {
                for item in items {
                    walk(item, operand, out);
                }
            }
            serde_json::Value::Object(map) => {
                for (key, value) in map {
                    walk(
                        value,
                        !TEMPLATE_BODY_NON_OPERAND_KEYS.contains(&key.as_str()),
                        out,
                    );
                }
            }
            _ => {}
        }
    }
    let mut out = BTreeSet::new();
    walk(body, false, &mut out);
    out
}

/// Refuse a SURVIVING registry body that names a coupling-rewritten variable.
///
/// A `variable_map` substitution and an `operator_compose` renaming match both
/// DELETE a name from the flattened tables and rewrite the equations off it. A
/// surviving `expression_templates` body is a shadow copy of authored source
/// that no equation walk reaches, and it expands at the BUILD boundary rather
/// than at flatten — so a body still naming a deleted variable would expand,
/// later and elsewhere, into a name the flattened system does not declare (for
/// `param_to_var` / `conversion_factor`, an unbound variable deep in the build;
/// for the scaling transforms, a silent semantic divergence from the
/// expand-at-load image).
///
/// This is the ONE site where such a reference is REFUSED rather than resolved
/// (CONFORMANCE_SPEC §5.35). The body is authored source: rewriting it would
/// silently diverge from the expand-at-load image the same document produces
/// with reference-preserving expansion disabled. A template `param` SHADOWS the
/// outer name (esm-spec §9.6.1), so a body that BINDS the name through its
/// params is fine — which is exactly the fix the message names.
///
/// Mirrors Julia `flatten.jl::_check_registry_coupling_rewrites` and Python
/// `flatten.py::_check_registry_coupling_rewrites`.
fn check_registry_coupling_rewrites(
    registry: &IndexMap<String, serde_json::Value>,
    rewritten: &BTreeSet<String>,
) -> Result<(), FlattenError> {
    if registry.is_empty() || rewritten.is_empty() {
        return Ok(());
    }
    // Sorted, so the template a multi-entry registry reports is not a function
    // of document order — the peer bindings sort here for the same reason.
    let mut names: Vec<&String> = registry.keys().collect();
    names.sort_unstable();
    for tname in names {
        let Some(decl) = registry[tname.as_str()].as_object() else {
            continue;
        };
        let Some(body) = decl.get("body") else {
            continue;
        };
        let params: BTreeSet<&str> = decl
            .get("params")
            .and_then(|p| p.as_array())
            .map(|entries| entries.iter().filter_map(|v| v.as_str()).collect())
            .unwrap_or_default();
        let hits: Vec<String> = template_body_var_names(body)
            .into_iter()
            .filter(|name| !params.contains(name.as_str()) && rewritten.contains(name))
            .collect();
        if !hits.is_empty() {
            return Err(FlattenError::ExpressionTemplate(crate::diagnostic::err(
                crate::diagnostic::codes::TEMPLATE_BODY_REFERENCES_COUPLING_REWRITTEN_VARIABLE,
                format!(
                    "expression template '{tname}' body references '{}', which a coupling rule \
                     rewrote in the flattened equations; the registry body would expand to a \
                     stale name at the build boundary. Bind the value through the template's \
                     params, or expand the reference before coupling (esm-spec §9.6.4).",
                    hits.join("', '")
                ),
            )));
        }
    }
    Ok(())
}

/// The MERGED expression-template registry of the flattened representation
/// (esm-spec §9.6.4 rule 7, §10.7; esm-libraries-spec §4.7.5 step 4).
///
/// Union of the per-component registries [captured at load]
/// (`EsmFile::component_templates`), in this order:
///
/// 1. **Scope, THEN union.** Each MODEL block's bodies are component-scoped
///    first ([`scope_template_body`]), because the dedup below compares
///    POST-scoping bodies. Step 4 calls this an ordering requirement rather
///    than a parenthetical, and it is load-bearing: two components importing
///    one library each supply their own free `inv_dx`, so their carried entries
///    are byte-identical pre-scoping and deduplicate to a single body that is
///    correct for NEITHER. Scoping also makes them non-deep-equal, which is
///    what routes them into the collision rename and keeps an entry per owner.
///    Reaction-system blocks pass through UNSCOPED by policy, mirroring the
///    Julia reference and the Python oracle: a rate-law reference is expanded
///    eagerly at collect, so a reaction-system entry is never resolved against
///    the post-flatten scope.
/// 2. **Deep-equal dedup at first occurrence.**
/// 3. **Collision rename** to `<ComponentPath>.<name>` in EVERY owning
///    component, propagated along the reference DAG
///    ([`crate::lower_expression_templates::registry_collision_names`]) so no
///    surviving body holds a reference the merged registry cannot resolve.
///
/// `match` rules are excluded: only match-less templates are referenceable
/// (§9.6.2), so only they can be merged.
///
/// Components are walked in DOCUMENT order (models in file order, then reaction
/// systems), which is what step 4's ordering rule requires and what makes
/// "first occurrence" mean the first occurrence in the file.
///
/// Rust's typed build path expands every surviving reference at load (RFC
/// out-of-line-expression-templates §7.7), so no equation reaching here carries
/// an `apply_expression_template` node and the rename has no COMPONENT
/// reference site left to rewrite — step 4's "Applicability" paragraph says
/// exactly this. The registry is still carried, because the field is normative
/// and a consumer must be able to reconstitute the reference-preserving
/// document from the flattened form alone.
pub fn merged_template_registry(file: &EsmFile) -> IndexMap<String, serde_json::Value> {
    let Some(component_templates) = &file.component_templates else {
        return IndexMap::new();
    };

    // Document order: models as the file declares them, then reaction systems,
    // then any captured component the typed file no longer holds.
    let mut ordered: Vec<String> = Vec::new();
    if let Some(models) = &file.models {
        ordered.extend(models.keys().map(|n| format!("models.{n}")));
    }
    if let Some(rs) = &file.reaction_systems {
        ordered.extend(rs.keys().map(|n| format!("reaction_systems.{n}")));
    }
    for key in component_templates.keys() {
        if !ordered.contains(key) {
            ordered.push(key.clone());
        }
    }

    // name -> [(component_path, declaration), ...], in document order.
    let mut byname: Vec<(String, Vec<(String, serde_json::Value)>)> = Vec::new();
    for compkey in &ordered {
        let Some(block) = component_templates.get(compkey).and_then(|v| v.as_object()) else {
            continue;
        };
        let (section, cname) = compkey.split_once('.').unwrap_or(("", compkey.as_str()));
        let model = (section == "models")
            .then(|| file.models.as_ref().and_then(|m| m.get(cname)))
            .flatten();
        for (tname, decl) in block {
            if decl.get("match").is_some_and(|m| !m.is_null()) {
                continue; // match rules are not referenceable, so not merged
            }
            let scoped = match (model, decl.get("body")) {
                (Some(model), Some(body)) => {
                    let params: HashSet<String> = decl
                        .get("params")
                        .and_then(|p| p.as_array())
                        .map(|a| {
                            a.iter()
                                .filter_map(|v| v.as_str().map(str::to_string))
                                .collect()
                        })
                        .unwrap_or_default();
                    let mut locals: HashSet<String> = model.variables.keys().cloned().collect();
                    if let Some(subs) = &model.subsystems {
                        locals.extend(subs.keys().cloned());
                    }
                    for p in &params {
                        locals.remove(p);
                    }
                    match serde_json::from_value::<Expr>(body.clone()) {
                        Ok(parsed) => {
                            let scoped_body =
                                scope_template_body(&parsed, cname, &locals, &HashSet::new());
                            match serde_json::to_value(&scoped_body) {
                                Ok(v) => {
                                    let mut d = decl.clone();
                                    if let Some(obj) = d.as_object_mut() {
                                        obj.insert("body".to_string(), v);
                                    }
                                    d
                                }
                                // A body that will not re-serialize is carried
                                // verbatim rather than dropped: the registry is
                                // provenance, and losing an entry is worse than
                                // carrying an unscoped one.
                                Err(_) => decl.clone(),
                            }
                        }
                        Err(_) => decl.clone(),
                    }
                }
                _ => decl.clone(),
            };
            match byname.iter_mut().find(|(k, _)| k == tname) {
                Some((_, occ)) => occ.push((cname.to_string(), scoped)),
                None => byname.push((tname.clone(), vec![(cname.to_string(), scoped)])),
            }
        }
    }

    let collide = crate::lower_expression_templates::registry_collision_names(&byname);
    let mut merged: IndexMap<String, serde_json::Value> = IndexMap::new();
    let mut rename: HashMap<String, HashMap<String, String>> = HashMap::new();
    for (name, occ) in &byname {
        if collide.contains(name) {
            for (path, decl) in occ {
                let newname = format!("{path}.{name}");
                merged.insert(newname.clone(), decl.clone());
                rename
                    .entry(path.clone())
                    .or_default()
                    .insert(name.clone(), newname);
            }
        } else {
            merged.insert(name.clone(), occ[0].1.clone()); // deep-equal dedup
        }
    }
    // A renamed body's own nested references follow its OWNER's map, so a
    // per-owner wrapper reaches its owner's leaf and never the other owner's.
    for per_owner in rename.values() {
        for new in per_owner.values() {
            if let Some(decl) = merged.get_mut(new) {
                crate::lower_expression_templates::rename_apply_refs(decl, per_owner);
            }
        }
    }
    merged
}

/// Component-scope ONE carried template body: prefix exactly the references
/// that name one of the OWNING component's locals.
///
/// Unlike [`namespace_expr`] — which prefixes every bare reference except an
/// explicit leave-alone set — this is a WHITELIST, matching the Julia
/// `namespace_expr(body, cname, local_names)` and the Python oracle's
/// `_scope_template_body`: a body legitimately references its own formal
/// `params`, loop symbols, and document-scoped index sets, none of which is a
/// component local and none of which may be prefixed. The caller removes the
/// template's `params` from `locals` before calling.
fn scope_template_body(
    expr: &Expr,
    prefix: &str,
    locals: &HashSet<String>,
    bound: &HashSet<String>,
) -> Expr {
    match expr {
        Expr::Number(n) => Expr::Number(*n),
        Expr::Integer(n) => Expr::Integer(*n),
        Expr::Variable(name) => {
            if bound.contains(name) {
                return Expr::Variable(name.clone());
            }
            let head = name.split('.').next().unwrap_or(name.as_str());
            if locals.contains(head) {
                Expr::Variable(format!("{prefix}.{name}"))
            } else {
                Expr::Variable(name.clone())
            }
        }
        Expr::Operator(node) => {
            let mut child_bound = bound.clone();
            if let Some(output_idx) = &node.output_idx {
                child_bound.extend(output_idx.iter().cloned());
            }
            if let Some(ranges) = &node.ranges {
                child_bound.extend(ranges.keys().cloned());
            }
            let mut out =
                node.map_children(&mut |c| scope_template_body(c, prefix, locals, &child_bound));
            if let Some(join) = &node.join {
                let mut binders: HashSet<&str> = HashSet::new();
                if let Some(output_idx) = &node.output_idx {
                    binders.extend(output_idx.iter().map(String::as_str));
                }
                if let Some(ranges) = &node.ranges {
                    binders.extend(ranges.keys().map(String::as_str));
                }
                if let Some(ns) = namespace_join_names(join, &binders, prefix, locals) {
                    out.join = Some(ns);
                }
            }
            Expr::operator(out)
        }
    }
}

/// Phase 5e of [`flatten`]: the independent variables of the flattened system
/// (esm-libraries-spec §4.7.6 "Independent-variable computation").
///
/// The spec's three steps:
///
/// 1. **Start with `["t"]`.** Time is always an independent variable.
/// 2. **Scan every equation for spatial operators** — `grad` / `div` /
///    `laplacian` (and any other undiscretized differential), or a `D` whose
///    `wrt` is not the time variable — and add each spatial dimension they
///    reference.
/// 3. **Scan every `domains` entry for spatial axes** and add them. VACUOUS
///    since v0.8.0: `Domain.spatial` was removed, and the surviving `domain`
///    carries only `independent_variable` / `temporal` / `element_type` /
///    `array_type`. There is no spatial domain left to scan, so the operators
///    in the equations are the whole signal — esm-spec §6.3.1 makes the same
///    point about the `"pde"` `system_kind` test.
///
/// Step 2's signal is harvested STRUCTURALLY, from the axis-naming `dim` scalar
/// field (esm-spec §4.9.1) and from a spatial `wrt` — never from a hardcoded
/// op-name list, so the sugar ops carry no spatial-detection privilege over a
/// custom rewrite-target op. A DISCRETIZED system has folded its spatial axes
/// into array dimensions and carries no such node, so it yields nothing and
/// stays a pure ODE with `["t"]`.
///
/// **Ordering.** `t` first, then the spatial axes in DOCUMENT ORDER, like every
/// other ordered field in step 4 — the order the scan first encounters them,
/// which is the order the document names them (`full_coupled` →
/// `["t", "lon", "lat", "lev"]`). The axes are never sorted: the axis order is
/// the order a downstream array layout follows, so sorting would silently
/// permute the modeller's axes.
fn derive_independent_variables(parts: &AssembledParts) -> Vec<String> {
    // First-encounter order, deduplicated. `out` doubles as the seen-set: it
    // starts with "t", which also drops a spatial `wrt` naming time.
    let mut out = vec!["t".to_string()];
    let mut scan = |e: &Expr| collect_spatial_dims(e, &mut out);
    for fe in &parts.equations {
        scan(&fe.eq.lhs);
        scan(&fe.eq.rhs);
    }
    for (_, rhs) in &parts.field_ics {
        scan(rhs);
    }
    // Step 3 is vacuous — see the doc comment.
    out
}

/// Collect the spatial dimension labels an UNDISCRETIZED differential names
/// anywhere in `expr`. Helper of [`derive_independent_variables`].
fn collect_spatial_dims(expr: &Expr, out: &mut Vec<String>) {
    let Expr::Operator(node) = expr else { return };
    // The axis a `grad` / `div` / `laplacian` (or any custom differential)
    // iterates over. Only an undiscretized differential carries it; no
    // evaluable-core op uses `dim`.
    if let Some(dim) = &node.dim
        && !out.iter().any(|d| d == dim)
    {
        out.push(dim.clone());
    }
    // A SPATIAL `D`: `wrt` naming an axis other than time. The structural
    // `D(u, t)` of an ODE is excluded, as is a `D` with no `wrt` (time by
    // default).
    if let Some(wrt) = &node.wrt
        && wrt != "t"
        && !out.iter().any(|d| d == wrt)
    {
        out.push(wrt.clone());
    }
    node.for_each_child(&mut |child| collect_spatial_dims(child, out));
}

/// Demand that `flat` carry NO undiscretized rewrite-target operator, reporting
/// the first offender as [`FlattenError::UnloweredOperator`] (the uniform
/// `unlowered_operator` code, esm-spec §4.2 / §9.6.8).
///
/// [`flatten`] itself does NOT run this: a PDE is a legitimate flattened system
/// whose spatial axes §4.7.6 records in
/// [`FlattenedSystem::independent_variables`], and refusing it would make
/// `PDESystem` construction and the `"pde"` `system_kind` unreachable. This is
/// for a consumer that genuinely REQUIRES a discretized system and wants to say
/// so before it starts work; the scalar and array simulators enforce the same
/// rule at compile time on their own, through
/// [`crate::compile_error::CompileError::UnloweredOperatorError`].
///
/// The tier decision is delegated wholesale to [`crate::op_registry`], so this
/// keeps no hand-maintained op-name list.
pub fn reject_unlowered_operators(flat: &FlattenedSystem) -> Result<(), FlattenError> {
    match first_unlowered_operator(flat) {
        Some(op) => Err(FlattenError::UnloweredOperator { op }),
        None => Ok(()),
    }
}

/// The name of the first undiscretized rewrite-target operator in `flat`, or
/// `None` when the system is fully discretized.
///
/// The query form of [`reject_unlowered_operators`], for a caller that already
/// has its own error type — the scalar and array simulators use it to report a
/// PDE that reached them with the uniform `unlowered_operator` code
/// ([`crate::compile_error::CompileError::UnloweredOperatorError`]) rather than
/// the vaguer "unsupported dimensionality", preserving the cross-binding
/// diagnostic esm-spec §4.2 / §9.6.8 specifies.
pub fn first_unlowered_operator(flat: &FlattenedSystem) -> Option<String> {
    for eq in &flat.equations {
        for side in [&eq.lhs, &eq.rhs] {
            if let Err(FlattenError::UnloweredOperator { op }) = reject_spatial_operators(side) {
                return Some(op);
            }
        }
    }
    None
}

/// The name a right-hand-side structural `D` differentiates, for the first such
/// node in `flat` that [`resolve_rhs_time_derivatives`] left standing — or
/// `None` when every one of them resolved.
///
/// The companion gate to that phase, and the second half of esm-spec §4.2's
/// right-hand-side `D` rule. The phase resolves a `D` over an unknown that
/// carries a differential equation; everything else it deliberately leaves
/// alone, because resolving it would be symbolic differentiation and the format
/// defines none:
///
/// * `D` of an OBSERVED or a PARAMETER,
/// * `D` of a compound expression (`D(a*b, t)`),
/// * a self- or mutually-referential tendency chain, which the phase stops
///   expanding rather than looping.
///
/// Each of those is a rewrite-target that reached evaluation unlowered, and
/// §4.2 says an implementation MUST NOT invent a value for it — **in particular
/// not `0`**, which is what all three Rust evaluators used to return and what
/// made three shipped documents compute silent zeros. So both compile paths ask
/// this before they build.
///
/// This is a SEPARATE query from [`first_unlowered_operator`] rather than a new
/// case inside it, for two reasons. It is RHS-only — a `D` on an equation's
/// left-hand side is what makes the equation differential and must never be
/// reported — and `first_unlowered_operator` is reached only from behind the
/// `independent_variables != ["t"]` guard in both compile paths, so a 0-D
/// document (which is exactly where `dxdt ~ D(x, t)` is written) never passes
/// through it at all.
///
/// The returned string is the differentiated operand rendered for the
/// diagnostic, not a variable that can be looked up: `D` of a compound has no
/// name, so it renders as the expression.
pub fn first_unresolved_rhs_time_derivative(flat: &FlattenedSystem) -> Option<String> {
    first_unresolved_rhs_time_derivative_in(&flat.equations)
}

/// [`first_unresolved_rhs_time_derivative`] over a bare equation list.
///
/// The array runtime's SINGLE-MODEL entry point (`ArrayCompiled::from_file` →
/// `from_model_owned_with_arrays`) deliberately never flattens — it exists so a
/// large expanded discretization is not copied through a `FlattenedSystem` — so
/// it needs both the resolution phase and this gate applied to the model's own
/// equations. Same two functions, same order, so the two array routes cannot
/// answer a document differently.
pub(crate) fn first_unresolved_rhs_time_derivative_in(equations: &[Equation]) -> Option<String> {
    for eq in equations {
        if let Some(target) = first_rhs_time_derivative(&eq.rhs) {
            return Some(target);
        }
    }
    None
}

/// The operand of the first structural `D` anywhere inside `expr`, rendered.
fn first_rhs_time_derivative(expr: &Expr) -> Option<String> {
    let Expr::Operator(node) = expr else {
        return None;
    };
    if is_structural_time_derivative(node) {
        return Some(match &node.args[0] {
            Expr::Variable(name) => name.clone(),
            other => format!("{other}"),
        });
    }
    let mut found: Option<String> = None;
    node.for_each_child(&mut |child| {
        if found.is_none() {
            found = first_rhs_time_derivative(child);
        }
    });
    found
}

/// Phase 5d of [`flatten`]: the provider-served loaded fields
/// (esm-spec §8.5; esm-libraries-spec §4.7.5 step 4 `loader_fields`).
///
/// One descriptor per flattened PARAMETER carrying a `data`-kind `update`, in
/// the document order of `parameters`. `cadence` follows the source-seeded
/// refinement of CONFORMANCE_SPEC §5.7.2: a source WITH a `temporal` block is
/// time-varying (`"discrete"`), one without it is read once (`"const"`).
fn collect_loader_fields(
    file: &EsmFile,
    parameters: &IndexMap<String, ModelVariable>,
) -> Vec<LoaderField> {
    let mut out = Vec::new();
    for (name, var) in parameters {
        let Some(spec) = &var.update else { continue };
        let rules: &[crate::types::ParameterUpdate] = match spec {
            crate::types::ParameterUpdateSpec::Single(rule) => std::slice::from_ref(rule),
            crate::types::ParameterUpdateSpec::Several(rules) => rules,
        };
        for rule in rules {
            let Some(source) = rule.data_source() else {
                continue;
            };
            let Some(binding) = rule.value().and_then(|v| v.from.as_ref()) else {
                continue;
            };
            let has_temporal = file
                .data_sources
                .as_ref()
                .and_then(|ds| ds.get(source))
                .is_some_and(|ds| ds.temporal.is_some());
            out.push(LoaderField {
                name: name.clone(),
                owner: name
                    .rsplit_once('.')
                    .map(|(owner, _)| owner.to_string())
                    .unwrap_or_default(),
                source: source.to_string(),
                file_variable: binding.file_variable.clone(),
                cadence: if has_temporal { "discrete" } else { "const" }.to_string(),
            });
            break; // one parameter is fed by one source
        }
    }
    out
}

/// Phase 1 of [`flatten`]: build one [`SystemBlock`] per component — models
/// first (spec §4.7.5 step 2), then reaction systems lowered to ODE
/// equations — each with dot-namespaced variables and equations. Within each
/// kind, components keep the order the document declares them
/// (esm-libraries-spec §4.7.5 step 4, "Ordering"). Returns the contributing
/// system names (provenance) alongside the blocks.
fn collect_component_systems(
    file: &EsmFile,
) -> Result<(Vec<String>, Vec<SystemBlock>), FlattenError> {
    let mut source_systems = Vec::new();
    let mut per_system: Vec<SystemBlock> = Vec::new();

    // Models first (spec §4.7.5 step 2), in the order the DOCUMENT declares
    // them (esm-libraries-spec §4.7.5 step 4, "Ordering"): key order is
    // observable in the flattened parameter vector, so it is never sorted.
    if let Some(models) = &file.models {
        for (name, model) in models {
            let block = build_model_block(name, model)?;
            source_systems.push(name.clone());
            per_system.push(block);
        }
    }

    // Reaction systems next — lowered to ODE equations then namespaced.
    if let Some(rsystems) = &file.reaction_systems {
        for (name, rs) in rsystems {
            let block = build_reaction_block(name, rs)?;
            source_systems.push(name.clone());
            per_system.push(block);
        }
    }

    Ok((source_systems, per_system))
}

/// Phase 3 of [`flatten`]: apply the file's coupling entries in declaration
/// order (`operator_compose`, `couple`, `variable_map` — §4.7.1–§4.7.4),
/// mutating the per-system blocks. Returns the human-readable descriptions of
/// the rules applied, in order, for [`FlattenMetadata`].
/// What [`apply_coupling_entries`] hands back: three parallel results of the one
/// pass, named rather than positional so the call site cannot transpose the two
/// name collections — they are both string collections keyed on the same
/// vocabulary and mean quite different things.
struct CouplingOutcome {
    /// Human-readable descriptions of the rules applied, in order.
    rules_applied: Vec<String>,
    /// Every state spelling an `operator_compose` renaming match DELETED,
    /// mapped onto the survivor it was folded into (issue #230). A CONSUMER
    /// map: it says where a name went.
    merged_variable_renames: IndexMap<String, String>,
    /// Every name a coupling rule rewrote OUT of the equations, for the
    /// registry guard alone. Not a consumer map: it says a name is GONE, not
    /// where it went.
    coupling_rewritten_names: BTreeSet<String>,
}

fn apply_coupling_entries(
    file: &EsmFile,
    per_system: &mut Vec<SystemBlock>,
) -> Result<CouplingOutcome, FlattenError> {
    let mut coupling_rules_applied = Vec::new();
    // Every name a coupling rule rewrote OUT of the equations, for the registry
    // guard alone (see [`FlattenMetadata::coupling_rewritten_names`]). Julia
    // calls this local `map_rewritten_names`.
    let mut coupling_rewritten_names: BTreeSet<String> = BTreeSet::new();
    // The document-wide merge map: every state spelling an `operator_compose`
    // renaming match has DELETED, mapped onto the survivor (issue #230). It
    // accumulates across the rank-0 pass and is applied to the by-name endpoints
    // of every entry that has not run yet, so an entry naming a merged-away
    // spelling resolves to the survivor instead of dangling.
    let mut merged_renames: IndexMap<String, String> = IndexMap::new();
    let Some(entries) = &file.coupling else {
        return Ok(CouplingOutcome {
            rules_applied: coupling_rules_applied,
            merged_variable_renames: merged_renames,
            coupling_rewritten_names,
        });
    };

    // BY KIND, not by array position. §4.7.1 runs before §4.7.2 and §4.7.3 so
    // that placeholder expansion and the RHS merge happen before a `couple`
    // connector term or a `variable_map` substitution rewrites the dependent
    // variable names out from under them — the operator terms belong to the
    // ODE the component authored, and folding a connector term in first would
    // stack the two contributions in the wrong order (a visible divergence:
    // `advanced_coupling` declares `couple` first and `operator_compose`
    // third, and the oracle still emits the transport terms ahead of the
    // deposition sink). Within a kind, array order is preserved.
    //
    // `coupling_rules_applied` stays in DECLARATION order: it is provenance
    // for the document as authored, not a trace of the application schedule.
    let kind_rank = |entry: &CouplingEntry| match entry {
        CouplingEntry::OperatorCompose { .. } => 0,
        CouplingEntry::Couple { .. } => 1,
        _ => 2,
    };
    let mut descriptions: Vec<Option<String>> = vec![None; entries.len()];
    for rank in 0..=2 {
        for (i, entry) in entries.iter().enumerate() {
            if kind_rank(entry) != rank {
                continue;
            }
            let mut one = Vec::new();
            apply_coupling_entry(
                entry,
                i,
                per_system,
                &mut one,
                &mut merged_renames,
                &mut coupling_rewritten_names,
            )?;
            descriptions[i] = one.into_iter().next();
        }
    }
    coupling_rules_applied.extend(descriptions.into_iter().flatten());
    // Every merged-away spelling is a rewritten name too: `retarget_merged_names`
    // deleted it from the tables and rewrote every equation off it, exactly as a
    // NAMED `variable_map` transform does to its `to` (Julia's
    // `union!(map_rewritten_names, keys(merged_renames))`).
    coupling_rewritten_names.extend(merged_renames.keys().cloned());
    Ok(CouplingOutcome {
        rules_applied: coupling_rules_applied,
        merged_variable_renames: merged_renames,
        coupling_rewritten_names,
    })
}

/// Fold a merge's fresh rename map into the running document-wide one.
///
/// Renames CHAIN: if an earlier `operator_compose` merged `B.x` onto `A.x` and a
/// later one merges `A.x` onto `C.x`, a document that still names `B.x` must
/// land on `C.x` — so the accumulated map's VALUES are retargeted through the
/// new map before the new pairs are added.
fn compose_renames(acc: &mut IndexMap<String, String>, next: IndexMap<String, String>) {
    for survivor in acc.values_mut() {
        if let Some(further) = next.get(survivor.as_str()) {
            *survivor = further.clone();
        }
    }
    acc.extend(next);
}

/// The survivor `name` resolves to, or `name` itself.
fn resolve_renamed<'a>(name: &'a str, renames: &'a IndexMap<String, String>) -> &'a str {
    renames.get(name).map(String::as_str).unwrap_or(name)
}

/// Rewrite a `couple` connector's by-name endpoints off names an earlier merge
/// deleted (issue #230).
///
/// `operator_compose` entries run before `couple` and `variable_map` (§4.7.5
/// step 3 ordering) and a renaming merge DELETES the spelling it consumed. The
/// document-wide retarget ([`retarget_merged_names`]) reaches equation ASTs only
/// — a connector's `from` / `to` is a plain scoped-reference STRING carried on
/// the entry, so an entry that has not run yet can still name a state that has
/// moved, and the connector then matches nothing and is dropped in SILENCE.
///
/// Returns a rewritten CLONE (borrowing the original when nothing changes), so
/// the source document keeps what its author wrote.
fn retarget_connector<'a>(
    connector: &'a serde_json::Value,
    renames: &IndexMap<String, String>,
) -> std::borrow::Cow<'a, serde_json::Value> {
    use std::borrow::Cow;
    if renames.is_empty() {
        return Cow::Borrowed(connector);
    }
    let Some(eqs) = connector.get("equations").and_then(|e| e.as_array()) else {
        return Cow::Borrowed(connector);
    };
    let subs: HashMap<String, Expr> = renames
        .iter()
        .map(|(from, to)| (from.clone(), Expr::Variable(to.clone())))
        .collect();
    let mut changed = false;
    let mut out_eqs = Vec::with_capacity(eqs.len());
    for eq in eqs {
        let mut eq = eq.clone();
        if let Some(obj) = eq.as_object_mut() {
            for side in ["from", "to"] {
                let Some(name) = obj.get(side).and_then(|v| v.as_str()) else {
                    continue;
                };
                let survivor = resolve_renamed(name, renames);
                if survivor != name {
                    let survivor = survivor.to_string();
                    obj.insert(side.to_string(), serde_json::Value::String(survivor));
                    changed = true;
                }
            }
            // The connector's own expression is carried on the ENTRY too, so
            // the equation-AST retarget never saw it either. `rename_names`
            // rather than `substitute`, so a `join` inside it gets the same
            // plain-string coverage every other retarget site does.
            if let Some(raw) = obj.get("expression")
                && let Ok(expr) = serde_json::from_value::<Expr>(raw.clone())
            {
                let rewritten = rename_names(&expr, &subs, renames);
                if rewritten != expr
                    && let Ok(v) = serde_json::to_value(&rewritten)
                {
                    obj.insert("expression".to_string(), v);
                    changed = true;
                }
            }
        }
        out_eqs.push(eq);
    }
    if !changed {
        return Cow::Borrowed(connector);
    }
    let mut out = connector.clone();
    if let Some(obj) = out.as_object_mut() {
        obj.insert("equations".to_string(), serde_json::Value::Array(out_eqs));
    }
    Cow::Owned(out)
}

/// Phase 4 of [`flatten`]: conflict detection after coupling — every pair of
/// equations with the same D(X, t) LHS across systems that were NOT jointly
/// named in an `operator_compose` entry is a
/// [`FlattenError::ConflictingDerivative`].
fn detect_conflicts(file: &EsmFile, per_system: &[SystemBlock]) -> Result<(), FlattenError> {
    let operator_compose_systems: Vec<Vec<String>> = file
        .coupling
        .as_ref()
        .map(|entries| {
            entries
                .iter()
                .filter_map(|e| match e {
                    CouplingEntry::OperatorCompose { systems, .. } => Some(systems.clone()),
                    _ => None,
                })
                .collect()
        })
        .unwrap_or_default();

    let mut lhs_targets: IndexMap<String, Vec<String>> = IndexMap::new();
    for block in per_system {
        for FlatEq { eq, .. } in &block.equations {
            if let Some(dep) = extract_ddt_dependent(&eq.lhs) {
                lhs_targets.entry(dep).or_default().push(block.name.clone());
            }
        }
    }

    let mut conflicting_species: Vec<String> = Vec::new();
    for (species, owning_systems) in &lhs_targets {
        if owning_systems.len() < 2 {
            continue;
        }
        let was_composed = operator_compose_systems
            .iter()
            .any(|compose_systems| owning_systems.iter().all(|s| compose_systems.contains(s)));
        if !was_composed {
            conflicting_species.push(species.clone());
        }
    }
    if !conflicting_species.is_empty() {
        conflicting_species.sort();
        conflicting_species.dedup();
        return Err(FlattenError::ConflictingDerivative {
            species: conflicting_species,
        });
    }
    Ok(())
}

/// The [`FlattenedSystem`]-shaped accumulation produced by phase 5
/// ([`assemble_output`]) and refined by the post-collection passes
/// ([`apply_variable_map_removals`], [`maybe_apply_pointwise_lift`],
/// [`resolve_rhs_time_derivatives`], [`extract_field_ics`]).
struct AssembledParts {
    state_variables: IndexMap<String, ModelVariable>,
    parameters: IndexMap<String, ModelVariable>,
    observed_variables: IndexMap<String, ModelVariable>,
    field_ics: Vec<(String, Expr)>,
    equations: Vec<FlatEq>,
    continuous_events: Vec<ContinuousEvent>,
    discrete_events: Vec<DiscreteEvent>,
    lifted_shapes: IndexMap<String, Vec<i64>>,
}

/// Phase 5 of [`flatten`]: merge the per-system blocks (in block order) into
/// the final variable maps, equation list, and event lists.
///
/// `ic` equations stay in `equations` here; [`extract_field_ics`] classifies
/// them out after the right-hand-side `D` resolution has run over them.
fn assemble_output(per_system: Vec<SystemBlock>) -> AssembledParts {
    let mut parts = AssembledParts {
        state_variables: IndexMap::new(),
        parameters: IndexMap::new(),
        observed_variables: IndexMap::new(),
        field_ics: Vec::new(),
        equations: Vec::new(),
        continuous_events: Vec::new(),
        discrete_events: Vec::new(),
        lifted_shapes: IndexMap::new(),
    };

    for block in per_system {
        for (name, var) in block.state_vars {
            parts.state_variables.insert(name, var);
        }
        for (name, var) in block.parameters {
            parts.parameters.insert(name, var);
        }
        for (name, var) in block.observed_vars {
            parts.observed_variables.insert(name, var);
        }
        parts.equations.extend(block.equations);
        parts.continuous_events.extend(block.continuous_events);
        parts.discrete_events.extend(block.discrete_events);
    }
    parts
}

/// Phase 5b″ of [`flatten`]: classify scoped-reference / array `ic` equations
/// (esm-spec §11.4.1) out of the ordinary equation list into `field_ics`, as
/// `(target_state, rhs)` — the downstream simulator folds them into `u0` from
/// the data-Provider seam rather than treating them as state ODEs.
fn extract_field_ics(parts: &mut AssembledParts) {
    // An `ic` equation's contribution list leaves with it: `field_ics` carries
    // none (esm-libraries-spec §4.7.5).
    let mut kept = Vec::with_capacity(parts.equations.len());
    for fe in std::mem::take(&mut parts.equations) {
        if let Some(target) = extract_ic_target(&fe.eq.lhs) {
            parts.field_ics.push((target, fe.eq.rhs));
        } else {
            kept.push(fe);
        }
    }
    parts.equations = kept;
}

/// Phase 5a of [`flatten`]: apply post-collection `variable_map` parameter
/// removals. A `param_to_var` that binds a LOADED field (its producer's
/// owning system is a top-level `data_sources` entry) onto a grid-shaped
/// consumer parameter records the producer name + rank so the pointwise lift
/// indexes the loaded field per grid cell (esm-spec §11.5 "BCs from data").
/// The loaded producer is NOT added to `parameters`: it is served at runtime
/// through the data-Provider forcing seam, not as a scalar parameter (which
/// the array evaluator would otherwise resolve ahead of the forcing buffer).
/// Returns the loaded-producer name → rank map consumed by
/// [`maybe_apply_pointwise_lift`].
/// The grid-shaped fields fed from OUTSIDE the model — every discrete
/// parameter with a non-empty declared `shape`, keyed by its flattened name and
/// mapped to its rank.
///
/// This is the esm 1.0.0 successor of [`apply_variable_map_removals`]'s
/// `param_to_var` result. Before 1.0.0 a loaded field arrived as a coupling
/// edge from a loader component to a model parameter, and that EDGE is what
/// told the pointwise lift which operands were grid-shaped external fields.
/// The edge is gone: the loaded field IS a parameter carrying an `update` that
/// names its source (esm-spec §8.5). The same fact is therefore read off the
/// declaration — a discrete parameter with a shape — instead of off a coupling
/// entry, and the lift indexes it per cell exactly as before. Without this a
/// grid-shaped wind field stays a whole ARRAY inside a per-cell expression and
/// the tendency evaluates to `NaN`.
fn source_fed_producers(parts: &AssembledParts) -> HashMap<String, usize> {
    let class = flattened_classification(parts);
    parts
        .parameters
        .iter()
        .filter(|(name, _)| class.is_discrete_parameter(name))
        .filter_map(|(name, var)| {
            var.shape
                .as_ref()
                .filter(|s| !s.is_empty())
                .map(|s| (name.clone(), s.len()))
        })
        .collect()
}

/// The esm-spec §6.3.1 classification of the FLATTENED system.
///
/// Re-derived over the flattened maps and equations rather than lifted from the
/// per-component answers, because flattening moves the ground under it:
/// `operator_compose` merges two RHSs into one equation, `variable_map` deletes
/// a parameter and promotes a variable in its place, and the pointwise lift
/// rewrites a scalar state ODE into a `faq`. Every membership decision
/// is delegated to [`crate::classification`] — the binding's only sanctioned
/// answer to these questions — so no `update.kind == "wiener"` test is spelled
/// here. Mirrors Python's `_classification_view` / `_classify_flattened`.
fn flattened_classification(parts: &AssembledParts) -> crate::classification::Classification {
    let mut view: IndexMap<String, ModelVariable> = IndexMap::new();
    for (name, var) in &parts.state_variables {
        view.insert(name.clone(), var.clone());
    }
    for (name, var) in &parts.observed_variables {
        view.entry(name.clone()).or_insert_with(|| var.clone());
    }
    for (name, var) in &parts.parameters {
        view.entry(name.clone()).or_insert_with(|| var.clone());
    }
    let equations: Vec<Equation> = parts.equations.iter().map(|fe| fe.eq.clone()).collect();
    crate::classification::Classification::from_parts(&view, &equations)
}

/// Select `names` out of `maps`, keeping each map's DOCUMENT order.
///
/// The classification accessors return lexicographically sorted name lists — a
/// set-valued answer spelled as a list. esm-libraries-spec §4.7.5 step 4
/// requires document order of every map on the flattened system, so membership
/// comes from the accessor and POSITION comes from the already-document-ordered
/// map being filtered. Sorting here instead would be observable.
fn in_document_order(
    names: &[String],
    maps: &[&IndexMap<String, ModelVariable>],
) -> IndexMap<String, ModelVariable> {
    let wanted: HashSet<&str> = names.iter().map(String::as_str).collect();
    let mut out = IndexMap::new();
    for m in maps {
        for (name, var) in *m {
            if wanted.contains(name.as_str()) && !out.contains_key(name) {
                out.insert(name.clone(), var.clone());
            }
        }
    }
    out
}

fn apply_variable_map_removals(
    file: &EsmFile,
    parts: &mut AssembledParts,
    merged_renames: &IndexMap<String, String>,
) -> HashMap<String, usize> {
    let loader_names: HashSet<String> = file
        .data_sources
        .as_ref()
        .map(|dl| dl.keys().cloned().collect())
        .unwrap_or_default();
    let mut loaded_producers: HashMap<String, usize> = HashMap::new();
    if let Some(entries) = &file.coupling {
        for (index, entry) in entries.iter().enumerate() {
            let CouplingEntry::VariableMap {
                from,
                to,
                transform,
                ..
            } = entry
            else {
                continue;
            };
            match transform {
                VariableMapTransform::Named(name)
                    if matches!(name.as_str(), "param_to_var" | "conversion_factor") =>
                {
                    let consumer_shape_rank = parts
                        .parameters
                        .get(to)
                        .and_then(|v| v.shape.as_ref())
                        .map(|s| s.len())
                        .filter(|r| *r > 0);
                    parts.parameters.shift_remove(to);
                    let from_owner = from.split('.').next().unwrap_or("");
                    if let Some(rank) = consumer_shape_rank
                        && loader_names.contains(from_owner)
                        && !parts.parameters.contains_key(from)
                    {
                        loaded_producers.insert(from.clone(), rank);
                    }
                }
                // Expression transform (esm-spec §10.4): the entry binds the
                // target to a DERIVED value. Remove the `to` parameter and
                // introduce in its place an observed variable — same name,
                // units, shape, description — whose defining expression is the
                // transform VERBATIM (its references are, by contract, already
                // fully scoped, so no namespacing is applied). References to
                // `to` in the equations are left intact: they now resolve to
                // the observed, exactly as if the author had declared it.
                VariableMapTransform::Expression(node) => {
                    let removed = parts.parameters.shift_remove(to);
                    let (units, shape, description) = removed
                        .map(|p| (p.units, p.shape, p.description))
                        .unwrap_or((None, None, None));
                    parts.observed_variables.insert(
                        to.clone(),
                        ModelVariable {
                            var_type: VariableType::Unknown,
                            units,
                            description,
                            shape,
                            ..Default::default()
                        },
                    );
                    // The DEFINITION is an equation with a bare-variable LHS —
                    // esm 1.0.0 has no `expression` field on a variable, and it
                    // is that equation form that makes `to` an observed unknown
                    // (esm-spec §6.3.1).
                    // …off the names a merge deleted. This install happens in
                    // ASSEMBLY, after `retarget_merged_names` has run over the
                    // equation pool, so the document-wide retarget never sees
                    // this node and the authored spelling would survive here
                    // alone (CONFORMANCE_SPEC §5.35). Renaming at the INSTALL
                    // rather than on the entry keeps the §10.4 `contains` check
                    // above comparing the authored `from` against the authored
                    // node, which is what it is for.
                    let subs: HashMap<String, Expr> = merged_renames
                        .iter()
                        .map(|(gone, survivor)| (gone.clone(), Expr::Variable(survivor.clone())))
                        .collect();
                    let rhs = rename_names(&Expr::operator(node.clone()), &subs, merged_renames);
                    // The coupling entry wrote this definition itself.
                    parts.equations.push(FlatEq::authored(
                        Equation {
                            comment: None,
                            lhs: Expr::Variable(to.clone()),
                            rhs,
                        },
                        TermOrigin::Coupling { coupling: index },
                    ));
                }
                VariableMapTransform::Named(_) => {}
            }
        }
    }
    loaded_producers
}

/// Phase 5b of [`flatten`]: pointwise spatial lift trigger (esm-spec §10.5).
/// `operator_compose` has merged each reaction/model state ODE with the
/// spatial operator's advection makearray; array-ify those merged equations
/// onto the operator's grid so the lifted reaction network runs pointwise.
/// No-op unless an `operator_compose` entry declares `lifting: "pointwise"`
/// and a merged equation carries an operator makearray.
fn maybe_apply_pointwise_lift(
    file: &EsmFile,
    parts: &mut AssembledParts,
    loaded_producers: &HashMap<String, usize>,
) -> Result<(), FlattenError> {
    let pointwise = file
        .coupling
        .as_ref()
        .map(|entries| {
            entries.iter().any(|e| {
                matches!(e, CouplingEntry::OperatorCompose { lifting: Some(l), .. } if l == "pointwise")
            })
        })
        .unwrap_or(false);
    if pointwise {
        apply_pointwise_lift(
            &mut parts.equations,
            &mut parts.lifted_shapes,
            loaded_producers,
        )?;
    }
    Ok(())
}

/// Is `node` the STRUCTURAL time derivative — `D` with `wrt: "t"` or no `wrt`
/// at all (esm-spec §4.2: an absent `wrt` MEANS `t`), applied to a single
/// operand?
///
/// The complement of [`crate::op_registry::is_rewrite_target_derivative`],
/// which is the SPATIAL tier: a `D` whose `wrt` names an axis, lowered to a
/// stencil by a discretization rule and never evaluated.
fn is_structural_time_derivative(node: &ExpressionNode) -> bool {
    node.op == "D"
        && node.args.len() == 1
        && !crate::op_registry::is_rewrite_target_derivative(node)
}

/// Phase 5b′ of [`flatten`]: rewrite every right-hand-side STRUCTURAL time
/// derivative into the tendency the flattened system already defines for it.
///
/// `D` on an equation's LEFT-hand side is structural: it is what makes the
/// equation differential, and system assembly consumes it. On a RIGHT-hand
/// side there was no consumer at all, and the three evaluators each answered
/// `D(anything) = 0` "for parity" with one another — a silent wrong answer
/// rather than a missing feature, which is what made an observed written
/// `dxdt ~ D(x, t)` (esm-spec §6.6.2, the instantaneous-derivative test shape)
/// read as exactly `0` and grade its inline test against a configuration the
/// model never computed.
///
/// The value is not a runner's to invent: everything it needs is already in
/// this system. `D(x, t)` over a state is `x`'s own `D(x)/dt ~ f`; `D(y, t)`
/// over an OBSERVED is the total derivative of `y`'s defining equation, which
/// is that equation's right-hand side differentiated by the same rule, one
/// level down. So the whole rule is one recursive walk, `deriv` below, and it
/// runs HERE — the layer that qualifies names, applies coupling and lowers a
/// reaction network to its mass-action ODEs — so no evaluator ever meets a
/// right-hand-side `D` and every `FlattenedSystem` consumer answers alike by
/// construction. It is what lets `D(Chem.O3, t)` in a sibling model resolve to
/// the mechanism's tendency (esm-spec §7.4) with no runner learning anything
/// about reactions.
///
/// What `deriv` covers, and nothing else:
///
/// * a STATE (a name carrying `D(x)/dt ~ f`) — its tendency, with any `D`
///   inside that tendency resolved in turn, so a chained
///   `D(lai)/dt ~ sla · D(biomass)/dt` terminates in states;
/// * an OBSERVED (a name carrying `y ~ g`) — `deriv(g)`, the chain rule
///   applied by substituting the definition and differentiating it;
/// * a TIME-INVARIANT name (a parameter) and a literal — `0`;
/// * `+`, binary and unary `-`, `neg`, n-ary `*`, and binary `/` — distributed
///   by the ordinary sum, product and quotient rules over the operands'
///   derivatives.
///
/// Every other shape — `^`, a call, a reduction, a nested `D`, a name in no
/// table — resolves to NOTHING and is left exactly as authored, as is any
/// cyclic chain (`active` stops it). Those reach
/// [`first_unresolved_rhs_time_derivative`] and are refused with
/// `unlowered_operator`: §4.2 forbids inventing a value for them, in
/// particular `0`. A SPATIAL `D` is untouched — it is a rewrite target for a
/// discretization rule (§9.6.8) and that gate still owns it — and left-hand
/// sides are never rewritten.
///
/// Returns whether any right-hand side carried a time derivative; when none
/// did, nothing is rewritten and none is left.
pub(crate) fn resolve_rhs_time_derivatives(
    equations: &mut [Equation],
    time_invariant: &HashSet<String>,
) -> bool {
    let Some((carriers, tables)) =
        plan_time_derivative_resolution(equations.iter(), time_invariant)
    else {
        return false;
    };
    let Some(tables) = tables else {
        return true;
    };
    for (eq, carries) in equations.iter_mut().zip(carriers) {
        if carries {
            let mut active = self_defined(&eq.lhs);
            eq.rhs = tables.substitute(&eq.rhs, &mut active);
        }
    }
    true
}

/// Which right-hand sides carry a structural time derivative, and the tables
/// to resolve them against (`None` when the equations define nothing to
/// resolve against). `None` overall when no right-hand side carries one: a
/// document with none keeps its equations untouched rather than being rebuilt
/// through `substitute`.
fn plan_time_derivative_resolution<'e, 'a>(
    equations: impl Iterator<Item = &'e Equation> + Clone,
    time_invariant: &'a HashSet<String>,
) -> Option<(Vec<bool>, Option<DerivTables<'a>>)> {
    let carriers: Vec<bool> = equations
        .clone()
        .map(|eq| contains_time_derivative(&eq.rhs))
        .collect();
    if !carriers.contains(&true) {
        return None;
    }
    Some((carriers, DerivTables::build(equations, time_invariant)))
}

/// [`resolve_rhs_time_derivatives`] over flatten's own equations: the resolved
/// expression replaces the `D` node INSIDE the referencing contribution, which
/// keeps its origins (esm-libraries-spec §4.7.5); the resolved quantity's own
/// contributions are not spliced in.
fn resolve_rhs_time_derivatives_per_contribution(
    equations: &mut [FlatEq],
    time_invariant: &HashSet<String>,
) {
    let Some((carriers, Some(tables))) =
        plan_time_derivative_resolution(equations.iter().map(|fe| &fe.eq), time_invariant)
    else {
        return;
    };
    for (fe, carries) in equations.iter_mut().zip(carriers) {
        if carries {
            let mut active = self_defined(&fe.eq.lhs);
            fe.map_contributions(|e| tables.substitute(e, &mut active));
        }
    }
}

/// The quantity an equation DEFINES, which is not available to substitute into
/// its own right-hand side; seeding `active` with it is what makes
/// `D(x)/dt ~ k·D(x, t)` and `y ~ D(y, t)` terminate as unresolved rather than
/// expand forever.
fn self_defined(lhs: &Expr) -> Vec<String> {
    match lhs {
        Expr::Operator(node) if is_structural_time_derivative(node) => match node.args.first() {
            Some(Expr::Variable(name)) => vec![name.clone()],
            _ => Vec::new(),
        },
        Expr::Variable(name) => vec![name.clone()],
        _ => Vec::new(),
    }
}

/// The tendency and defining equations [`resolve_rhs_time_derivatives`] reads,
/// plus the names whose time derivative is `0`.
struct DerivTables<'a> {
    /// `x` -> the right-hand side of its `D(x)/dt ~ …` equation.
    tendency: HashMap<String, Expr>,
    /// `y` -> the right-hand side of its `y ~ …` defining equation.
    definition: HashMap<String, Expr>,
    /// Names that do not vary with `t` — the flattened system's parameters.
    /// A name in NONE of the three is unresolvable rather than zero: answering
    /// `0` for a name this pass simply does not recognise is the very defect
    /// §4.2 forbids.
    time_invariant: &'a HashSet<String>,
}

impl<'a> DerivTables<'a> {
    /// The tables `equations` define, or `None` when they define nothing to
    /// resolve against.
    fn build<'e>(
        equations: impl IntoIterator<Item = &'e Equation>,
        time_invariant: &'a HashSet<String>,
    ) -> Option<Self> {
        let mut tables = DerivTables {
            tendency: HashMap::new(),
            definition: HashMap::new(),
            time_invariant,
        };
        for eq in equations {
            match &eq.lhs {
                Expr::Operator(node) if is_structural_time_derivative(node) => {
                    if let Some(Expr::Variable(name)) = node.args.first() {
                        tables.tendency.insert(name.clone(), eq.rhs.clone());
                    }
                }
                // A bare-variable LHS is a DEFINING equation — esm-spec §6.3.1's
                // observed / algebraic form. Its right-hand side is what the
                // chain rule differentiates.
                Expr::Variable(name) => {
                    tables.definition.insert(name.clone(), eq.rhs.clone());
                }
                _ => {}
            }
        }
        (!tables.tendency.is_empty() || !tables.definition.is_empty()).then_some(tables)
    }

    /// Rewrite every structural `D` inside `expr`, leaving the ones `deriv`
    /// cannot answer exactly as authored for the gate to report.
    fn substitute(&self, expr: &Expr, active: &mut Vec<String>) -> Expr {
        let Expr::Operator(node) = expr else {
            return expr.clone();
        };
        if is_structural_time_derivative(node) {
            return match node.args.first().and_then(|a| self.deriv(a, active)) {
                Some(out) => out,
                None => expr.clone(),
            };
        }
        Expr::operator(node.map_children(&mut |child| self.substitute(child, active)))
    }

    /// d/dt of `expr`, or `None` when this format does not define it.
    fn deriv(&self, expr: &Expr, active: &mut Vec<String>) -> Option<Expr> {
        match expr {
            Expr::Integer(_) | Expr::Number(_) => Some(zero()),
            Expr::Variable(name) => {
                if active.iter().any(|n| n == name) {
                    // A cycle. Stop, and let the gate name it.
                    return None;
                }
                if let Some(f) = self.tendency.get(name) {
                    let f = f.clone();
                    active.push(name.clone());
                    let out = self.substitute(&f, active);
                    active.pop();
                    Some(out)
                } else if let Some(g) = self.definition.get(name) {
                    let g = g.clone();
                    active.push(name.clone());
                    let out = self.deriv(&g, active);
                    active.pop();
                    out
                } else if self.time_invariant.contains(name) {
                    Some(zero())
                } else {
                    None
                }
            }
            Expr::Operator(node) => self.deriv_op(node, active),
        }
    }

    /// [`Self::deriv`] over an operator node: the closed arithmetic set.
    fn deriv_op(&self, node: &ExpressionNode, active: &mut Vec<String>) -> Option<Expr> {
        let d = |a: &Expr, active: &mut Vec<String>| self.deriv(a, active);
        match node.op.as_str() {
            "+" => {
                let mut terms = Vec::with_capacity(node.args.len());
                for a in &node.args {
                    terms.push(d(a, active)?);
                }
                Some(sum(terms))
            }
            "-" => match node.args.len() {
                1 => Some(negate(d(&node.args[0], active)?)),
                2 => {
                    let a = d(&node.args[0], active)?;
                    let b = d(&node.args[1], active)?;
                    Some(difference(a, b))
                }
                _ => None,
            },
            "neg" if node.args.len() == 1 => Some(negate(d(&node.args[0], active)?)),
            // Product rule over an n-ary `*`: one term per factor, that
            // factor differentiated and the others left alone.
            "*" => {
                let mut terms = Vec::with_capacity(node.args.len());
                for (i, a) in node.args.iter().enumerate() {
                    let da = d(a, active)?;
                    if is_zero(&da) {
                        continue;
                    }
                    let mut factors = vec![da];
                    for (j, b) in node.args.iter().enumerate() {
                        if i != j {
                            factors.push(b.clone());
                        }
                    }
                    terms.push(product(factors));
                }
                Some(sum(terms))
            }
            "/" if node.args.len() == 2 => {
                let (u, v) = (&node.args[0], &node.args[1]);
                let du = d(u, active)?;
                let dv = d(v, active)?;
                if is_zero(&dv) {
                    // v is constant in t: (u/v)' = u'/v, which keeps the
                    // expression small in the common `D(x, t)/c` shape.
                    return Some(quotient(du, v.clone()));
                }
                let num = difference(product(vec![du, v.clone()]), product(vec![u.clone(), dv]));
                Some(quotient(num, product(vec![v.clone(), v.clone()])))
            }
            _ => None,
        }
    }
}

/// Does `expr` carry a structural `D` anywhere?
fn contains_time_derivative(expr: &Expr) -> bool {
    let Expr::Operator(node) = expr else {
        return false;
    };
    is_structural_time_derivative(node) || node.any_child(&mut contains_time_derivative)
}

// ---------------------------------------------------------------------------
// Small folding constructors for the derivative expressions.
//
// Folding is not cosmetic here. A parameter and a literal both differentiate
// to `0`, so an unfolded product rule would emit `0*x + 2*0` shapes throughout
// and `D(k, t)` would be a sum of zeros rather than the literal `0` that a
// downstream classifier can recognise as constant.
// ---------------------------------------------------------------------------

fn zero() -> Expr {
    Expr::Number(0.0)
}

fn is_zero(e: &Expr) -> bool {
    matches!(e, Expr::Number(v) if *v == 0.0) || matches!(e, Expr::Integer(0))
}

fn is_one(e: &Expr) -> bool {
    matches!(e, Expr::Number(v) if *v == 1.0) || matches!(e, Expr::Integer(1))
}

fn node(op: &str, args: Vec<Expr>) -> Expr {
    Expr::operator(ExpressionNode {
        op: op.to_string(),
        args,
        ..Default::default()
    })
}

fn sum(terms: Vec<Expr>) -> Expr {
    let mut kept: Vec<Expr> = terms.into_iter().filter(|t| !is_zero(t)).collect();
    match kept.len() {
        0 => zero(),
        1 => kept.pop().expect("len 1"),
        _ => node("+", kept),
    }
}

fn difference(a: Expr, b: Expr) -> Expr {
    if is_zero(&b) {
        return a;
    }
    if is_zero(&a) {
        return negate(b);
    }
    node("-", vec![a, b])
}

fn negate(a: Expr) -> Expr {
    match &a {
        _ if is_zero(&a) => zero(),
        Expr::Number(v) => Expr::Number(-v),
        Expr::Integer(v) => Expr::Integer(-v),
        // Unary `-`, not `neg`: both spell negation, but the scalar
        // interpreter has an arm for the first and (until #220) none for the
        // second, so emitting `neg` here would be a NaN on one backend.
        _ => node("-", vec![a]),
    }
}

fn product(factors: Vec<Expr>) -> Expr {
    if factors.iter().any(is_zero) {
        return zero();
    }
    let mut kept: Vec<Expr> = factors.into_iter().filter(|f| !is_one(f)).collect();
    match kept.len() {
        0 => Expr::Number(1.0),
        1 => kept.pop().expect("len 1"),
        _ => node("*", kept),
    }
}

fn quotient(a: Expr, b: Expr) -> Expr {
    if is_zero(&a) {
        return zero();
    }
    node("/", vec![a, b])
}

/// Flatten a single [`Model`] as a convenience wrapper around [`flatten`].
///
/// The model is wrapped in a synthetic single-component [`EsmFile`] under the
/// name `"model"` (or its declared `name` field if present) and run through
/// the full pipeline — so the result is still dot-namespaced and has real
/// [`FlattenMetadata`]. Use this when you want the spec-compliant output for
/// a standalone component without hand-building an [`EsmFile`].
pub fn flatten_model(model: &Model) -> Result<FlattenedSystem, FlattenError> {
    let system_name = model.name.clone().unwrap_or_else(|| "model".to_string());

    let mut models = IndexMap::new();
    models.insert(system_name, model.clone());

    // A synthesized single-system view: it declares no templates and no
    // metaparameters of its own (the source document's survive on IT).
    let file = EsmFile {
        models: Some(models),
        ..Default::default()
    };

    flatten(&file)
}

// ============================================================================
// Internal plumbing
// ============================================================================

/// Per-system intermediate representation built during phase 1. Carries the
/// namespaced variables, parameters, events, and equations for a single
/// component so that coupling can operate on structured data rather than
/// strings.
struct SystemBlock {
    name: String,
    state_vars: IndexMap<String, ModelVariable>,
    /// EVERY parameter of the component, in declaration order and of every
    /// cadence. The wiener / discrete subsets are re-derived over the FLATTENED
    /// system in [`flattened_classification`]; they are not carved out here, because
    /// esm-spec §6.3.1's four sets partition `parameters` rather than sitting
    /// beside it.
    parameters: IndexMap<String, ModelVariable>,
    observed_vars: IndexMap<String, ModelVariable>,
    /// The equations this block holds, each with its contribution list. Which
    /// block an equation sits in is its slot owner (§4.7.1 step 4), not its
    /// provenance: a reattributed equation moves here with its list.
    equations: Vec<FlatEq>,
    continuous_events: Vec<ContinuousEvent>,
    discrete_events: Vec<DiscreteEvent>,
}

fn build_model_block(system_name: &str, model: &Model) -> Result<SystemBlock, FlattenError> {
    let mut state_vars = IndexMap::new();
    let mut parameters = IndexMap::new();
    let mut observed_vars = IndexMap::new();

    // The component's own declared names — the gate for namespacing the
    // plain-string references a `join` clause carries (§5.5.6).
    // Mirrors Julia `_collect_model!`'s `local_names`.
    //
    // From esm 1.0.0 a data source can no longer be mounted as a SUBSYSTEM
    // (RFC unified-variable-model D2: a source is not a component), so there
    // are no loader-subsystem keys to add here and no loader observeds to
    // synthesise. A model reads external data through a PARAMETER whose
    // `update` names the source, which lands in `parameters` below like any
    // other parameter.
    //
    // A model's SUBSYSTEM keys join the gate: a reference rooted at one of
    // them (`Photochemistry.NO2_photo` written inside the parent) is
    // subsystem-LOCAL, not an already-absolute cross-component reference, and
    // must be lifted to the lowered subsystem name `<parent>.<sub>.<var>`.
    // Mirrors the Python oracle's `sub_keys` / `locals_` in `_collect_model`.
    let sub_keys: HashSet<String> = model
        .subsystems
        .as_ref()
        .map(|subs| subs.keys().cloned().collect())
        .unwrap_or_default();
    let locals: HashSet<String> = model
        .variables
        .keys()
        .cloned()
        .chain(sub_keys.iter().cloned())
        .collect();

    // Which unknowns are ODE states and which are observed is DERIVED from
    // this model's equations (esm-spec §6.3.1), once, before namespacing.
    let class = crate::classification::Classification::of(model);

    // DOCUMENT ORDER (esm-libraries-spec §4.7.5 step 4, "Ordering"): the
    // component's variables in the order the component declares them. A
    // parameter vector is positional, so lexicographic sorting here would be
    // observable — and non-conforming.
    for (var_name, var) in &model.variables {
        let namespaced = format!("{system_name}.{var_name}");
        let mut cloned = var.clone();
        // A parameter's `update` carries Expressions (trigger, value,
        // unit conversion) over the model's own symbols, so they namespace
        // exactly as the equations do.
        cloned.for_each_expression_mut(&mut |expr| {
            *expr = namespace_expr(expr, system_name, &sub_keys, &locals);
        });
        match var.var_type {
            // The two maps are NOT a partition (esm-libraries-spec §4.7.5
            // step 4). `observed_variables` is the §6.3.1 CLASSIFICATION —
            // every unknown an equation DEFINES, at either LHS spelling —
            // while `state_variables` is the SOLVED-FOR VECTOR. So:
            //
            //   * an ODE state and an algebraic unknown are solved for and
            //     nothing defines them by name, so `state_vars` only (the
            //     consumers that integrate this bucket already tolerate an
            //     unknown with no derivative equation — `dae.rs` handles it);
            //   * an INLINEABLE observed (the strict `y ~ f(…)` a bare-variable
            //     LHS defines) is eliminated by substitution and contributes no
            //     buffer, so `observed_vars` only;
            //   * an ARRAYED definition (`y[i] ~ f(i)`) is BOTH. §6.3.1 makes it
            //     observed, and it materializes into a buffer its consumers
            //     index rather than being inlined, so the solver must allocate
            //     it. Filing it in one map or the other loses half of that,
            //     exactly as filing an algebraic unknown outside
            //     `state_variables` did before 45fa534a0.
            VariableType::Unknown => {
                if class.is_observed(var_name) {
                    if !class.is_inlined(var_name) {
                        state_vars.insert(namespaced.clone(), cloned.clone());
                    }
                    observed_vars.insert(namespaced, cloned);
                } else {
                    state_vars.insert(namespaced, cloned);
                }
            }
            // EVERY parameter lands in `parameters`, whatever its cadence.
            // esm-spec §6.3.1: `brownian_parameters` / `discrete_parameters` /
            // `sampled_parameters` / `constant_parameters` PARTITION the
            // parameters, so a wiener-updated entry is a parameter that ALSO
            // appears in the Brownian subset — see [`flattened_classification`].
            VariableType::Parameter => {
                parameters.insert(namespaced, cloned);
            }
        }
    }

    let equations: Vec<FlatEq> = model
        .equations
        .iter()
        .map(|eq| {
            FlatEq::authored(
                Equation {
                    lhs: namespace_expr(&eq.lhs, system_name, &sub_keys, &locals),
                    rhs: namespace_expr(&eq.rhs, system_name, &sub_keys, &locals),
                    comment: eq.comment.clone(),
                },
                TermOrigin::Component {
                    component: system_name.to_string(),
                },
            )
        })
        .collect();

    let continuous_events = model
        .continuous_events
        .clone()
        .unwrap_or_default()
        .into_iter()
        .map(|e| namespace_continuous_event(e, system_name, &sub_keys, &locals))
        .collect();
    let discrete_events = model
        .discrete_events
        .clone()
        .unwrap_or_default()
        .into_iter()
        .map(|e| namespace_discrete_event(e, system_name, &sub_keys, &locals))
        .collect();

    let mut block = SystemBlock {
        name: system_name.to_string(),
        state_vars,
        parameters,
        observed_vars,
        equations,
        continuous_events,
        discrete_events,
    };

    // NESTED SUBSYSTEMS (esm-spec §6.2). A subsystem is an ordinary model
    // mounted under a key, lowered with the compound prefix
    // `<parent>.<key>` and FOLDED INTO the parent block — the flattened
    // system has no separate component for it, exactly as the Python oracle's
    // `_collect_model` recursion + `_ComponentSystem.merge` produce. Rust
    // ignored `subsystems` entirely, which silently dropped every nested
    // variable, parameter, and equation from the flattened system
    // (`tests/scoping/bare_reference_resolution.esm` lost `NO2_photo` and its
    // ODE, leaving an `ic` equation pointing at a state that did not exist).
    //
    // Order matters and is the oracle's: the parent's own tables first, the
    // subsystems' appended in declaration order.
    //
    // EVENTS ARE DELIBERATELY NOT lifted: the document's event view aggregates
    // only TOP-LEVEL components' events (parse.py's `EsmFile.events`), so a
    // subsystem-owned event is not part of the flattened system in any
    // binding. Folding them in here would make Rust the outlier.
    if let Some(subs) = &model.subsystems {
        for (sub_name, sub_value) in subs {
            // A `{ "ref": … }` entry (or any non-model mount) is not a
            // subsystem to lower: reference resolution runs before flattening,
            // so anything still unresolved here contributes nothing.
            let Ok(sub_model) = serde_json::from_value::<Model>(sub_value.clone()) else {
                continue;
            };
            let sub_block = build_model_block(&format!("{system_name}.{sub_name}"), &sub_model)?;
            block.state_vars.extend(sub_block.state_vars);
            block.parameters.extend(sub_block.parameters);
            block.observed_vars.extend(sub_block.observed_vars);
            block.equations.extend(sub_block.equations);
        }
    }

    Ok(block)
}

fn build_reaction_block(
    system_name: &str,
    rs: &ReactionSystem,
) -> Result<SystemBlock, FlattenError> {
    let mut state_vars = IndexMap::new();
    let mut parameters = IndexMap::new();

    // Document order (see [`build_model_block`]).
    for (species_name, species) in &rs.species {
        let namespaced = format!("{system_name}.{species_name}");
        // Reservoir species (`constant: true`, §7.4): held fixed, no ODE
        // (`lower_reactions_to_equations` skips its equation), so it is a
        // PARAMETER whose value is the species' `default`, not a state. It still
        // resolves as a concentration factor wherever a rate law references it.
        // Mirrors the Julia reference (namespacing.jl `_collect_reaction_system!`,
        // `target = sp.constant === true ? params : states`).
        let var = ModelVariable {
            var_type: if species.constant == Some(true) {
                VariableType::Parameter
            } else {
                VariableType::Unknown
            },
            units: species.units.clone(),
            default: species.default.map(InlineValue::Scalar),
            description: species.description.clone(),
            ..Default::default()
        };
        if species.constant == Some(true) {
            parameters.insert(namespaced, var);
        } else {
            state_vars.insert(namespaced, var);
        }
    }

    // The §6.3 value model travels with the parameter, exactly as it does out
    // of [`build_model_block`]. `update` above all: it is the only channel
    // binding a parameter to a data source (esm-spec §5.4), so dropping it here
    // would flatten a data-driven parameter into a constant — and it is the
    // SOLE seed of the DISCRETE cadence class (CONFORMANCE_SPEC §5.7.2).
    for (param_name, param) in &rs.parameters {
        let namespaced = format!("{system_name}.{param_name}");
        parameters.insert(
            namespaced,
            ModelVariable {
                var_type: VariableType::Parameter,
                units: param.units.clone(),
                default: param.default.map(InlineValue::Scalar),
                description: param.description.clone(),
                default_units: param.default_units.clone(),
                shape: param.shape.clone(),
                distribution: param.distribution.clone(),
                update: param.update.clone(),
                ..Default::default()
            },
        );
    }

    // Declared local names for the §5.5.6 `join` gate: a reaction system's
    // species and parameters. Mirrors Julia `_collect_reaction_system!`.
    let locals: HashSet<String> = rs
        .species
        .keys()
        .chain(rs.parameters.keys())
        .cloned()
        .collect();

    let lowered = crate::reactions::lower_reactions_to_equations(&rs.reactions, &rs.species)?;
    let equations = lowered
        .into_iter()
        .map(|eq| {
            FlatEq::authored(
                Equation {
                    lhs: namespace_expr(&eq.lhs, system_name, &HashSet::new(), &locals),
                    rhs: namespace_expr(&eq.rhs, system_name, &HashSet::new(), &locals),
                    comment: eq.comment,
                },
                TermOrigin::Component {
                    component: system_name.to_string(),
                },
            )
        })
        .collect();

    // A reaction system's events are carried on the same footing as a model's:
    // the schema gives `ReactionSystem` the same `continuous_events` /
    // `discrete_events` blocks, and Python, Go and TypeScript all lift them.
    // Dropping them here made `reject_unsupported_features` blind to an event a
    // reaction system owns, so the compiled system ran the document without it
    // (issues #264, #356).
    let continuous_events = rs
        .continuous_events
        .clone()
        .unwrap_or_default()
        .into_iter()
        .map(|e| namespace_continuous_event(e, system_name, &HashSet::new(), &locals))
        .collect();
    let discrete_events = rs
        .discrete_events
        .clone()
        .unwrap_or_default()
        .into_iter()
        .map(|e| namespace_discrete_event(e, system_name, &HashSet::new(), &locals))
        .collect();

    Ok(SystemBlock {
        name: system_name.to_string(),
        state_vars,
        parameters,
        observed_vars: IndexMap::new(),
        equations,
        continuous_events,
        discrete_events,
    })
}

/// Dot-prefix every un-namespaced variable reference in `expr` with
/// `system_name`. Variables already containing a `.` are left alone so that
/// cross-system references (e.g. an equation explicitly referencing
/// `GEOSFP.T` in a `SimpleOzone` equation) survive unchanged. The independent
/// variable `t` is never namespaced — it's a global symbol the evaluator
/// resolves to the current time, not a component-scoped name.
///
/// Array nodes (`faq`/`makearray`/`integral`/…) carry their
/// body in out-of-band fields (`expr`, `filter`, `lower`, `upper`, `values`,
/// `axes`) plus structural metadata (`output_idx`, `ranges`, `reduce`,
/// `semiring`, `shape`, …). Every such field is preserved and the
/// expression-bearing ones are recursively namespaced, so a discretized
/// `faq` survives coupling. Loop-index symbols introduced by an enclosing
/// `faq` (`output_idx` + `ranges` keys) or `integral`
/// (`int_var`) are component-local — the array interpreter resolves them
/// positionally against `loop_binds`, never against the variable registry — so
/// they are excluded from namespacing within that node's scope (ess-14f.8).
///
/// The ONE structural field that is not merely preserved is `join`
/// (CONFORMANCE_SPEC §5.5.6): a `join.overlap`'s `src_env`/`tgt_env` envelope
/// factors, and a `join.on` key column, are *variable references that happen to
/// be encoded as plain strings rather than as `Expr::Variable` children* — the
/// value-invention materializer resolves each one against the variable registry
/// (`vi_join_index_sym` → `ctx.variables`, `broad_phase::envelope_vectors` →
/// `ctx.const_arrays`), which after flattening is the NAMESPACED registry. They
/// are therefore namespaced by [`namespace_join_names`], under the same
/// declared-local gate Julia's `_namespace_join` uses, so a name that is a loop
/// symbol or a document-scoped index set passes through untouched.
fn namespace_expr(
    expr: &Expr,
    system_name: &str,
    subsys: &HashSet<String>,
    locals: &HashSet<String>,
) -> Expr {
    namespace_expr_scoped(expr, system_name, &HashSet::new(), subsys, locals)
}

/// Dot-prefix the plain-string names carried by a node's `join` clauses
/// (CONFORMANCE_SPEC §5.5.6). Applies the SAME rule [`namespace_expr_scoped`]
/// applies to an `Expr::Variable`, gated on `locals` — the component's own
/// declared variable names plus its subsystem keys:
///
/// * a name this node BINDS as a loop symbol (an `output_idx` entry or a
///   `ranges` key) is left alone — **even when a local variable of the same
///   name is declared**. Index symbols are local to the enclosing `faq`
///   and shadow any coincident variable name (esm-spec §4.3.1: "a given string
///   can be a variable reference in most contexts but serves as an index symbol
///   inside `aggregate.output_idx`, `aggregate.expr`, and `aggregate.ranges`
///   keys"), and an `on` key column is resolved against THIS node's ranges
///   ([`crate::value_invention`]'s `vi_join_index_sym`, the interpreter's
///   `join_sym_for_key`) — so prefixing a shadowed symbol makes it resolve to
///   nothing. This check comes FIRST for that reason;
/// * otherwise a bare name that IS a declared local variable gets the prefix;
/// * a dotted name whose head is a local subsystem gets the prefix;
/// * anything else — a document-scoped index set named by an `on` key column
///   (§5.3), an already-qualified cross-component reference — is left alone.
///
/// Mirrors Julia `namespacing.jl::_namespace_join`. Returns `None` when nothing
/// changed, so a join-free (or fully external) node is byte-identical.
fn namespace_join_names(
    join: &[JoinClause],
    binders: &HashSet<&str>,
    system_name: &str,
    locals: &HashSet<String>,
) -> Option<Vec<JoinClause>> {
    let ns = |n: &String| -> String {
        if binders.contains(n.as_str()) {
            n.clone()
        } else if let Some((head, _)) = n.split_once('.') {
            if locals.contains(head) {
                return format!("{system_name}.{n}");
            }
            n.clone()
        } else if locals.contains(n) {
            format!("{system_name}.{n}")
        } else {
            n.clone()
        }
    };
    let out: Vec<JoinClause> = join
        .iter()
        .map(|c| JoinClause {
            on: c.on.iter().map(|[l, r]| [ns(l), ns(r)]).collect(),
            // Range symbols the node itself binds, not variable references —
            // namespacing must leave them alone, exactly as for an overlap
            // clause's `sym_src` / `sym_tgt`.
            syms: c.syms.clone(),
            overlap: c.overlap.as_ref().map(|ov| OverlapClause {
                src_env: ov.src_env.iter().map(&ns).collect(),
                tgt_env: ov.tgt_env.iter().map(&ns).collect(),
                eps: ov.eps,
                // Range symbols the node itself binds, not variable references
                // — namespacing must leave them alone.
                sym_src: ov.sym_src.clone(),
                sym_tgt: ov.sym_tgt.clone(),
            }),
            // A resolved `on` gate's DATA-COLUMN names are references too, and
            // are namespaced by the same rule; its loop symbols are binders and
            // are not. (Resolution runs after flattening, so this is normally
            // `None` — it exists so the two orders agree.)
            on_gate: c.on_gate.as_ref().map(|g| g.map_column_names(ns)),
        })
        .collect();
    (out != join).then_some(out)
}

fn namespace_expr_scoped(
    expr: &Expr,
    system_name: &str,
    bound: &HashSet<String>,
    subsys: &HashSet<String>,
    locals: &HashSet<String>,
) -> Expr {
    match expr {
        Expr::Number(n) => Expr::Number(*n),
        Expr::Integer(n) => Expr::Integer(*n),
        Expr::Variable(name) => {
            // `t` is the independent variable and `_var` the §6.4 operator
            // placeholder; both are global symbols, neither is component-scoped.
            if name == "t" || name == VAR_PLACEHOLDER || bound.contains(name) {
                Expr::Variable(name.clone())
            } else if name.contains('.') {
                // A dotted reference is already-namespaced UNLESS its head is a
                // subsystem key, in which case it is a subsystem-local reference
                // (`raw.k`) that must be lifted to `<system>.raw.k`.
                let head = name.split('.').next().unwrap_or("");
                if subsys.contains(head) {
                    Expr::Variable(format!("{system_name}.{name}"))
                } else {
                    Expr::Variable(name.clone())
                }
            } else {
                Expr::Variable(format!("{system_name}.{name}"))
            }
        }
        Expr::Operator(node) => {
            // Extend the bound-index set with the loop symbols this node
            // introduces so its body / filter / bound expressions skip them.
            // `ranges` keys cover both the output and contracted indices of an
            // `faq`; `output_idx` is added defensively; an
            // `integral` binds its `int_var`.
            let mut child_bound = bound.clone();
            if let Some(output_idx) = &node.output_idx {
                child_bound.extend(output_idx.iter().cloned());
            }
            if let Some(ranges) = &node.ranges {
                child_bound.extend(ranges.keys().cloned());
            }
            if let Some(int_var) = &node.int_var {
                child_bound.insert(int_var.clone());
            }

            // Re-namespace every expression-bearing child through the crate's
            // ONE canonical child-walker (`ExpressionNode::map_children`) rather
            // than hand-listing fields. `map_children` clones the node first —
            // preserving EVERY structural/metadata field verbatim, just like the
            // old explicit clone — and covers the FULL child set, including the
            // aggregate grouping `key` and template `bindings` that the previous
            // hand-rolled enumeration silently omitted (leaving their variable
            // references un-namespaced when flattening a coupled system).
            let mut out = node.map_children(&mut |c| {
                namespace_expr_scoped(c, system_name, &child_bound, subsys, locals)
            });

            // `wrt` is a differentiation-variable *string*, not a child `Expr`,
            // so it is a node-local rewrite the child-walker does not (and must
            // not) cover; apply it to the rebuilt node exactly as before.
            // `wrt` is a differentiation-variable *string*, not a child `Expr`.
            // A SPATIAL `wrt` names a document-scoped AXIS (esm-libraries-spec
            // §4.7.6 harvests it as an independent variable), so it is prefixed
            // only when it actually names one of this component's own locals —
            // the same whitelist rule `namespace_join_names` applies to a plain
            // string that may be a document-scoped index set. Prefixing it
            // unconditionally produced axes like `m.x` in
            // `independent_variables`; nothing observed that before, because an
            // undiscretized spatial `D` could not reach a FlattenedSystem at all
            // until flatten stopped refusing PDEs.
            out.wrt = node.wrt.as_ref().map(|w| {
                if w.contains('.')
                    || w == "t"
                    || w == VAR_PLACEHOLDER
                    || child_bound.contains(w)
                    || !locals.contains(w)
                {
                    w.clone()
                } else {
                    format!("{system_name}.{w}")
                }
            });
            // `join` likewise carries variable references as plain strings
            // (§5.5.6). The child-walker preserves the field verbatim; the
            // names inside it must follow the registry they resolve against.
            //
            // The binder set is THIS node's own loop symbols, not `child_bound`
            // (which also holds enclosing nodes'). A join column is resolved
            // against this node's `ranges`, so its own binders are the exact
            // shadowing set — and keeping the set node-local is what lets every
            // binding implement the identical rule without threading a scope.
            if let Some(join) = &node.join {
                let mut binders: HashSet<&str> = HashSet::new();
                if let Some(output_idx) = &node.output_idx {
                    binders.extend(output_idx.iter().map(String::as_str));
                }
                if let Some(ranges) = &node.ranges {
                    binders.extend(ranges.keys().map(String::as_str));
                }
                if let Some(ns) = namespace_join_names(join, &binders, system_name, locals) {
                    out.join = Some(ns);
                }
            }
            Expr::operator(out)
        }
    }
}

fn namespace_continuous_event(
    mut event: ContinuousEvent,
    system_name: &str,
    subsys: &HashSet<String>,
    locals: &HashSet<String>,
) -> ContinuousEvent {
    event.conditions = event
        .conditions
        .into_iter()
        .map(|c| namespace_expr(&c, system_name, subsys, locals))
        .collect();
    event.affects = event
        .affects
        .into_iter()
        .map(|mut a| {
            a.lhs = namespace_plain(&a.lhs, system_name);
            a.rhs = namespace_expr(&a.rhs, system_name, subsys, locals);
            a
        })
        .collect();
    if let Some(neg) = event.affect_neg.take() {
        event.affect_neg = Some(
            neg.into_iter()
                .map(|mut a| {
                    a.lhs = namespace_plain(&a.lhs, system_name);
                    a.rhs = namespace_expr(&a.rhs, system_name, subsys, locals);
                    a
                })
                .collect(),
        );
    }
    event
}

fn namespace_discrete_event(
    mut event: DiscreteEvent,
    system_name: &str,
    subsys: &HashSet<String>,
    locals: &HashSet<String>,
) -> DiscreteEvent {
    use crate::types::DiscreteEventTrigger;
    event.trigger = match event.trigger {
        DiscreteEventTrigger::Condition { expression } => DiscreteEventTrigger::Condition {
            expression: namespace_expr(&expression, system_name, subsys, locals),
        },
        other => other,
    };
    if let Some(affects) = event.affects.take() {
        event.affects = Some(
            affects
                .into_iter()
                .map(|mut a| {
                    a.lhs = namespace_plain(&a.lhs, system_name);
                    a.rhs = namespace_expr(&a.rhs, system_name, subsys, locals);
                    a
                })
                .collect(),
        );
    }
    event
}

/// The operator-model placeholder (esm-spec §6.4). A GLOBAL sentinel, not a
/// component-scoped name: `operator_compose` substitutes it with each matching
/// ODE state of the TARGET system, so prefixing it with the operator model's
/// own namespace destroys the very name the substitution looks for. Treated
/// exactly like the independent variable `t` everywhere namespacing happens.
///
/// `pub(crate)` because the load-time gate that REJECTS a binder shadowing it
/// (`parse::reject_reserved_index_symbols`) must name the same sentinel: the
/// scoping rule here and the rejection there are two halves of one contract.
pub(crate) const VAR_PLACEHOLDER: &str = "_var";

fn namespace_plain(name: &str, system_name: &str) -> String {
    if name.contains('.') || name == VAR_PLACEHOLDER {
        name.to_string()
    } else {
        format!("{system_name}.{name}")
    }
}

/// Scan an expression-tree RHS and reject any unlowered rewrite-target operator
/// (esm-spec §4.2 / §9.6.8) with the uniform [`FlattenError::UnloweredOperator`]
/// (`unlowered_operator`) code.
///
/// The tier decision is delegated wholesale to [`crate::op_registry`], the
/// single source of truth for the operator vocabulary — this gate keeps NO
/// hand-maintained op-name list of its own. A node the registry classifies
/// [`crate::op_registry::OpError::Unlowered`] is a rewrite target: the optional
/// sugar ops (`grad`/`div`/`laplacian`/`curl`/`∇`/`integral`), a SPATIAL `D` (a
/// `D` whose `wrt` is a spatial axis rather than the time variable `"t"`), or
/// ANY op not in the evaluable core — an unregistered user discretization op
/// (`godunov_hamiltonian`) is treated exactly like the named sugar ops, with no
/// privileged status. The structural equation-LHS `D(u, t)` stays
/// evaluable-core and is untouched. A rewrite rule must lower these to a stencil
/// before evaluation; this format ships no such rules (they live in
/// EarthSciDiscretizations).
///
/// Malformed-CORE problems (a wrong arity, an inverted `makearray` region) are
/// not this gate's concern — the compile / eval stages report those with their
/// own diagnostics — so only the `Unlowered` classification is surfaced here.
fn reject_spatial_operators(expr: &Expr) -> Result<(), FlattenError> {
    match expr {
        Expr::Number(_) | Expr::Integer(_) | Expr::Variable(_) => Ok(()),
        Expr::Operator(node) => {
            if let Err(crate::op_registry::OpError::Unlowered { op }) =
                crate::op_registry::check_node(node)
            {
                return Err(FlattenError::UnloweredOperator { op });
            }
            // Recurse through the crate's ONE canonical child-walker so the gate
            // sees operators hidden in EVERY expression-bearing sidecar field
            // (`aggregate.expr` bodies, `filter` predicates, integral `lower`/
            // `upper` bounds, `makearray.values`, `key`, `axes`, `bindings`) and
            // not merely `args` — an `args`-only walk let a spatial/sugar op
            // buried in a sidecar escape the gate entirely. The first offender's
            // `FlattenError::UnloweredOperator` diagnostic propagates unchanged.
            node.try_for_each_child(&mut |child| reject_spatial_operators(child))
        }
    }
}

/// Extract the dependent variable name from an `LHS = D(X, t)` pattern.
/// Returns `None` for any other LHS shape.
///
/// "Time derivative" is decided by [`crate::op_registry::is_rewrite_target_derivative`]
/// so that esm-spec §4.2's default applies: an ABSENT `wrt` MEANS `t`. Testing
/// `wrt != Some("t")` instead made a `D(X)` LHS invisible to the conflicting-
/// derivative check and to the pointwise lift (EarthSciAST#407).
fn extract_ddt_dependent(lhs: &Expr) -> Option<String> {
    let Expr::Operator(node) = lhs else {
        return None;
    };
    if node.op != "D" {
        return None;
    }
    if crate::op_registry::is_rewrite_target_derivative(node) {
        return None;
    }
    if node.args.len() != 1 {
        return None;
    }
    match &node.args[0] {
        Expr::Variable(name) => Some(name.clone()),
        _ => None,
    }
}

/// Apply a single coupling entry to the per-system blocks, mutating
/// `coupling_rules_applied` with a human-readable description. `index` is the
/// entry's position in the coupling sequence after `coupling_import`
/// expansion: an expression the entry writes itself carries
/// `{"coupling": index}` (esm-libraries-spec §4.7.5).
fn apply_coupling_entry(
    entry: &CouplingEntry,
    index: usize,
    per_system: &mut Vec<SystemBlock>,
    coupling_rules_applied: &mut Vec<String>,
    merged_renames: &mut IndexMap<String, String>,
    coupling_rewritten_names: &mut BTreeSet<String>,
) -> Result<(), FlattenError> {
    match entry {
        CouplingEntry::OperatorCompose {
            systems,
            translate,
            require_match,
            description,
            ..
        } => {
            let made = apply_operator_compose(
                systems,
                translate.as_ref(),
                *require_match,
                per_system,
                merged_renames,
            )?;
            compose_renames(merged_renames, made);
            coupling_rules_applied.push(
                description
                    .clone()
                    .unwrap_or_else(|| format!("operator_compose({})", systems.join(" + "))),
            );
        }
        CouplingEntry::Couple {
            systems,
            connector,
            // Carried for round-trip only. The flattener acts on `lifting`
            // solely for `operator_compose` (the `"pointwise"` promotion in
            // `lift_pointwise_states`); on a `couple`/`variable_map` entry it
            // is emitted back unchanged, exactly as before this field was
            // typed — it used to be dropped at load, so no flattening
            // behaviour is being changed here.
            lifting: _,
            description,
        } => {
            // The connector's `from`/`to` are plain scoped-reference strings on
            // the entry, so a spelling an earlier merge deleted has to be
            // resolved here — nothing else reaches them (issue #230).
            let connector = retarget_connector(connector, merged_renames);
            apply_couple(systems, connector.as_ref(), index, per_system)?;
            coupling_rules_applied.push(
                description
                    .clone()
                    .unwrap_or_else(|| format!("couple({})", systems.join(" <-> "))),
            );
        }
        CouplingEntry::VariableMap {
            from,
            to,
            transform,
            factor,
            // Round-trip only — see the note on the `Couple` arm above.
            lifting: _,
            description,
        } => {
            match transform {
                // Same by-name endpoints as the `couple` arm, and the sharper
                // half of the reach gap: a `from` naming a merged-away state
                // substitutes a DEAD name into every equation referencing the
                // mapped parameter, rather than merely failing to match
                // (issue #230). Only this arm substitutes, so only this arm
                // resolves — the expression arm's `contains` check below reads
                // the AUTHORED node, which still spells the authored `from`.
                VariableMapTransform::Named(_) => {
                    let resolved_to = resolve_renamed(to, merged_renames).to_string();
                    apply_variable_map(
                        resolve_renamed(from, merged_renames),
                        &resolved_to,
                        *factor,
                        per_system,
                    );
                    // A NAMED transform substitutes `to` away entirely; the
                    // Expression arm below leaves it standing as the observed
                    // the transform defines. Only the first DELETES a name, so
                    // only the first joins the set the registry guard refuses
                    // against (Julia's `map_rewritten_names`).
                    coupling_rewritten_names.insert(resolved_to);
                }
                // Expression transform (esm-spec §10.4): no substitution —
                // references to `to` stay intact and resolve to the observed
                // introduced in the collection phase. Validated here so a bad
                // entry fails before any rewriting: an expression transform
                // spells its own arithmetic (no `factor` slot) and MUST
                // reference the entry's `from` variable — the data-flow edge
                // the entry declares.
                VariableMapTransform::Expression(node) => {
                    if factor.is_some() {
                        return Err(FlattenError::VariableMapFactorWithExpression {
                            from: from.clone(),
                            to: to.clone(),
                        });
                    }
                    if !node.any_child(&mut |e| crate::expression::contains(e, from)) {
                        return Err(FlattenError::VariableMapExpressionMissingFrom {
                            from: from.clone(),
                            to: to.clone(),
                        });
                    }
                }
            }
            coupling_rules_applied.push(description.clone().unwrap_or_else(|| {
                let factor_str = factor.map(|f| format!(" [factor={f}]")).unwrap_or_default();
                format!("variable_map({from} -> {to}, {transform}){factor_str}")
            }));
        }
        CouplingEntry::OperatorApply {
            operator,
            description,
        } => {
            coupling_rules_applied.push(
                description
                    .clone()
                    .unwrap_or_else(|| format!("operator_apply({operator})")),
            );
        }
        CouplingEntry::Callback {
            callback_id,
            description,
            ..
        } => {
            coupling_rules_applied.push(
                description
                    .clone()
                    .unwrap_or_else(|| format!("callback({callback_id})")),
            );
        }
        CouplingEntry::Event {
            event_type,
            name,
            description,
            ..
        } => {
            coupling_rules_applied.push(description.clone().unwrap_or_else(|| {
                format!(
                    "event({}: {})",
                    event_type,
                    name.as_deref().unwrap_or("unnamed")
                )
            }));
        }
        // `coupling_import` entries are expanded into concrete edges by
        // `flatten_with_options` before `flatten_impl` runs, so one never
        // reaches the rule-application step. Treat as a no-op for robustness.
        CouplingEntry::CouplingImport { .. } => {}
    }
    Ok(())
}

/// The dependent variable an equation defines, for `operator_compose` matching
/// (esm-libraries-spec §4.7.1 step 1).
///
/// `D(x, t)` yields `x`; a bare-variable LHS yields itself; the `index` /
/// `faq` shells peel to the variable they write. An LHS that is a
/// composite expression (an algebraic constraint, an `ic` seed) defines no
/// single variable and yields `None`, so it never participates in a match and
/// is preserved unchanged by step 5.
///
/// Delegates to the crate's canonical [`crate::classification::lhs_form`]
/// rather than re-deriving the shapes, matching the oracle's
/// `_lhs_dependent_var`.
fn compose_dependent(lhs: &Expr) -> Option<String> {
    match crate::classification::lhs_form(lhs) {
        crate::classification::LhsForm::Derivative(name)
        | crate::classification::LhsForm::Bare(name) => Some(name),
        crate::classification::LhsForm::Expression => None,
    }
}

/// Normalize an `operator_compose` `translate` map, **INVERTED** for matching
/// (esm-libraries-spec §4.7.1 step 2, esm-spec §10.2).
///
/// The authored direction is normative and is NOT symmetric: for
/// `"systems": [A, B]` every KEY names a variable of `A` and every VALUE names
/// a variable of `B`. Step 3 walks *B's* equations, so the matching loop needs
/// the map the other way round; this returns the inverse
/// `{b_name: (a_name, factor)}`.
///
/// Indexing the authored (A-keyed) map by B's dependent variable is the bug
/// this function exists to prevent — a correctly spelled `translate` map then
/// matches nothing at all and the whole coupling entry is a silent no-op.
///
/// A value is either a plain string (`"B.O3"`) or an object carrying the target
/// and an optional conversion factor (`{"var": "B.O3", "factor": 1e-9}`); the
/// `to` / `target` spellings of that key are accepted alongside `var`, as in
/// the oracle. Anything else is ignored.
fn build_translate_map(
    translate: Option<&serde_json::Value>,
    a_system: &str,
    b_system: &str,
) -> HashMap<String, (String, f64)> {
    let mut out: HashMap<String, (String, f64)> = HashMap::new();
    let Some(obj) = translate.and_then(|v| v.as_object()) else {
        return out;
    };
    for (a_name, value) in obj {
        let a_q = qualify_translate_endpoint(a_name, a_system);
        match value {
            serde_json::Value::String(b_name) => {
                out.insert(qualify_translate_endpoint(b_name, b_system), (a_q, 1.0));
            }
            serde_json::Value::Object(spec) => {
                let b_name = ["var", "to", "target"]
                    .iter()
                    .find_map(|k| spec.get(*k).and_then(|v| v.as_str()));
                let factor = spec.get("factor").and_then(|f| f.as_f64()).unwrap_or(1.0);
                if let Some(b_name) = b_name {
                    out.insert(qualify_translate_endpoint(b_name, b_system), (a_q, factor));
                }
            }
            _ => {}
        }
    }
    out
}

/// Put one `translate` endpoint into the NAMESPACED form the matcher uses
/// (esm-libraries-spec §4.7.1 step 2, esm-spec §10.2).
///
/// `translate` endpoints are authored in either form — bare (`"O3"`) or fully
/// scoped (`"ChemistrySystem.O3"`) — and §10.2 admits both, but matching runs
/// against the namespaced dependent variable of a flattened equation. An
/// endpoint left bare can therefore never match, which is why a correctly
/// spelled bare map was a silent no-op: the lookup missed, and the bare-name
/// fallback then searched A for B's short name and missed too.
///
/// A bare endpoint is qualified with the system it belongs to under §10.2's
/// direction rule — a KEY against `systems[0]`, a VALUE against `systems[1]`.
/// An endpoint that already carries a dot is left ALONE: it is either already
/// namespaced or names a subsystem path, and re-prefixing it would break it.
///
/// `_var` is exempt in both positions. It is a GLOBAL sentinel (esm-spec §6.4),
/// never namespaced; a value of `"B._var"` is the redundant spelling §10.2
/// requires to stay harmless, and it stays harmless because placeholder
/// expansion has already turned that equation into a DIRECT match, which takes
/// precedence over this map.
fn qualify_translate_endpoint(name: &str, system: &str) -> String {
    if name.is_empty()
        || name == VAR_PLACEHOLDER
        || name.ends_with(&format!(".{VAR_PLACEHOLDER}"))
        || name.contains('.')
        || system.is_empty()
    {
        return name.to_string();
    }
    format!("{system}.{name}")
}

/// Expand the `_var` placeholder (esm-spec §6.4) in B's equations against A's
/// solved-for variables — esm-libraries-spec §4.7.1 step 3, "Placeholder
/// expansion".
///
/// An operator model writes ONE equation over the sentinel `_var`
/// (`D(_var, t) = -u·grad(_var)`); composing it with A means CLONING that
/// equation once per variable A solves for, with `_var` substituted for that
/// variable's namespaced name. `_var` is a GLOBAL sentinel and is never
/// namespaced (see [`VAR_PLACEHOLDER`]), so the substitution is a plain
/// single-name rewrite through the crate's canonical
/// [`crate::substitute::substitute`] — which reaches the sidecar expression
/// fields (`aggregate.expr`, `filter`, integral bounds) a hand-rolled `args`
/// walk would miss.
///
/// Runs BEFORE matching, which is what makes an expanded equation a DIRECT
/// match in step 3 and keeps a redundant `translate: {"A.x": "B._var"}` entry
/// harmless (§10.2's redundancy invariant).
fn expand_placeholder_equations(a_idx: usize, b_idx: usize, per_system: &mut [SystemBlock]) {
    let a_states: Vec<String> = per_system[a_idx].state_vars.keys().cloned().collect();
    if a_states.is_empty() {
        return;
    }
    let b_equations = std::mem::take(&mut per_system[b_idx].equations);
    let mut expanded: Vec<FlatEq> = Vec::with_capacity(b_equations.len());
    for fe in b_equations {
        if crate::expression::contains(&fe.eq.lhs, VAR_PLACEHOLDER)
            || crate::expression::contains(&fe.eq.rhs, VAR_PLACEHOLDER)
        {
            for state in &a_states {
                let subs: HashMap<String, Expr> =
                    std::iter::once((VAR_PLACEHOLDER.to_string(), Expr::Variable(state.clone())))
                        .collect();
                // Each clone keeps B's contributions, and so B's component as
                // their origin.
                let mut clone = fe.clone();
                clone.eq.lhs = crate::substitute::substitute(&fe.eq.lhs, &subs);
                clone.map_contributions(|e| crate::substitute::substitute(e, &subs));
                expanded.push(clone);
            }
        } else {
            expanded.push(fe);
        }
    }
    per_system[b_idx].equations = expanded;
}

/// Apply an `operator_compose` rule (esm-libraries-spec §4.7.1, all five
/// steps): merge system B's equations into system A by matching dependent
/// variables and summing right-hand sides.
///
/// For `"systems": [A, B]`, A is `systems[0]` and B is `systems[1]`. The five
/// steps run in order:
///
/// 1. **Extract dependent variables** — [`compose_dependent`].
/// 2. **Apply translations** — [`build_translate_map`] builds the INVERSE
///    (B → A) map the matching loop needs.
/// 3. **Match equations**, in the spec's precedence order: DIRECT first, then
///    TRANSLATION, then the bare-name fallback. Placeholder expansion
///    ([`expand_placeholder_equations`]) has already run, so an expanded
///    equation carries A's own variable name and is a DIRECT match.
///    Direct-first is load-bearing rather than cosmetic: consulting
///    `translate` first would let an A-keyed map hit spuriously on that
///    rewritten name and redirect the match to a target that does not exist,
///    turning a working composition into an over-determination error (§10.2's
///    redundancy invariant).
/// 4. **Combine matched equations** — A keeps its LHS, and the RHS becomes
///    `rhs_A + factor * rhs_B`. On a TRANSLATION match only, B's dependent
///    variable is rewritten to A's target throughout `rhs_B` first: a
///    `translate` pair names two spellings of the SAME quantity, and leaving
///    `rhs_B` in B's spelling would strand that variable as an unknown nothing
///    defines, because its own defining equation was just consumed. B's other
///    variables — its parameters, its observeds — keep their names. On a
///    direct or placeholder match the two names are already equal, so the
///    rewrite is the identity.
/// 5. **Preserve unmatched equations** — a B equation with no A counterpart
///    stays in B's block, in place and unchanged, and is REPORTED: an entry that
///    merges nothing at all, or only some of what B authored, prints
///    `operator_compose_no_merge` / `operator_compose_partial_merge`, and fails
///    outright when the entry declares `require_match`. Preserving an unmatched
///    equation quietly is what made "merged everything" and "merged nothing" the
///    same observable outcome.
///
/// This function previously merged only equations whose dependent variable was
/// byte-identical across two blocks. Because flattening namespaces every
/// variable (`A.O3` vs `B.O3`), that can essentially never happen, so it was a
/// total no-op: neither placeholder expansion nor `translate` was implemented
/// at all, and `translate` was destructured away unread.
fn apply_operator_compose(
    systems: &[String],
    translate: Option<&serde_json::Value>,
    require_match: Option<bool>,
    per_system: &mut [SystemBlock],
    renames: &IndexMap<String, String>,
) -> Result<IndexMap<String, String>, FlattenError> {
    if systems.len() < 2 {
        return Ok(IndexMap::new());
    }
    let Some(a_idx) = per_system.iter().position(|b| b.name == systems[0]) else {
        return Ok(IndexMap::new());
    };
    let Some(b_idx) = per_system.iter().position(|b| b.name == systems[1]) else {
        return Ok(IndexMap::new());
    };
    if a_idx == b_idx {
        return Ok(IndexMap::new());
    }

    // Step 3's placeholder expansion, run first so the expanded equations are
    // ordinary direct matches below.
    expand_placeholder_equations(a_idx, b_idx, per_system);

    // Step 2: the INVERSE (B -> A) translation map, both endpoints put into
    // NAMESPACED form first (`qualify_translate_endpoint`) — matching runs
    // against a flattened equation's namespaced dependent variable, so a bare
    // endpoint that is not qualified here can never match.
    // Both endpoints are rewritten off names an earlier merge in this document
    // already deleted: an earlier entry may have consumed either the A-side or
    // the B-side spelling this one names (issue #230).
    let translate: HashMap<String, (String, f64)> =
        build_translate_map(translate, &systems[0], &systems[1])
            .into_iter()
            .map(|(b_name, (a_name, factor))| {
                (
                    resolve_renamed(&b_name, renames).to_string(),
                    (resolve_renamed(&a_name, renames).to_string(), factor),
                )
            })
            .collect();

    // Step 1: A's equations, indexed by dependent variable.
    let mut a_index: IndexMap<String, usize> = IndexMap::new();
    for (i, FlatEq { eq, .. }) in per_system[a_idx].equations.iter().enumerate() {
        if let Some(dep) = compose_dependent(&eq.lhs) {
            a_index.insert(dep, i);
        }
    }

    let b_equations = std::mem::take(&mut per_system[b_idx].equations);
    let mut surviving: Vec<FlatEq> = Vec::new();
    // `b_dep -> target_dep` for every match that RENAMED the dependent variable
    // (step 4's "the merged-away name does not survive"). Insertion-ordered so
    // the prune below is deterministic.
    let mut merged_away: IndexMap<String, String> = IndexMap::new();
    // Positions in A's equation vector this entry merged INTO, for the
    // reattribution below. Collected rather than acted on in place because
    // `a_index` indexes that vector POSITIONALLY and stays live until the last
    // B equation has been matched — relocating an equation mid-loop would
    // invalidate it.
    let mut merged_positions: HashSet<usize> = HashSet::new();
    // The subset of `merged_away` the BARE-NAME fallback produced. Its surviving
    // spelling is settled by ownership below, not by which side was `systems[0]`.
    let mut bare_matches: IndexMap<String, String> = IndexMap::new();
    // Step 5's merge tally: how many equations the operator side authored that
    // COULD match (one with no extractable dependent variable is not a
    // contribution and is exempt by construction), and which of them did not.
    let mut authored = 0_usize;
    let mut unmatched: Vec<String> = Vec::new();
    for b_fe in b_equations {
        let Some(b_dep) = compose_dependent(&b_fe.eq.lhs) else {
            surviving.push(b_fe);
            continue;
        };
        authored += 1;

        // Step 3, in precedence order: direct, then translation, then the
        // bare-name fallback.
        let mut target = b_dep.clone();
        let mut factor = 1.0_f64;
        let mut is_bare_match = false;
        if a_index.contains_key(&b_dep) {
            // Direct match: `target` is already right.
        } else if let Some((a_name, f)) = translate.get(&b_dep) {
            target = a_name.clone();
            factor = *f;
        } else {
            let short = b_dep.split_once('.').map(|(_, s)| s).unwrap_or(&b_dep);
            let suffix = format!(".{short}");
            if let Some(hit) = a_index.keys().find(|k| k.ends_with(&suffix)) {
                target = hit.clone();
                is_bare_match = true;
            }
        }

        // Step 5: no counterpart in A, so the equation stays in B untouched.
        let Some(&i) = a_index.get(&target) else {
            unmatched.push(b_dep);
            surviving.push(b_fe);
            continue;
        };

        // Step 4. B's dependent variable is rewritten to A's target throughout
        // `rhs_B`. On a direct or placeholder match the two names are already
        // equal, so this is the identity and no renaming happens; it bites on a
        // TRANSLATION match (and on the bare-name fallback, which is a
        // translation by another route), where the two names are two spellings
        // of ONE quantity and B's own defining equation is being consumed right
        // here — leaving `rhs_B` in B's spelling would strand that variable as
        // an unknown nothing defines. ONLY the dependent variable moves; B's
        // parameters and observeds keep their names.
        //
        // B's contributions are APPENDED to A's, in order, origins unchanged
        // (esm-libraries-spec §4.7.5). A `translate` factor scales B's one
        // contribution; when B already carries several, they collapse into ONE
        // `factor * (b1 + b2 + …)` whose origins are the union: indivisible,
        // because distributing the factor would change the arithmetic.
        let b_eq = b_fe.eq;
        let mut b_contributions = b_fe.contributions;
        if target != b_dep {
            let subs: HashMap<String, Expr> =
                std::iter::once((b_dep.clone(), Expr::Variable(target.clone()))).collect();
            for c in &mut b_contributions {
                c.expr = crate::substitute::substitute(&c.expr, &subs);
            }
        }
        if factor != 1.0 {
            b_contributions = vec![Contribution {
                expr: Expr::operator(ExpressionNode {
                    op: "*".to_string(),
                    args: vec![Expr::Number(factor), fold_contributions(&b_contributions)],
                    ..Default::default()
                }),
                origins: union_origins(&b_contributions, None),
            }];
        }
        let a_fe = &mut per_system[a_idx].equations[i];
        let mut merged = std::mem::take(&mut a_fe.contributions);
        merged.extend(b_contributions);
        a_fe.set_contributions(merged);
        // Step 4: "the final equation for variable x has the original LHS:
        // D(x, t)". Where A defines the quantity by a bare equation and B
        // gives it a tendency, the merged equation is that tendency, spelled
        // in A's name (which the ownership rule below may still retarget).
        let a_lhs = &per_system[a_idx].equations[i].eq.lhs;
        if !matches!(
            crate::classification::lhs_form(a_lhs),
            crate::classification::LhsForm::Derivative(_)
        ) && matches!(
            crate::classification::lhs_form(&b_eq.lhs),
            crate::classification::LhsForm::Derivative(_)
        ) {
            let subs: HashMap<String, Expr> =
                std::iter::once((b_dep.clone(), Expr::Variable(target.clone()))).collect();
            per_system[a_idx].equations[i].eq.lhs = crate::substitute::substitute(&b_eq.lhs, &subs);
        }
        merged_positions.insert(i);
        if target != b_dep {
            if is_bare_match {
                bare_matches.insert(b_dep.clone(), target.clone());
            }
            merged_away.insert(b_dep, target);
        }
    }
    per_system[b_idx].equations = surviving;

    report_operator_compose_merge(
        &systems[0],
        &systems[1],
        require_match,
        authored,
        &unmatched,
    )?;

    // §4.7.1 step 3, the bare-name fallback's OWNERSHIP rule. A bare-name match
    // asserts that A's `x` and B's `x` are one state under two spellings; the
    // surviving spelling is the OWNER's, not `systems[0]`'s, so that flipping
    // the entry's argument order cannot change which state name — and therefore
    // which INITIAL CONDITION — comes out the far side.
    let mut inverted: IndexMap<String, String> = IndexMap::new();
    for (b_dep, target) in &bare_matches {
        if bare_name_owner(per_system, &systems[0], &systems[1], b_dep, target)? == *b_dep {
            inverted.insert(target.clone(), b_dep.clone());
            merged_away.shift_remove(b_dep);
        }
    }
    if !inverted.is_empty() {
        // Retarget BEFORE the reattribution: the reattribution reads each merged
        // equation's dependent variable to decide whose block it belongs in, and
        // after this rewrite that variable is the owner's spelling. Running it
        // first would file the merged tendency under the name that just went away.
        retarget_merged_names(per_system, &inverted);
        for gone in inverted.keys() {
            let owner = gone.split_once('.').map(|(head, _)| head).unwrap_or(gone);
            if let Some(block) = per_system.iter_mut().find(|b| b.name == owner) {
                block.state_vars.shift_remove(gone);
                block.observed_vars.shift_remove(gone);
            }
        }
    }

    reattribute_merged_equations(a_idx, &merged_positions, per_system);

    // Step 4, second half: a RENAMING match — a translation match, or the
    // bare-name fallback, which is a name-based translation — has just consumed
    // B's defining equation for `b_dep`, so B's declaration of that name is left
    // constraining nothing. An unknown with no defining equation classifies as
    // ALGEBRAIC (esm-spec §6.3.1), so keeping it would hand the solver a state
    // with no constraint — a structurally singular system, which is exactly what
    // the rhs rewrite above exists to prevent; this prune is its other half.
    //
    // §10.2 says a `translate` pair names ONE physical quantity under two
    // spellings, so only A's spelling survives: every remaining reference is
    // retargeted at it FIRST, then the stranded declaration is dropped. The
    // retarget is DOCUMENT-WIDE, not B-local — a third system is free to
    // reference `B.x` by its scoped name, and pruning the declaration while
    // leaving that reference dangling would trade one broken system for another.
    if !merged_away.is_empty() {
        retarget_merged_names(per_system, &merged_away);
        for gone in merged_away.keys() {
            per_system[b_idx].state_vars.shift_remove(gone);
            per_system[b_idx].observed_vars.shift_remove(gone);
        }
    }

    // Everything this entry deleted, in one map, for the caller's running
    // document-wide rename (issue #230). `inverted` rides along because it is
    // the same operation pointed the other way — the loser of an ownership
    // decision is merged away exactly like the loser of a translation match.
    merged_away.extend(inverted);
    Ok(merged_away)
}

thread_local! {
    /// Active sink for [`capture_coupling_diagnostics`]. `None` — the default —
    /// means the warnings go to stderr, which is what a caller sees.
    static COUPLING_DIAGNOSTIC_SINK: std::cell::RefCell<Option<Vec<String>>> =
        const { std::cell::RefCell::new(None) };
}

/// Run `f`, collecting the WARNING-level coupling diagnostics it emits instead
/// of printing them, and return them alongside its result.
///
/// The side-effect-free counterpart of the stderr stream, in the shape
/// [`crate::pushdown_rewrite::pushdown_diagnostics`] established for the
/// projection-pushdown residuals. It exists because a diagnostic nothing can
/// assert on is a diagnostic that rots: the shared
/// `tests/conformance/operator_compose_merge/` corpus compares diagnostic
/// OUTCOMES, and without this the Rust adapter could check the `require_match`
/// refusals but not the warnings they were promoted from.
///
/// The sink is thread-local, so concurrent test threads do not capture each
/// other's findings, and it is restored on the way out even if `f` returns an
/// error (`f` is not unwind-safe by contract — a panic inside it leaves the sink
/// installed for that thread, which only affects a thread that is already
/// unwinding).
pub fn capture_coupling_diagnostics<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
    COUPLING_DIAGNOSTIC_SINK.with(|sink| *sink.borrow_mut() = Some(Vec::new()));
    let out = f();
    let collected =
        COUPLING_DIAGNOSTIC_SINK.with(|sink| sink.borrow_mut().take().unwrap_or_default());
    (out, collected)
}

/// Emit one coupling warning: into the active capture sink if there is one,
/// otherwise to stderr with the `warning: ` prefix `pushdown_rewrite` uses.
fn emit_coupling_warning(message: String) {
    let captured = COUPLING_DIAGNOSTIC_SINK.with(|sink| {
        if let Some(buf) = sink.borrow_mut().as_mut() {
            buf.push(message.clone());
            true
        } else {
            false
        }
    });
    if !captured {
        eprintln!("warning: {message}");
    }
}

/// Is `dep` a STATE variable of the (partly flattened) blocks?
///
/// A state is the thing that carries an initial condition, which is the whole of
/// what a bare-name match decides between. An observed carries none.
fn is_state_var(per_system: &[SystemBlock], dep: &str) -> bool {
    let root = dep.split_once('.').map(|(h, _)| h).unwrap_or(dep);
    per_system
        .iter()
        .find(|b| b.name == root)
        .is_some_and(|b| b.state_vars.contains_key(dep))
}

/// Which spelling owns the quantity a bare-name match unified?
/// (esm-libraries-spec §4.7.1 step 3.)
///
/// A DIRECT match needs no decision (the two names are equal) and a `translate`
/// match is the author naming the surviving spelling explicitly. The BARE-NAME
/// fallback is the one that has to choose, and choosing `systems[0]` — what this
/// binding did before — makes an `operator_compose` entry mean different things
/// in its two argument orders: flipping `systems` silently swapped which state
/// name, and which INITIAL CONDITION, came out the far side.
///
/// Ownership follows the variable's own namespace, the direction step 4's
/// merged-equation reattribution already reaches in. The merge deletes one of
/// the two names, so the question is which of them the flattened system keeps:
///
/// * **Both are STATES** — each carries its own initial condition, and nothing
///   in the document says which one the merged tendency should integrate from.
///   Refused, because deciding it here is exactly the silent choice issue #195
///   is about. The author says what they mean with `translate`, which names the
///   surviving spelling outright, or with `require_match`.
/// * **Exactly one is a state** — the other carries no initial condition, so
///   there is nothing to lose by renaming onto the state. That one is the owner,
///   in either argument order.
/// * **Neither is** — no initial condition is at stake either way; the incumbent
///   (`systems[0]`'s spelling) stands, as before.
fn bare_name_owner(
    per_system: &[SystemBlock],
    a: &str,
    b: &str,
    b_dep: &str,
    target: &str,
) -> Result<String, FlattenError> {
    let b_state = is_state_var(per_system, b_dep);
    let a_state = is_state_var(per_system, target);
    if b_state && a_state {
        return Err(FlattenError::OperatorComposeAmbiguousBareName {
            a: a.to_string(),
            b: b.to_string(),
            b_dep: b_dep.to_string(),
            target: target.to_string(),
        });
    }
    Ok(if b_state {
        b_dep.to_string()
    } else {
        target.to_string()
    })
}

/// Report an `operator_compose` entry that merged nothing, or only some of what
/// the operator side authored (esm-libraries-spec §4.7.1 step 5).
///
/// Preserving an unmatched equation is correct — an operator system may
/// legitimately contribute states of its own — but preserving it SILENTLY leaves
/// "merged everything" and "merged nothing" indistinguishable, and both wrong
/// outcomes reachable from a document that is spec-valid and loads clean.
///
/// `require_match` is TRI-STATE, and the three states are three different things
/// an author can mean:
///
/// | `require_match` | zero merged                       | some but not all      |
/// |:----------------|:----------------------------------|:----------------------|
/// | `None`          | `operator_compose_no_merge` ERROR | partial-merge warning |
/// | `Some(true)`    | `operator_compose_require_match_unmatched` ERROR (both) ||
/// | `Some(false)`   | permitted, silently               | permitted, silently   |
///
/// ZERO merged is an error by default because such an entry is indistinguishable
/// from an entry that is not there. PARTIAL stays a warning because an operator
/// may legitimately contribute states of its own alongside the ones it does
/// merge, and the format cannot tell the two apart.
///
/// `require_match: false` is the explicit opt-out — the author declaring a
/// standalone-contributing operator. It is a DECLARATION, not a default: an
/// absent flag means "I have not said", which is why it is the case that errors.
///
/// The warning goes through [`emit_coupling_warning`] — stderr, the same channel
/// `pushdown_rewrite`'s residual diagnostics use, or the active
/// [`capture_coupling_diagnostics`] sink; the two refusals are real errors and
/// are returned.
fn report_operator_compose_merge(
    a: &str,
    b: &str,
    require_match: Option<bool>,
    authored: usize,
    unmatched: &[String],
) -> Result<(), FlattenError> {
    if authored == 0 || unmatched.is_empty() {
        return Ok(());
    }
    // The author has declared a standalone-contributing operator. Nothing to
    // report: an unmatched equation is what they said to expect.
    if require_match == Some(false) {
        return Ok(());
    }
    let merged = authored - unmatched.len();
    let names = unmatched.join(", ");
    if require_match == Some(true) {
        return Err(FlattenError::OperatorComposeRequireMatchUnmatched {
            a: a.to_string(),
            b: b.to_string(),
            merged,
            authored,
            unmatched: names,
        });
    }
    if merged == 0 {
        return Err(FlattenError::OperatorComposeNoMerge {
            a: a.to_string(),
            b: b.to_string(),
            authored,
            unmatched: names,
        });
    }
    emit_coupling_warning(format!(
        "operator_compose_partial_merge: operator_compose({a} + {b}) merged {merged} of \
         {authored} equations '{b}' authored; unmatched dependent variable(s): {names}. The \
         unmatched equations are preserved unchanged (esm-libraries-spec §4.7.1 step 5), so they \
         integrate DECOUPLED from '{a}'. Set `require_match: true` if they were meant to be \
         contributions, or `require_match: false` if they were not."
    ));
    Ok(())
}

/// Move each freshly merged equation into its dependent variable's block.
///
/// A composed tendency is no longer any single author's contribution, so
/// esm-libraries-spec §4.7.1 step 4 attributes it to the system that OWNS its
/// dependent variable rather than to the `systems[0]` that happened to carry
/// the surviving equation. Where A already IS that system — the ordinary
/// `["Chemistry", "Advection"]` spelling, and every fixture in the shared tree
/// before this one — the move is the identity and nothing changes.
///
/// Where it is NOT the identity is a document that CHAINS compose entries over
/// one state with the OPERATOR as A:
///
/// ```json
/// {"type": "operator_compose", "systems": ["Sink", "Chem"]}
/// {"type": "operator_compose", "systems": ["Src",  "Chem"]}
/// {"type": "operator_compose", "systems": ["Chem", "Adv"], "lifting": "pointwise"}
/// ```
///
/// with `Sink` and `Src` authoring `D(Chem.X, t) = …` directly. §4.7.1 permits
/// it and `reseact.esm` is built on it (deposition, then emission, then the
/// transport lift). Entry 1 consumes Chem's own equation and leaves the sum in
/// the `Sink` block; entry 2 then walks the `Src` and `Chem` blocks and cannot
/// see it. Both the composed tendency and Src's un-merged contribution survive
/// to assembly, which reports two systems defining `Chem.O3` — loud rather than
/// corrupt, but the document is spec-valid and must flatten. Relocating the
/// merge to the `Chem` block is what puts it back where the next entry looks for
/// it, in either role.
///
/// The per-system block is this binding's analogue of the reference
/// implementation's per-equation owner (Julia `coupling_apply.jl`, the
/// `new_owners[j] = _component_root(dep)` line): which block an equation sits in
/// is its SLOT OWNER, which decides what a later entry can see. It is not
/// provenance — who authored each summand travels in the equation's contribution
/// list, which moves with it (esm-libraries-spec §4.7.5).
///
/// POSITION. §4.7.5 step 4 makes document order normative, and a relocated
/// equation is APPENDED to the owner's block rather than inserted at the slot of
/// the B equation it consumed. Appending is what reproduces the reference order:
/// each merge trails the ones before it, so a species whose chain ends at a
/// later entry ends up after one whose chain ended earlier — `Chem.NO` (last
/// merged by entry 1) ahead of `Chem.O3` (last merged by entry 2) in the
/// document above. Inserting at the consumed equation's slot instead would
/// freeze both at Chem's original declaration order and disagree with every
/// other binding.
///
/// An equation whose dependent variable names no block of this document stays
/// where it is; there is nowhere to move it to.
fn reattribute_merged_equations(
    a_idx: usize,
    merged_positions: &HashSet<usize>,
    per_system: &mut [SystemBlock],
) {
    if merged_positions.is_empty() {
        return;
    }
    let a_name = per_system[a_idx].name.clone();
    let mut kept: Vec<FlatEq> = Vec::new();
    let mut moved: Vec<(String, FlatEq)> = Vec::new();
    for (i, eq) in std::mem::take(&mut per_system[a_idx].equations)
        .into_iter()
        .enumerate()
    {
        let owner = if merged_positions.contains(&i) {
            compose_dependent(&eq.eq.lhs).map(|dep| {
                dep.split_once('.')
                    .map(|(root, _)| root.to_string())
                    .unwrap_or(dep)
            })
        } else {
            None
        };
        match owner {
            Some(owner) if owner != a_name && per_system.iter().any(|blk| blk.name == owner) => {
                moved.push((owner, eq));
            }
            _ => kept.push(eq),
        }
    }
    per_system[a_idx].equations = kept;
    for (owner, eq) in moved {
        if let Some(blk) = per_system.iter_mut().find(|blk| blk.name == owner) {
            blk.equations.push(eq);
        }
    }
}

/// Rewrite every reference to a merged-away dependent variable, EVERYWHERE
/// (esm-libraries-spec §4.7.1 step 4).
///
/// Applied after an `operator_compose` renaming match folds `B.x` into `A.y`:
/// the two spellings named one quantity, only `A.y` still exists, so every
/// equation side in the whole document is rewritten off the dead name. An
/// observed variable's defining expression is one of those equations (it is not
/// carried on the variable record), so this covers it too.
///
/// "Document-wide" is more than the equation pool, and the three surfaces below
/// are the rest of it (CONFORMANCE_SPEC §5.35). All three were namespaced at
/// COLLECTION — phase 1, before any coupling rule ran — so each still holds the
/// FULLY-QUALIFIED spelling this merge just deleted, and nothing downstream
/// rewrites it:
///
/// * **EVENTS.** An affect's `lhs` is a plain variable NAME, not an expression,
///   and it is exactly what a renaming merge deletes: an affect writing to an
///   unknown the flattened system does not declare is a silent wrong answer
///   rather than a refusal. A crossing condition, an affect RHS, an
///   `affect_neg`, and a discrete `condition` trigger's expression go with it.
/// * **`update` RULES.** A variable's parameter-update `when` / `expression`
///   slots are Expressions carried on the VARIABLE rather than in `equations`,
///   so no equation walk reaches them; a parameter that refreshes from `B.x`
///   would keep reading a state that no longer exists.
/// * **`join` SIDECARS.** Handled inside [`rename_join_names`] — see there.
///
/// (`field_ics` are classified out of `equations` after this runs, so they ride
/// along with the equations.)
fn retarget_merged_names(per_system: &mut [SystemBlock], renames: &IndexMap<String, String>) {
    if renames.is_empty() {
        return;
    }
    let subs: HashMap<String, Expr> = renames
        .iter()
        .map(|(from, to)| (from.clone(), Expr::Variable(to.clone())))
        .collect();
    let ren = |expr: &Expr| rename_names(expr, &subs, renames);
    for block in per_system.iter_mut() {
        for fe in block.equations.iter_mut() {
            fe.eq.lhs = ren(&fe.eq.lhs);
            fe.map_contributions(&ren);
        }
        for var in block
            .state_vars
            .values_mut()
            .chain(block.parameters.values_mut())
            .chain(block.observed_vars.values_mut())
        {
            var.for_each_expression_mut(&mut |expr| *expr = ren(expr));
        }
        for event in block.continuous_events.iter_mut() {
            rename_continuous_event_names(event, &subs, renames);
        }
        for event in block.discrete_events.iter_mut() {
            rename_discrete_event_names(event, &subs, renames);
        }
    }
}

/// [`crate::substitute::substitute`], extended to a `join`'s plain strings.
///
/// The walker every merged-away retarget uses. `substitute` itself is left
/// alone: it is the general binding-substitution primitive, and a `join` string
/// cannot hold the arbitrary EXPRESSION a binding may supply. Mirrors Python
/// `flatten.py::rename_names`.
fn rename_names(
    expr: &Expr,
    subs: &HashMap<String, Expr>,
    renames: &IndexMap<String, String>,
) -> Expr {
    rename_join_names(&crate::substitute::substitute(expr, subs), renames)
}

/// One event's affect list, off the names a merge deleted.
///
/// Deliberately NOT [`crate::substitute::substitute_in_continuous_event`]: that
/// one maps EXPRESSIONS, and an affect's `lhs` is a plain variable NAME string.
/// The `lhs` is precisely what a renaming merge deletes.
fn rename_affect_names(
    affects: &mut [AffectEquation],
    subs: &HashMap<String, Expr>,
    renames: &IndexMap<String, String>,
) {
    for affect in affects {
        if let Some(survivor) = renames.get(&affect.lhs) {
            affect.lhs = survivor.clone();
        }
        affect.rhs = rename_names(&affect.rhs, subs, renames);
    }
}

/// A continuous event's conditions, affects and `affect_neg` (see
/// [`rename_affect_names`]).
fn rename_continuous_event_names(
    event: &mut ContinuousEvent,
    subs: &HashMap<String, Expr>,
    renames: &IndexMap<String, String>,
) {
    for condition in event.conditions.iter_mut() {
        *condition = rename_names(condition, subs, renames);
    }
    rename_affect_names(&mut event.affects, subs, renames);
    if let Some(neg) = event.affect_neg.as_mut() {
        rename_affect_names(neg, subs, renames);
    }
}

/// A discrete event's trigger and affects. Only a `condition` trigger carries an
/// expression; a periodic / times trigger is pure data.
fn rename_discrete_event_names(
    event: &mut DiscreteEvent,
    subs: &HashMap<String, Expr>,
    renames: &IndexMap<String, String>,
) {
    if let DiscreteEventTrigger::Condition { expression } = &mut event.trigger {
        *expression = rename_names(expression, subs, renames);
    }
    if let Some(affects) = event.affects.as_mut() {
        rename_affect_names(affects, subs, renames);
    }
}

fn sum_exprs(a: Expr, b: Expr) -> Expr {
    Expr::operator(ExpressionNode {
        op: "+".to_string(),
        args: vec![a, b],
        wrt: None,
        dim: None,
        ..Default::default()
    })
}

/// Apply a `couple` rule by injecting the connector equations (if any) into
/// a synthetic system block. The connector is an opaque JSON value in the
/// Rust type model — we look for an `equations` array of `{lhs, rhs}`
/// pairs, each of which may be a JSON-encoded [`Expr`].
///
/// Every expression a connector writes is authored by the entry, so its
/// contribution carries `{"coupling": index}` (esm-libraries-spec §4.7.5).
fn apply_couple(
    systems: &[String],
    connector: &serde_json::Value,
    index: usize,
    per_system: &mut Vec<SystemBlock>,
) -> Result<(), FlattenError> {
    let Some(eqs_json) = connector.get("equations").and_then(|e| e.as_array()) else {
        return Ok(());
    };
    let block_name = format!("couple({})", systems.join(","));
    let mut new_equations = Vec::new();
    for eq_val in eqs_json {
        // esm-spec §4.7.2 gives a connector equation TWO spellings, and a
        // document may mix them:
        //
        //   * EXPLICIT — `{lhs, rhs}` — a new equation of its own, collected
        //     into a synthetic `couple(...)` block below;
        //   * INJECTED — `{from, to, transform, expression}` — a source/sink
        //     TERM folded into the equation that already defines `to`.
        //
        // Only the explicit form was implemented, so every fixture using the
        // injected one hard-failed with `MalformedConnectorEquation`. That went
        // unnoticed because the spatial-operator refusal fired first on all
        // three corpus documents that carry it.
        if eq_val.get("lhs").is_some() || eq_val.get("rhs").is_some() {
            let lhs = parse_connector_side(eq_val, "lhs", systems)?;
            let rhs = parse_connector_side(eq_val, "rhs", systems)?;
            new_equations.push(FlatEq::authored(
                Equation {
                    comment: None,
                    lhs,
                    rhs,
                },
                TermOrigin::Coupling { coupling: index },
            ));
        } else if eq_val.get("to").is_some() {
            inject_connector_term(eq_val, systems, index, per_system)?;
        } else {
            return Err(FlattenError::MalformedConnectorEquation {
                systems: systems.join(","),
                side: "lhs".to_string(),
            });
        }
    }
    if !new_equations.is_empty() {
        per_system.push(SystemBlock {
            name: block_name,
            state_vars: IndexMap::new(),
            parameters: IndexMap::new(),
            observed_vars: IndexMap::new(),
            equations: new_equations,
            continuous_events: Vec::new(),
            discrete_events: Vec::new(),
        });
    }
    Ok(())
}

/// The `(block, equation)` position of the LAST equation in document order
/// whose dependent variable is `target` — restricted to a `D(target, t)` left
/// side when `tendency_only` (a multiplicative factor scales the tendency,
/// never a bare `target ~ …` equation, esm-libraries-spec §4.7.2).
fn last_defining_equation(
    per_system: &[SystemBlock],
    target: &str,
    tendency_only: bool,
) -> Option<(usize, usize)> {
    use crate::classification::{LhsForm, lhs_form};
    let mut found = None;
    for (b, block) in per_system.iter().enumerate() {
        for (i, FlatEq { eq, .. }) in block.equations.iter().enumerate() {
            let dep = match lhs_form(&eq.lhs) {
                LhsForm::Derivative(name) => name,
                LhsForm::Bare(name) if !tendency_only => name,
                _ => continue,
            };
            if dep == target {
                found = Some((b, i));
            }
        }
    }
    found
}

/// Fold one INJECTED connector equation — `{from, to, transform, expression}`
/// (esm-spec §4.7.2) — into the equation that already defines its `to` target.
///
/// `from` / `to` are scoped references (`A.x`) and the `expression`'s own
/// references are, by contract, already fully scoped, so nothing is namespaced
/// here — the term is used verbatim, exactly as the Python oracle uses it.
///
/// The target equation is found by its LHS DEPENDENT VARIABLE, read through the
/// crate's canonical [`crate::classification::lhs_form`], so `D(x, t)`,
/// `D(x[i], t)`, a bare `x`, and the `faq`-wrapped spellings all resolve
/// to `x`; when several equations define `to`, the LAST in document order
/// takes the term. An `additive` term whose `to` is an UNKNOWN no equation
/// defines BECOMES its tendency, a new `D(to, t) ~ term` (§4.7.2). Any other
/// `to` that names no equation's LHS — a parameter, a name no component owns,
/// or the target of a `replacement` — is SKIPPED, not an error, as in the
/// oracle.
///
/// `transform` selects how the term combines with the existing RHS: `additive`
/// sums, `multiplicative` multiplies, `replacement` overwrites. An absent or
/// unrecognised transform falls through to `additive`, mirroring the oracle.
///
/// `multiplicative` is the ONE transform with a precondition: esm-spec §10.3
/// and esm-libraries-spec §4.7.2 define it against the target's EXISTING ODE
/// right-hand side, so a `to` with no `D(to)` tendency raises
/// [`FlattenError::CoupleMultiplicativeNoTendency`] rather than taking the
/// skip. The check runs BEFORE the skip and is keyed on a TENDENCY
/// specifically, not on "some equation defines `to`" — an observed or an
/// algebraic unknown has a defining equation and still has nothing to multiply.
/// For the same reason the factor scales the LAST `D(to, t)` equation, even
/// when a bare `to ~ …` equation comes after it.
fn inject_connector_term(
    eq_val: &serde_json::Value,
    systems: &[String],
    index: usize,
    per_system: &mut [SystemBlock],
) -> Result<(), FlattenError> {
    let Some(target) = eq_val.get("to").and_then(|v| v.as_str()) else {
        return Ok(());
    };

    let transform = eq_val.get("transform").and_then(|v| v.as_str());
    let multiplicative = transform == Some("multiplicative");
    // The target equation: the LAST whose dependent variable is `to`, and for
    // a multiplicative factor the last whose left side is `D(to, t)` — the
    // presence check below and the fold read the same lookup.
    let found = last_defining_equation(per_system, target, multiplicative);
    if multiplicative && found.is_none() {
        return Err(FlattenError::CoupleMultiplicativeNoTendency {
            target: target.to_string(),
        });
    }

    // The term: the declared `expression`, or a bare reference to `from` when
    // the entry carries none.
    let term = match eq_val.get("expression") {
        Some(v) => serde_json::from_value::<Expr>(v.clone()).map_err(|_| {
            FlattenError::MalformedConnectorEquation {
                systems: systems.join(","),
                side: "expression".to_string(),
            }
        })?,
        None => match eq_val.get("from").and_then(|v| v.as_str()) {
            Some(from) => Expr::Variable(from.to_string()),
            None => {
                return Err(FlattenError::MalformedConnectorEquation {
                    systems: systems.join(","),
                    side: "from".to_string(),
                });
            }
        },
    };

    let authored = Contribution {
        expr: term.clone(),
        origins: vec![TermOrigin::Coupling { coupling: index }],
    };

    let Some((b, i)) = found else {
        // No equation defines `to`. An additive term onto an UNKNOWN BECOMES
        // its tendency (§4.7.2), filed with the top-level component `to`'s
        // first path segment names. A parameter target, a name no component
        // owns, or any other transform has nothing to fold into and is skipped.
        if !matches!(transform, None | Some("additive") | Some("")) {
            return Ok(());
        }
        let root = target.split('.').next().unwrap_or(target);
        let Some(owner) = per_system
            .iter_mut()
            .find(|blk| blk.name == root && blk.state_vars.contains_key(target))
        else {
            return Ok(());
        };
        let lhs = Expr::operator(ExpressionNode {
            op: "D".to_string(),
            args: vec![Expr::Variable(target.to_string())],
            wrt: Some("t".to_string()),
            ..Default::default()
        });
        owner.equations.push(FlatEq {
            eq: Equation {
                comment: None,
                lhs,
                rhs: term,
            },
            contributions: vec![authored],
            lifted: false,
        });
        return Ok(());
    };

    let fe = &mut per_system[b].equations[i];
    let contributions = match transform {
        // Non-additive: the existing list and the factor collapse into one
        // indivisible contribution whose origins are the union.
        Some("multiplicative") => vec![Contribution {
            expr: Expr::operator(ExpressionNode {
                op: "*".to_string(),
                args: vec![fe.body().clone(), term],
                ..Default::default()
            }),
            origins: union_origins(
                &fe.contributions,
                Some(TermOrigin::Coupling { coupling: index }),
            ),
        }],
        Some("replacement") => vec![authored],
        // `additive`, absent, or unrecognised.
        _ => {
            let mut list = std::mem::take(&mut fe.contributions);
            list.push(authored);
            list
        }
    };
    fe.set_contributions(contributions);
    Ok(())
}

/// Deserialize one side (`lhs` / `rhs`) of a `couple` connector equation as an
/// [`Expr`]. An absent side or a value that does not parse is a
/// [`FlattenError::MalformedConnectorEquation`] rather than a silent drop.
fn parse_connector_side(
    eq_val: &serde_json::Value,
    side: &str,
    systems: &[String],
) -> Result<Expr, FlattenError> {
    eq_val
        .get(side)
        .cloned()
        .and_then(|v| serde_json::from_value::<Expr>(v).ok())
        .ok_or_else(|| FlattenError::MalformedConnectorEquation {
            systems: systems.join(","),
            side: side.to_string(),
        })
}

/// Apply a NAMED-transform `variable_map` rule by substituting `from` for
/// `to` in every equation's expression tree (and scaling by `factor` where
/// applicable). Parameter removal for `param_to_var`/`conversion_factor`
/// happens in the collection phase to keep this function purely
/// expression-rewriting. Expression transforms (esm-spec §10.4) never reach
/// here — they perform no substitution at all (the target becomes an
/// observed in the collection phase).
fn apply_variable_map(from: &str, to: &str, factor: Option<f64>, per_system: &mut [SystemBlock]) {
    // `factor` is a scaling coefficient; the schema restricts it to the scaling
    // transforms (additive / multiplicative / conversion_factor), so apply it
    // uniformly whenever present. This matches Python and Julia — Rust previously
    // scaled only for `conversion_factor`, silently dropping the factor for
    // additive / multiplicative. A factor of 1.0 is a no-op and left unwrapped.
    // (Parameter removal for param_to_var/conversion_factor is in the collection
    // phase, so this function no longer needs `transform`.) The factor leads,
    // `factor * from`, as in the oracle.
    let replacement = match factor {
        Some(f) if f != 1.0 => Expr::operator(ExpressionNode {
            op: "*".to_string(),
            args: vec![Expr::Number(f), Expr::Variable(from.to_string())],
            wrt: None,
            dim: None,
            ..Default::default()
        }),
        _ => Expr::Variable(from.to_string()),
    };
    // One single-target substitution map, reused across equations, observeds,
    // AND events through the canonical `crate::substitute` traversal (which
    // preserves every array-node metadata field via `map_children`). Hand-rolled
    // walkers previously drifted — the local `substitute_var` covered equations
    // and observeds but not events, so an event condition / affect RHS
    // referencing the removed `to` parameter kept a dangling reference.
    let subs: HashMap<String, Expr> = std::iter::once((to.to_string(), replacement)).collect();
    // The same single pair in the form the join renamer takes: a `join` names
    // its key columns and overlap envelope factors as plain STRINGS, which no
    // expression substitution can reach.
    let join_renames: IndexMap<String, String> =
        std::iter::once((to.to_string(), from.to_string())).collect();
    // A substitution changes an INPUT of a term, not its author: it applies
    // inside each contribution and adds no origin (esm-libraries-spec §4.7.5).
    for block in per_system.iter_mut() {
        for fe in &mut block.equations {
            fe.eq.lhs = crate::substitute::substitute(&fe.eq.lhs, &subs);
            fe.map_contributions(|e| {
                rename_join_names(&crate::substitute::substitute(e, &subs), &join_renames)
            });
        }
        // A `variable_map` also removes the mapped parameter from the system, so
        // it must reach every remaining Expression a VARIABLE carries — the
        // trigger and value expressions of a parameter `update` — otherwise one
        // keeps a dangling reference to the now-removed parameter and evaluates
        // to NaN. (An observed unknown's defining expression is an equation from
        // esm 1.0.0, already rewritten by the loop above.)
        for var in block
            .observed_vars
            .values_mut()
            .chain(block.parameters.values_mut())
        {
            var.for_each_expression_mut(&mut |expr| {
                *expr =
                    rename_join_names(&crate::substitute::substitute(expr, &subs), &join_renames);
            });
        }
        // ...and event conditions / affect RHS (continuous + discrete), for the
        // same reason: an event whose condition or affect referenced the removed
        // `to` parameter would otherwise keep a dangling reference. The event
        // helpers rewrite conditions, affect RHS, affect_neg RHS, and the trigger
        // expression, leaving affect LHS (a bare variable name) untouched.
        for ev in &mut block.continuous_events {
            *ev = crate::substitute::substitute_in_continuous_event(ev, &subs);
        }
        for ev in &mut block.discrete_events {
            *ev = crate::substitute::substitute_in_discrete_event(ev, &subs);
        }
    }
}

/// True iff any node in `expr` carries a non-empty `join`.
fn contains_join(expr: &Expr) -> bool {
    match expr {
        Expr::Operator(node) => {
            node.join.as_ref().is_some_and(|j| !j.is_empty()) || node.any_child(&mut contains_join)
        }
        _ => false,
    }
}

/// Apply a rename MAP to every plain-string name a `join` clause carries
/// (CONFORMANCE_SPEC §5.5.6), the join-side companion of the `variable_map`
/// substitution above.
///
/// `crate::substitute` walks expression CHILDREN, so it cannot see these names;
/// but they are references in the same namespaced scope as everything else
/// (that is exactly what makes them namespaceable). A `param_to_var` /
/// `conversion_factor` map REMOVES `to` from the flattened parameter registry,
/// so a join still naming it points at a variable that no longer exists and
/// materialisation dies with `join references unknown variable`. Mirrors Julia
/// `coupling_apply.jl::_rename_join_names`.
///
/// The exact case this exists for: an overlap-gated value-invention producer
/// over a coupled rectangle buffer, where `tgt_env = [ISRM.src_W, …]` while an
/// `ISRM_SR.src_W -> ISRM.src_W` map has already removed `ISRM.src_W`.
///
/// Taken as a MAP rather than a single pair, because the same hazard reaches a
/// join from two directions: a `variable_map` deleting its consumer parameter
/// (one pair, [`apply_variable_map`]) and an `operator_compose` renaming match
/// deleting a dependent variable (a whole map,
/// esm-libraries-spec §4.7.1 step 4 / CONFORMANCE_SPEC §5.35).
fn rename_join_names(expr: &Expr, renames: &IndexMap<String, String>) -> Expr {
    // Scan BEFORE the rebuild: `map_children` clones, and this runs over every
    // equation of every block for every `variable_map` entry. Almost no model
    // carries a join, and those must stay free of an extra whole-tree copy on
    // top of the substitution's. The scan is once per tree, not per node — the
    // recursion below is the unguarded `rename_join_names_in`.
    if renames.is_empty() || !contains_join(expr) {
        return expr.clone();
    }
    rename_join_names_in(expr, renames)
}

fn rename_join_names_in(expr: &Expr, renames: &IndexMap<String, String>) -> Expr {
    let Expr::Operator(node) = expr else {
        return expr.clone();
    };
    let mut out = node.map_children(&mut |c| rename_join_names_in(c, renames));
    if let Some(join) = &node.join {
        let ren = |n: &String| -> String { renames.get(n).unwrap_or(n).clone() };
        out.join = Some(
            join.iter()
                .map(|c| JoinClause {
                    on: c.on.iter().map(|[l, r]| [ren(l), ren(r)]).collect(),
                    // Binders, not references — renaming leaves them alone.
                    syms: c.syms.clone(),
                    overlap: c.overlap.as_ref().map(|ov| OverlapClause {
                        src_env: ov.src_env.iter().map(&ren).collect(),
                        tgt_env: ov.tgt_env.iter().map(&ren).collect(),
                        eps: ov.eps,
                        // Range symbols the node itself binds, not variable
                        // references — renaming must leave them alone.
                        sym_src: ov.sym_src.clone(),
                        sym_tgt: ov.sym_tgt.clone(),
                    }),
                    on_gate: c.on_gate.as_ref().map(|g| g.map_column_names(ren)),
                })
                .collect(),
        );
    }
    Expr::operator(out)
}

/// Preflight (esm-spec §4.6 / §10.4): every `variable_map` endpoint must name
/// something the collected system carries — a state, a parameter, or an
/// observed, under its FULL dot path.
///
/// This is the resolution half of the entry, and until it existed both halves
/// failed silently. `apply_variable_map` substitutes `to` -> `from` whether or
/// not either name binds, and `apply_variable_map_removals` pops `to` with
/// `shift_remove`, whose `None` was discarded — so an endpoint that resolved
/// to nothing produced a flattened system that looked exactly like one where
/// the coupling had been applied and had simply had no effect. The two failure
/// modes reported in issue #198 are both this: a target that keeps its
/// declared default, and a source that leaves every rewritten consumer reading
/// a name no table binds (NaN at run time, not a diagnostic).
///
/// EXEMPTION: a `from` whose owning system is a top-level `data_sources` key.
/// Such a producer is served through the runtime forcing seam rather than as a
/// declared variable, so it is legitimately absent from the collected tables
/// (see [`apply_variable_map_removals`], which records it as a loaded
/// producer).
///
/// Deliberately NOT checked: whether a promoting transform's `to` is a
/// PARAMETER rather than an unknown. `tests/valid/scoped_refs_coupling.esm`
/// maps `param_to_var` onto a declared unknown, and tightening that is a
/// separate question from whether the endpoint resolves at all.
fn check_variable_map_endpoints(
    file: &EsmFile,
    per_system: &[SystemBlock],
) -> Result<(), FlattenError> {
    let Some(entries) = &file.coupling else {
        return Ok(());
    };
    let mut known: HashSet<&str> = HashSet::new();
    for block in per_system {
        known.extend(block.state_vars.keys().map(String::as_str));
        known.extend(block.parameters.keys().map(String::as_str));
        known.extend(block.observed_vars.keys().map(String::as_str));
    }
    let loader_names: HashSet<&str> = file
        .data_sources
        .as_ref()
        .map(|ds| ds.keys().map(String::as_str).collect())
        .unwrap_or_default();
    for entry in entries {
        let CouplingEntry::VariableMap { from, to, .. } = entry else {
            continue;
        };
        // A `from` served by a data source never lands in the collected tables.
        // The owner is the segment BEFORE the first dot, and a dotless `from`
        // is its own owner — matching the other four bindings, which all take
        // the whole string when there is no dot.
        let from_owner = from
            .split_once('.')
            .map_or(from.as_str(), |(owner, _)| owner);
        let from_is_loaded = loader_names.contains(from_owner);
        for (side, endpoint) in [("from", from), ("to", to)] {
            if endpoint.is_empty()
                || known.contains(endpoint.as_str())
                || (side == "from" && from_is_loaded)
            {
                continue;
            }
            return Err(FlattenError::VariableMapUnresolvedEndpoint {
                from: from.clone(),
                to: to.clone(),
                side: side.to_string(),
                endpoint: endpoint.clone(),
            });
        }
    }
    Ok(())
}

/// Preflight (esm-spec §10.4): walk every `variable_map` coupling entry whose
/// transform is the named `identity` and raise [`FlattenError::DomainUnitMismatch`]
/// when the `from` and `to` variables both carry DECLARED, non-empty, and
/// DIFFERING unit strings. Mirrors Julia's `_check_variable_map_units`
/// (coupling_apply.jl): an `identity` map asserts the two ends are the same
/// quantity, so incompatible declared units are a modeling error.
/// `param_to_var` / `conversion_factor` / expression transforms are exempt (the
/// conversion is declared, or the mapping does not imply unit equivalence at the
/// site), and a missing or empty unit on either side is the valid (unchecked)
/// case.
fn check_variable_map_units(file: &EsmFile) -> Result<(), FlattenError> {
    let Some(entries) = &file.coupling else {
        return Ok(());
    };
    for entry in entries {
        let CouplingEntry::VariableMap {
            from,
            to,
            transform,
            ..
        } = entry
        else {
            continue;
        };
        if transform.as_named() != Some("identity") {
            continue;
        }
        let (Some(source_units), Some(target_units)) = (
            lookup_variable_units(file, from),
            lookup_variable_units(file, to),
        ) else {
            continue;
        };
        if source_units.is_empty() || target_units.is_empty() {
            continue;
        }
        if source_units != target_units {
            return Err(FlattenError::DomainUnitMismatch {
                variable: from.clone(),
                source_units,
                target_units,
            });
        }
    }
    Ok(())
}

/// Look up a dot-qualified variable's declared units across models, subsystems,
/// and reaction systems (species + parameters). Returns `None` when the
/// variable is missing or carries no declared units. Mirrors Julia's
/// `_lookup_variable_units` (coupling_apply.jl).
pub(crate) fn lookup_variable_units(file: &EsmFile, qualified: &str) -> Option<String> {
    let (root, tail) = qualified.split_once('.')?;
    if let Some(models) = &file.models
        && let Some(model) = models.get(root)
    {
        return lookup_model_units(model, tail);
    }
    if let Some(rsystems) = &file.reaction_systems
        && let Some(rsys) = rsystems.get(root)
    {
        return lookup_rsys_units(rsys, tail);
    }
    None
}

/// Resolve a variable's declared units within a [`Model`], recursing into
/// Model subsystems for nested names like `"Inner.T"`. A present variable's
/// units are returned as-is (possibly `None`); the subsystem recursion is only
/// tried when the variable is absent from this model's own `variables`.
fn lookup_model_units(model: &Model, name: &str) -> Option<String> {
    if let Some(var) = model.variables.get(name) {
        return var.units.clone();
    }
    if let Some((head, rest)) = name.split_once('.')
        && let Some(subs) = &model.subsystems
        && let Some(sub_val) = subs.get(head)
        && let Ok(sub_model) = serde_json::from_value::<Model>(sub_val.clone())
    {
        return lookup_model_units(&sub_model, rest);
    }
    None
}

/// Resolve a variable's declared units within a [`ReactionSystem`] — species
/// first, then parameters, then nested subsystems — mirroring Julia's
/// `_lookup_rsys_units`.
fn lookup_rsys_units(rsys: &ReactionSystem, name: &str) -> Option<String> {
    if let Some(sp) = rsys.species.get(name) {
        return sp.units.clone();
    }
    if let Some(p) = rsys.parameters.get(name) {
        return p.units.clone();
    }
    if let Some((head, rest)) = name.split_once('.')
        && let Some(subs) = &rsys.subsystems
        && let Some(sub_val) = subs.get(head)
        && let Ok(sub_rsys) = serde_json::from_value::<ReactionSystem>(sub_val.clone())
    {
        return lookup_rsys_units(&sub_rsys, rest);
    }
    None
}

// ============================================================================
// Scoped-reference `ic` classification (esm-spec §11.4.1)
// ============================================================================

/// If `lhs` is `ic(target)` — an `ic` operator over a single variable argument —
/// return the target state name, else `None`. `pub(crate)` so the single-model
/// array-compile path ([`crate::simulate_array::ArrayCompiled::from_model`])
/// classifies `ic` equations identically to this flatten pass.
pub(crate) fn extract_ic_target(lhs: &Expr) -> Option<String> {
    let Expr::Operator(node) = lhs else {
        return None;
    };
    if node.op != "ic" || node.args.len() != 1 {
        return None;
    }
    match &node.args[0] {
        Expr::Variable(v) => Some(v.clone()),
        _ => None,
    }
}

// ============================================================================
// Pointwise spatial lift of merged state ODEs (esm-spec §10.5)
// ============================================================================
//
// Reaction ODE-gen and `operator_compose` both run at the AST level and IN THAT
// ORDER (reactions → generic `D(sp)=Σ terms`, then `operator_compose` merges each
// species' reaction ODE with the spatial operator's advection contribution). What
// operator_compose does NOT do is array-ify the result: the merged
// `D(sp) = <reaction in scalar sp> + <-u·makearray(grad(sp))>` still has a SCALAR
// `sp` while its advection `makearray` indexes `sp` per grid cell. This pass
// performs the `lifting:"pointwise"` promotion — it wraps each such merged state
// ODE in a `faq` over the grid, indexing the bare reaction species per cell
// and each operator makearray per cell, so the reaction network runs pointwise on
// the grid through the existing array evaluator. Mirrors the Julia reference
// `_apply_pointwise_lift!` (flatten.jl).

/// Collect every `makearray` node reachable from `expr`, recursing through
/// [`ExpressionNode::for_each_child`] so no expression-bearing sidecar field
/// is missed; nodes land in its contractual pre-order.
fn collect_makearrays<'a>(acc: &mut Vec<&'a ExpressionNode>, expr: &'a Expr) {
    let Expr::Operator(node) = expr else {
        return;
    };
    if node.op == "makearray" {
        acc.push(node);
    }
    node.for_each_child(&mut |c| collect_makearrays(acc, c));
}

/// First `Variable` leaf name in an index-argument expression (the loop variable
/// of that index position), or `None` for a constant position.
fn index_arg_loop(expr: &Expr) -> Option<String> {
    match expr {
        Expr::Variable(v) => Some(v.clone()),
        Expr::Operator(node) => {
            for a in &node.args {
                if let Some(v) = index_arg_loop(a) {
                    return Some(v);
                }
            }
            None
        }
        _ => None,
    }
}

/// Determine the ordered spatial loop variables of a lowered spatial operator by
/// reading an `index(<lifted species>, a1, …, aRank)` gather inside `ma` whose
/// every position carries a loop variable (the interior stencil). Returns the
/// loop names in index-position (dim) order, or `None`.
fn detect_lift_loops(
    ma: &ExpressionNode,
    lifted: &HashSet<String>,
    rank: usize,
) -> Option<Vec<String>> {
    fn walk(expr: &Expr, lifted: &HashSet<String>, rank: usize, out: &mut Option<Vec<String>>) {
        if out.is_some() {
            return;
        }
        let Expr::Operator(node) = expr else {
            return;
        };
        if node.op == "index"
            && node.args.len() == rank + 1
            && let Some(Expr::Variable(name)) = node.args.first()
            && lifted.contains(name)
        {
            let mut loops = Vec::with_capacity(rank);
            let mut ok = true;
            for a in node.args.iter().skip(1) {
                match index_arg_loop(a) {
                    Some(lv) => loops.push(lv),
                    None => {
                        ok = false;
                        break;
                    }
                }
            }
            if ok {
                *out = Some(loops);
                return;
            }
        }
        for a in &node.args {
            walk(a, lifted, rank, out);
        }
        if let Some(e) = &node.expr {
            walk(e, lifted, rank, out);
        }
        if let Some(vs) = &node.values {
            for v in vs {
                walk(v, lifted, rank, out);
            }
        }
    }
    let mut out = None;
    for a in &ma.args {
        walk(a, lifted, rank, &mut out);
    }
    if let Some(vs) = &ma.values {
        for v in vs {
            walk(v, lifted, rank, &mut out);
        }
    }
    out
}

/// Per-dimension grid extent of a lowered spatial operator: the largest cell
/// index addressed in each `regions` dimension.
fn makearray_extents(ma: &ExpressionNode) -> Vec<i64> {
    let Some(regions) = &ma.regions else {
        return Vec::new();
    };
    let Some(first) = regions.first() else {
        return Vec::new();
    };
    let rank = first.len();
    let mut ext = vec![0i64; rank];
    for region in regions {
        if region.len() != rank {
            continue;
        }
        for (d, r) in region.iter().enumerate() {
            // An unfolded bound contributes no extent (it cannot: §9.7.6 folds
            // every bound to an integer before this pass runs).
            if let Some(hi) = r[1].as_i64() {
                ext[d] = ext[d].max(hi);
            }
        }
    }
    ext
}

/// Rewrite a scalar (merged reaction + operator) RHS into its per-cell form over
/// the spatial `loops`: a bare reference to an array variable becomes
/// `index(var, loops…)`, and each spatial-operator `makearray` becomes
/// `index(makearray, loops…)` (its region values already index per cell).
/// Self-contained nodes (`index`/`faq`) are left untouched;
/// elementwise ops recurse.
fn lift_rhs_to_cell(expr: &Expr, arrayvars: &HashSet<String>, loops: &[String]) -> Expr {
    match expr {
        Expr::Variable(name) if arrayvars.contains(name) => index_node(name, loops),
        Expr::Variable(_) | Expr::Number(_) | Expr::Integer(_) => expr.clone(),
        Expr::Operator(node) => {
            if node.op == "makearray" {
                return index_makearray(node, loops);
            }
            if matches!(node.op.as_str(), "index" | "faq") {
                return expr.clone();
            }
            let mut out = ExpressionNode::clone(node);
            out.args = node
                .args
                .iter()
                .map(|a| lift_rhs_to_cell(a, arrayvars, loops))
                .collect();
            Expr::operator(out)
        }
    }
}

/// Build `index(name, loops…)`.
fn index_node(name: &str, loops: &[String]) -> Expr {
    let mut args = Vec::with_capacity(loops.len() + 1);
    args.push(Expr::Variable(name.to_string()));
    for l in loops {
        args.push(Expr::Variable(l.clone()));
    }
    Expr::operator(ExpressionNode {
        op: "index".to_string(),
        args,
        ..Default::default()
    })
}

/// Build `index(<makearray>, loops…)`.
fn index_makearray(ma: &ExpressionNode, loops: &[String]) -> Expr {
    let mut args = Vec::with_capacity(loops.len() + 1);
    args.push(Expr::operator(ma.clone()));
    for l in loops {
        args.push(Expr::Variable(l.clone()));
    }
    Expr::operator(ExpressionNode {
        op: "index".to_string(),
        args,
        ..Default::default()
    })
}

/// Pointwise spatial lift (esm-spec §10.5). Promotes every state ODE that
/// `operator_compose` merged with a spatial operator (its merged RHS carries an
/// operator `makearray`) from a 0-D scalar to the operator's grid shape, and
/// rewrites the equation into a `faq` over the grid. `loaded_producers`
/// maps loaded field name → rank; a producer whose rank equals the grid rank is
/// indexed per cell alongside the lifted species.
///
/// Per-cell indexing applies inside each contribution; the `faq` wrapper goes
/// around their left-fold sum (esm-libraries-spec §4.7.5).
fn apply_pointwise_lift(
    equations: &mut [FlatEq],
    lifted_shapes: &mut IndexMap<String, Vec<i64>>,
    loaded_producers: &HashMap<String, usize>,
) -> Result<(), FlattenError> {
    // A species is lifted iff its state ODE's merged RHS carries a spatial-operator
    // makearray (the advection contribution operator_compose added).
    let mut lifted: HashSet<String> = HashSet::new();
    for FlatEq { eq, .. } in equations.iter() {
        let Some(species) = extract_ddt_dependent(&eq.lhs) else {
            continue;
        };
        let mut mas: Vec<&ExpressionNode> = Vec::new();
        collect_makearrays(&mut mas, &eq.rhs);
        if !mas.is_empty() {
            lifted.insert(species);
        }
    }
    if lifted.is_empty() {
        return Ok(());
    }

    for fe in equations.iter_mut() {
        let eq = &fe.eq;
        let Some(species) = extract_ddt_dependent(&eq.lhs) else {
            continue;
        };
        if !lifted.contains(&species) {
            continue;
        }
        let mut mas: Vec<&ExpressionNode> = Vec::new();
        collect_makearrays(&mut mas, &eq.rhs);
        let Some(first_ma) = mas.first() else {
            continue;
        };
        let regions = match &first_ma.regions {
            Some(r) if !r.is_empty() => r,
            _ => continue,
        };
        let rank = regions[0].len();

        // Loop variables of the grid iteration, read from an interior stencil.
        let mut loops: Option<Vec<String>> = None;
        for ma in &mas {
            loops = detect_lift_loops(ma, &lifted, rank);
            if loops.is_some() {
                break;
            }
        }
        // No full-rank interior-stencil gather in any operator makearray → the
        // grid loop variables are unknown, so the merged reaction/operator ODE
        // cannot be array-ified onto the operator grid. Mirrors the Julia /
        // Python `DimensionPromotionError` message for this same case
        // (pointwise_lift.jl `_pointwise_lift_loops`, flatten.py).
        let loops = loops.ok_or_else(|| FlattenError::DimensionPromotion {
            message: format!(
                "pointwise lift: could not determine the spatial loop variables \
                 for species '{species}' from its operator makearray"
            ),
        })?;

        let extents = makearray_extents(first_ma);
        // The post-lift grid shape, recorded as a first-class flattened field
        // (esm-libraries-spec §4.7.5 step 4 `lifted_shapes`) so a consumer need
        // not re-infer it from the lifted equations' index use.
        lifted_shapes.insert(species.clone(), extents.clone());

        // Operands to index per cell: the lifted species plus any loaded producer
        // whose rank matches the grid rank (e.g. a grid-shaped wind field).
        let mut arrayvars: HashSet<String> = lifted.clone();
        for (name, r) in loaded_producers {
            if *r == rank {
                arrayvars.insert(name.clone());
            }
        }

        // Grid ranges: dense `[1, extent]` intervals keyed by the loop symbols.
        let mut ranges: HashMap<String, RangeSpec> = HashMap::new();
        for (d, loop_name) in loops.iter().enumerate() {
            ranges.insert(loop_name.clone(), RangeSpec::Interval([1, extents[d]]));
        }

        // The species' DECLARED shape is left alone. A synthetic `_lift_<loop>`
        // axis used to be written here so downstream consumers saw an array
        // state, but that fabricates a `shape` the document never declared —
        // and step 4 requires each map to carry the DECLARED variable. The real
        // post-lift grid shape now travels in `lifted_shapes` above, which is
        // the field the spec provides for exactly this, and the array simulator
        // infers the concrete extent from the lifted equations regardless.

        let idx_species = index_node(&species, &loops);
        let d_body = Expr::operator(ExpressionNode {
            op: "D".to_string(),
            args: vec![idx_species],
            wrt: Some("t".to_string()),
            ..Default::default()
        });
        let new_lhs = Expr::operator(ExpressionNode {
            op: "faq".to_string(),
            output_idx: Some(loops.clone()),
            ranges: Some(ranges.clone()),
            expr: Some(Box::new(d_body)),
            ..Default::default()
        });
        let wrapper = ExpressionNode {
            op: "faq".to_string(),
            output_idx: Some(loops.clone()),
            ranges: Some(ranges),
            ..Default::default()
        };
        fe.eq.lhs = new_lhs;
        fe.eq.rhs = Expr::operator(wrapper);
        fe.lifted = true;
        fe.map_contributions(|e| lift_rhs_to_cell(e, &arrayvars, &loops));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_support::{ddt, test_file, var};
    use crate::types::{Model, ModelVariable, VariableType};
    use std::collections::HashMap;

    #[test]
    fn test_flatten_empty_file_errors() {
        let err = flatten(&EsmFile::default()).unwrap_err();
        assert!(matches!(err, FlattenError::Empty));
    }

    #[test]
    fn test_flatten_single_model_namespaces_variables() {
        let mut vars = IndexMap::new();
        vars.insert(
            "x".to_string(),
            ModelVariable {
                default: Some(0.0.into()),
                ..var(VariableType::Unknown, Some("m"))
            },
        );
        vars.insert(
            "k".to_string(),
            ModelVariable {
                default: Some(1.0.into()),
                ..var(VariableType::Parameter, None)
            },
        );

        let mut models = IndexMap::new();
        models.insert(
            "sys".to_string(),
            Model {
                name: Some("System".to_string()),
                variables: vars,
                equations: vec![ddt("x", Expr::Variable("k".to_string()))],
                ..Default::default()
            },
        );

        let file = EsmFile {
            models: Some(models),
            ..Default::default()
        };

        let flat = flatten(&file).unwrap();
        assert_eq!(flat.independent_variables, vec!["t".to_string()]);
        assert!(flat.state_variables.contains_key("sys.x"));
        assert!(flat.parameters.contains_key("sys.k"));
        assert_eq!(flat.equations.len(), 1);
        assert_eq!(
            extract_ddt_dependent(&flat.equations[0].lhs).unwrap(),
            "sys.x"
        );
        assert_eq!(flat.equations[0].rhs, Expr::Variable("sys.k".to_string()));
        assert_eq!(flat.metadata.source_systems, vec!["sys".to_string()]);
    }

    // gt-vx74: `t` is the global independent variable and must stay bare
    // after flatten (never `sys.t`). Observed expressions in tests/simulation
    // fixtures — notably python_scipy_integration.esm's ExponentialDecay
    // analytical_solution — reference `t` directly, and the evaluator only
    // recognizes bare `t` as the independent variable.
    #[test]
    fn test_namespace_expr_preserves_bare_t() {
        let expr = Expr::operator(ExpressionNode {
            op: "*".to_string(),
            args: vec![
                Expr::Variable("decay_rate".to_string()),
                Expr::Variable("t".to_string()),
            ],
            ..Default::default()
        });
        let out = namespace_expr(&expr, "ExponentialDecay", &HashSet::new(), &HashSet::new());
        match out {
            Expr::Operator(node) => {
                assert_eq!(
                    node.args[0],
                    Expr::Variable("ExponentialDecay.decay_rate".to_string())
                );
                assert_eq!(node.args[1], Expr::Variable("t".to_string()));
            }
            _ => panic!("expected operator node"),
        }
    }

    // ---- Test helpers for the variable_map unit check + pointwise lift ----

    fn make_model(vars: Vec<(&str, ModelVariable)>, equations: Vec<Equation>) -> Model {
        let mut variables = IndexMap::new();
        for (name, v) in vars {
            variables.insert(name.to_string(), v);
        }
        Model {
            variables,
            equations,
            ..Default::default()
        }
    }

    /// Two models coupled by an `identity` variable_map from `src.T` (units
    /// `from_units`) onto the parameter `dst.temp` (units `to_units`).
    fn identity_map_file(from_units: Option<&str>, to_units: Option<&str>) -> EsmFile {
        let src = make_model(
            vec![("T", var(VariableType::Unknown, from_units))],
            vec![ddt("T", Expr::Number(0.0))],
        );
        let dst = make_model(
            vec![
                ("temp", var(VariableType::Parameter, to_units)),
                ("y", var(VariableType::Unknown, Some("K"))),
            ],
            vec![ddt("y", Expr::Variable("temp".to_string()))],
        );
        let mut models = IndexMap::new();
        models.insert("src".to_string(), src);
        models.insert("dst".to_string(), dst);

        EsmFile {
            models: Some(models),
            coupling: Some(vec![CouplingEntry::VariableMap {
                from: "src.T".to_string(),
                to: "dst.temp".to_string(),
                transform: VariableMapTransform::Named("identity".to_string()),
                factor: None,
                lifting: None,
                description: None,
            }]),
            ..Default::default()
        }
    }

    // C1: an `identity` variable_map bridging a K-unit source and a degC-unit
    // target (both declared, non-empty, differing) raises DomainUnitMismatch —
    // mirrors Julia's `_check_variable_map_units`.
    #[test]
    fn test_variable_map_identity_unit_mismatch_errors() {
        let file = identity_map_file(Some("K"), Some("degC"));
        match flatten(&file).unwrap_err() {
            FlattenError::DomainUnitMismatch {
                variable,
                source_units,
                target_units,
            } => {
                assert_eq!(variable, "src.T");
                assert_eq!(source_units, "K");
                assert_eq!(target_units, "degC");
            }
            other => panic!("expected DomainUnitMismatch, got {other:?}"),
        }
    }

    // C1: matching declared units under `identity` is the valid case — no error.
    #[test]
    fn test_variable_map_identity_matching_units_ok() {
        let file = identity_map_file(Some("K"), Some("K"));
        assert!(flatten(&file).is_ok());
    }

    // C1: an absent unit on either side is exempt (the unchecked valid case),
    // even when the other side declares one.
    #[test]
    fn test_variable_map_identity_missing_unit_ok() {
        assert!(flatten(&identity_map_file(None, Some("degC"))).is_ok());
        assert!(flatten(&identity_map_file(Some("K"), None)).is_ok());
    }

    // ---- variable_map endpoint resolution (esm-spec §4.6 / §10.4) ----------

    /// A wrapper model whose SUBSYSTEM owns the coupling target: `Src.T` feeds
    /// the parameter `Wrap.inner.gain`, which `Wrap.inner`'s own ODE reads.
    /// `to_endpoint` is spelled by the caller so a wrong path can be probed.
    fn subsystem_map_file(to_endpoint: &str) -> EsmFile {
        let src = make_model(
            vec![("T", var(VariableType::Unknown, Some("K")))],
            vec![ddt("T", Expr::Number(1.0))],
        );
        let inner = make_model(
            vec![
                ("gain", var(VariableType::Parameter, Some("K"))),
                ("x", var(VariableType::Unknown, Some("K"))),
            ],
            vec![ddt("x", Expr::Variable("gain".to_string()))],
        );
        let mut subsystems = IndexMap::new();
        subsystems.insert(
            "inner".to_string(),
            serde_json::to_value(&inner).expect("model serializes"),
        );
        let wrap = Model {
            subsystems: Some(subsystems),
            ..Default::default()
        };

        let mut models = IndexMap::new();
        models.insert("Src".to_string(), src);
        models.insert("Wrap".to_string(), wrap);

        EsmFile {
            models: Some(models),
            coupling: Some(vec![CouplingEntry::VariableMap {
                from: "Src.T".to_string(),
                to: to_endpoint.to_string(),
                transform: VariableMapTransform::Named("param_to_var".to_string()),
                factor: None,
                lifting: None,
                description: None,
            }]),
            ..test_file()
        }
    }

    // A `to` endpoint reaching INTO a subsystem resolves by its FULL dot path:
    // the nested parameter is promoted away and the nested equation that read
    // it now reads the source. This is issue #198 item 1's first shape, and it
    // is the case a two-segment endpoint resolver cannot express.
    #[test]
    fn test_variable_map_into_subsystem_parameter_resolves() {
        let flat = flatten(&subsystem_map_file("Wrap.inner.gain")).expect("flattens");
        assert!(
            !flat.parameters.contains_key("Wrap.inner.gain"),
            "the nested target must be promoted away, got {:?}",
            flat.parameters.keys().collect::<Vec<_>>()
        );
        let rhs = &flat
            .equations
            .iter()
            .find(|e| {
                matches!(&e.lhs, Expr::Operator(n) if n.op == "D"
                && n.args.first() == Some(&Expr::Variable("Wrap.inner.x".to_string())))
            })
            .expect("the nested ODE survives")
            .rhs;
        assert_eq!(*rhs, Expr::Variable("Src.T".to_string()));
    }

    // The same edge spelled with a MISSING segment (`Wrap.gain` for a
    // parameter that lives at `Wrap.inner.gain`) resolves to nothing. It used
    // to flatten cleanly with the coupling silently dropped — the target kept
    // its declared default and nothing downstream could tell "applied" from
    // "ignored" (issue #198 item 1's third shape).
    #[test]
    fn test_variable_map_unresolved_to_endpoint_errors() {
        match flatten(&subsystem_map_file("Wrap.gain")).unwrap_err() {
            FlattenError::VariableMapUnresolvedEndpoint {
                side, endpoint, to, ..
            } => {
                assert_eq!(side, "to");
                assert_eq!(endpoint, "Wrap.gain");
                assert_eq!(to, "Wrap.gain");
            }
            other => panic!("expected VariableMapUnresolvedEndpoint, got {other:?}"),
        }
    }

    // A `from` that resolves to nothing is the NaN half: the substitution runs
    // regardless, so every consumer of `to` was rewritten to a name no table
    // binds and the run produced NaN rather than a diagnostic.
    #[test]
    fn test_variable_map_unresolved_from_endpoint_errors() {
        let mut file = subsystem_map_file("Wrap.inner.gain");
        if let Some(CouplingEntry::VariableMap { from, .. }) =
            file.coupling.as_mut().and_then(|c| c.first_mut())
        {
            *from = "Src.Nope.T".to_string();
        }
        match flatten(&file).unwrap_err() {
            FlattenError::VariableMapUnresolvedEndpoint { side, endpoint, .. } => {
                assert_eq!(side, "from");
                assert_eq!(endpoint, "Src.Nope.T");
            }
            other => panic!("expected VariableMapUnresolvedEndpoint, got {other:?}"),
        }
    }

    // C2: a pointwise-lift merged ODE whose operator makearray carries no
    // full-rank interior-stencil `index(...)` gather cannot resolve its grid
    // loop variables, and now surfaces DimensionPromotion (the reserved variant,
    // reused here for cross-binding parity) rather than the removed
    // PointwiseLiftFailed.
    #[test]
    fn test_pointwise_lift_failure_yields_dimension_promotion() {
        let makearray = Expr::operator(ExpressionNode {
            op: "makearray".to_string(),
            regions: Some(vec![vec![[
                crate::types::RegionBound::Int(1),
                crate::types::RegionBound::Int(3),
            ]]]),
            // Constant body — no `index(C, i)` interior stencil to read loops from.
            args: vec![Expr::Number(0.0)],
            ..Default::default()
        });
        let mut equations = vec![FlatEq::authored(
            ddt("C", makearray),
            TermOrigin::Component {
                component: "M".to_string(),
            },
        )];
        let loaded_producers: HashMap<String, usize> = HashMap::new();

        let mut lifted_shapes: IndexMap<String, Vec<i64>> = IndexMap::new();
        let err = apply_pointwise_lift(&mut equations, &mut lifted_shapes, &loaded_producers)
            .unwrap_err();
        match err {
            FlattenError::DimensionPromotion { message } => {
                assert!(message.contains("pointwise lift"), "message: {message}");
                assert!(message.contains("'C'"), "message: {message}");
            }
            other => panic!("expected DimensionPromotion, got {other:?}"),
        }
    }

    // Bug F regression: the unlowered-operator gate must descend into
    // expression-bearing sidecar fields, not merely `args`. A spatial/sugar op
    // buried in an `aggregate.expr` body — unreachable from `args` — previously
    // escaped `reject_spatial_operators` entirely. It must now be rejected with
    // the byte-identical `UnloweredOperator` diagnostic.
    #[test]
    fn test_reject_spatial_operator_hidden_in_aggregate_body() {
        let grad = Expr::operator(ExpressionNode {
            op: "grad".to_string(),
            args: vec![Expr::Variable("u".to_string())],
            ..Default::default()
        });
        let aggregate = Expr::operator(ExpressionNode {
            op: "faq".to_string(),
            // Nothing reachable through `args`; the op lives only in `expr`.
            args: vec![],
            expr: Some(Box::new(grad)),
            output_idx: Some(vec!["i".to_string()]),
            reduce: Some("+".to_string()),
            ..Default::default()
        });
        let err = reject_spatial_operators(&aggregate).unwrap_err();
        assert!(
            matches!(&err, FlattenError::UnloweredOperator { op } if op == "grad"),
            "expected UnloweredOperator{{grad}}, got {err:?}"
        );

        // A spatial `D` (wrt a spatial axis) hidden in a `filter` predicate is
        // likewise caught now that recursion goes through `for_each_child`.
        let spatial_d = Expr::operator(ExpressionNode {
            op: "D".to_string(),
            args: vec![Expr::Variable("u".to_string())],
            wrt: Some("x".to_string()),
            ..Default::default()
        });
        let filtered = Expr::operator(ExpressionNode {
            op: "faq".to_string(),
            args: vec![Expr::Variable("w".to_string())],
            filter: Some(Box::new(spatial_d)),
            reduce: Some("+".to_string()),
            ..Default::default()
        });
        let err = reject_spatial_operators(&filtered).unwrap_err();
        assert!(
            matches!(&err, FlattenError::UnloweredOperator { op } if op == "D"),
            "expected UnloweredOperator{{D}}, got {err:?}"
        );
    }

    // Bug E regression: `namespace_expr_scoped` must namespace variable
    // references inside an aggregate grouping `key` (a sidecar the previous
    // hand-rolled field enumeration omitted), while still honoring the bound
    // loop indices introduced by `output_idx`.
    #[test]
    fn test_namespace_expr_covers_aggregate_key() {
        let key = Expr::operator(ExpressionNode {
            op: "+".to_string(),
            args: vec![
                // A model variable — must be namespaced.
                Expr::Variable("region".to_string()),
                // A bound loop index — must stay bare.
                Expr::Variable("i".to_string()),
            ],
            ..Default::default()
        });
        let aggregate = Expr::operator(ExpressionNode {
            op: "faq".to_string(),
            args: vec![Expr::Variable("w".to_string())],
            output_idx: Some(vec!["i".to_string()]),
            key: Some(Box::new(key)),
            reduce: Some("+".to_string()),
            ..Default::default()
        });
        let out = namespace_expr(&aggregate, "sys", &HashSet::new(), &HashSet::new());
        match out {
            Expr::Operator(node) => {
                assert_eq!(node.args[0], Expr::Variable("sys.w".to_string()));
                let key = node.key.clone().expect("aggregate key preserved");
                match *key {
                    Expr::Operator(k) => {
                        assert_eq!(k.args[0], Expr::Variable("sys.region".to_string()));
                        assert_eq!(k.args[1], Expr::Variable("i".to_string()));
                    }
                    other => panic!("expected operator key, got {other:?}"),
                }
            }
            other => panic!("expected operator node, got {other:?}"),
        }
    }

    /// A pass over a FINISHED flattened system rewrites inside each
    /// contribution and rebuilds the right-hand side from the list, keeping the
    /// pointwise lift's `faq` wrapper around the sum (esm-libraries-spec §4.7.5).
    #[test]
    fn map_rhs_per_contribution_keeps_the_lift_wrapper() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/conformance/term_provenance/fixtures/pointwise_lift.esm");
        let file = crate::load_path(&path).expect("loads");
        let mut flat = flatten(&file).expect("flattens");
        let i = flat
            .equation_contributions
            .iter()
            .position(|cs| cs.len() == 3)
            .expect("the lifted equation has three contributions");
        let subs: HashMap<String, Expr> =
            std::iter::once(("Src.e".to_string(), Expr::Variable("Src.e2".to_string()))).collect();
        assert!(flat.equation_lifted[i], "the lift wrapped the equation");
        flat.map_rhs_per_contribution(|e| crate::substitute::substitute(e, &subs))
            .expect("the lists are in step");

        let contributions = &flat.equation_contributions[i];
        assert_eq!(contributions[1].expr, Expr::Variable("Src.e2".to_string()));
        let Expr::Operator(node) = &flat.equations[i].rhs else {
            panic!("the lifted right-hand side is an operator");
        };
        assert_eq!(node.op, "faq");
        assert_eq!(
            node.expr.as_deref(),
            Some(&fold_contributions(contributions))
        );
    }
}