cobre-io 0.15.0

Case directory loading and validation for the Cobre power systems ecosystem
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
//! Layer 5a — thermal-domain semantic validation.
//!
//! Thermal generation bounds (`min_generation_mw <= max_generation_mw`) and
//! anticipated-thermal cross-field invariants.

use std::collections::{HashMap, HashSet};

use chrono::{NaiveDate, TimeDelta};
use cobre_core::commissioning::commissioning_active;
use cobre_core::temporal::{
    Block, BlockMode, NoiseMethod, ScenarioSourceConfig, Stage, StageRiskConfig, StageStateConfig,
};
use cobre_core::{
    AnticipatedCommitmentHistory, AnticipatedConfig, EntityId, PostStudyStages, Thermal,
    VariableRef,
};
use cobre_stochastic::season_cast::{DatedWindow, StageCalendar};

use super::super::{ErrorKind, ValidationContext, schema::ParsedData};
use super::envelope_tolerance;

pub(super) fn check_thermal_generation_bounds(data: &ParsedData, ctx: &mut ValidationContext) {
    for thermal in &data.thermals {
        if thermal.min_generation_mw > thermal.max_generation_mw {
            let entity_str = format!("Thermal {}", thermal.id.0);
            ctx.add_error(
                ErrorKind::InvalidValue,
                "system/thermals.json",
                Some(&entity_str),
                format!(
                    "{entity_str}: min_generation_mw ({}) > max_generation_mw ({}); generation bounds are inconsistent",
                    thermal.min_generation_mw, thermal.max_generation_mw
                ),
            );
        }
    }
}

/// Checks cross-field invariants for anticipated thermal plants.
///
/// 1. **Per-plant lead horizon** — `LeadStages` rejects `K == 0` (defence in
///    depth; parse-time also rejects it). Both `LeadStages`'s `K > n_stages`
///    and `LeadTime`'s `delta_hours` exceeding the summed study-stage
///    durations (strict `>`, so a delivery landing exactly on the final stage
///    is accepted) reject only a thermal whose lead reaches NO declared
///    post-study stage: a thermal whose extended lead reaches a post-study
///    stage — decided in-study (`carried`) or decided pre-study
///    (`fixed_post_study`, the full-anticipation regime) — legitimately
///    delivers post-horizon, so it is exempt, identically for either lead
///    mode. Whether the lead reaches a post-study stage is resolved once per
///    thermal by `classify_deliveries`'s `carried` and `fixed_post_study`
///    sets over the concatenated study + post-study calendar — computed
///    independently of the solver crate's resolver (`cobre-io` is upstream
///    and cannot depend on it) — and shared by both guards. A commissioning
///    window IS supported and composes with the lookahead; these checks
///    validate the LEAD itself, independent of any window.
/// 2. **Horizon-straddle guard** — see `check_no_straddling_commitment_window`:
///    a `past_anticipated_commitments` window whose `[start_date, end_date)`
///    span crosses the study horizon end (`start_date < horizon_end &&
///    end_date > horizon_end`) is rejected, since it is unrepresentable by
///    either (3)'s study-side bijection or `check_post_study_stages`'s
///    post-study tiling and today silently prices its post-horizon tail at
///    zero. A window ending exactly at, or starting exactly at, the horizon is
///    accepted (purely in-study / purely post-study — two semantically
///    distinct coverages, so a straddling declaration must be split in two).
///    Gates (3)-(5) for the offending plant, since a straddling window's
///    coverage numbers are meaningless.
/// 3. **Past-commitments registry bijection** with
///    `ic.past_anticipated_commitments`: each anticipated thermal has at least
///    one commitment window, each window references an anticipated thermal, and
///    the plant's windows tile its leading `lead_delivery_stage_count` delivery
///    stages exactly (coverage `1.0`, no gap, no overlap, none beyond the
///    horizon) via the shared [`StageCalendar`] resolver — a hard gate, no
///    fallback (the "Pre-study anticipated commitments: calendar-derived
///    coverage" contract).
/// 4. **Committed-value generation bounds** — see `check_committed_value_bounds`.
/// 5. **Seed-vs-window consistency** — see `check_seed_within_window`.
pub(super) fn check_anticipated_thermals(data: &ParsedData, ctx: &mut ValidationContext) {
    // Study stages (id >= 0) are the contiguous suffix of the id-sorted stage
    // list; pre-study stages (negative IDs) are never delivery targets.
    let study_stages: &[Stage] = match data.stages.stages.iter().position(|s| s.id >= 0) {
        Some(idx) => &data.stages.stages[idx..],
        None => &[],
    };
    let study_stage_ids: Vec<i32> = study_stages.iter().map(|s| s.id).collect();
    let n_stages = study_stage_ids.len();
    let study_durations = study_stage_durations(data);
    let horizon_end = study_stages.last().map(|s| s.end_date);

    let extended_axis = build_extended_delivery_axis(data);

    for thermal in &data.thermals {
        let Some(ref cfg) = thermal.anticipated_config else {
            continue;
        };
        let thermal_id = thermal.id.0;

        let classes = classify_deliveries(
            *cfg,
            extended_axis.as_ref(),
            &study_durations,
            n_stages,
            (thermal.entry_stage_id, thermal.exit_stage_id),
        );
        // A plant reaching only fixed_post_study stages (empty carried) is
        // the full-anticipation regime — every in-study delivery decided
        // pre-study — and is fully representable; only beyond_reach (never
        // included here) means the plant truly cannot deliver. Shared by
        // both lead-mode guards below so `LeadStages` and `LeadTime` exempt
        // an equally-reachable plant identically.
        let reaches_post_study =
            !classes.carried.is_empty() || !classes.fixed_post_study.is_empty();

        if let AnticipatedConfig::LeadTime(delta_hours) = *cfg {
            let total_horizon_hours: f64 = study_durations.iter().sum();
            if delta_hours > total_horizon_hours && !reaches_post_study {
                let entity_str = format!("thermals[id={thermal_id}].anticipated_config.lead_time");
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "system/thermals.json",
                    Some(&entity_str),
                    format!(
                        "Thermal {thermal_id}: lead_time exceeds study horizon \
                         (lead_time={delta_hours}, total_horizon_hours={total_horizon_hours}); \
                         the plant can never deliver within the study horizon"
                    ),
                );
            }
        }

        let Some(k) = cfg.lead_stages() else {
            continue;
        };
        let entity_str = format!("thermals[id={thermal_id}].anticipated_config.lead_stages");

        if k == 0 {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "system/thermals.json",
                Some(&entity_str),
                format!("Thermal {thermal_id}: anticipated_config.lead_stages must be >= 1, got 0"),
            );
            continue;
        }

        let k_u = k as usize;

        if k_u > n_stages && !reaches_post_study {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "system/thermals.json",
                Some(&entity_str),
                format!(
                    "Thermal {thermal_id}: lead_stages exceeds study horizon \
                     (lead_stages={k}, n_stages={n_stages}); \
                     the plant can never deliver within the study horizon"
                ),
            );
        }
    }

    let ic = &data.initial_conditions;
    let windows_by_id = group_commitments_by_thermal(&ic.past_anticipated_commitments);

    // The resolver is only consulted for a thermal that carries commitment
    // windows; skip building it (and its ordered-calendar precondition) when
    // there are none to validate.
    let calendar = (!windows_by_id.is_empty()).then(|| StageCalendar::new(study_stages));

    let anticipated_thermal_ids: HashSet<EntityId> = data
        .thermals
        .iter()
        .filter(|t| t.anticipated_config.is_some())
        .map(|t| t.id)
        .collect();

    for thermal in &data.thermals {
        let Some(ref cfg) = thermal.anticipated_config else {
            continue;
        };
        let thermal_id = thermal.id;

        match windows_by_id.get(&thermal_id) {
            None => {
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "initial_conditions.json",
                    Some("initial_conditions.past_anticipated_commitments"),
                    format!(
                        "Thermal {}: missing entry in initial_conditions.past_anticipated_commitments; \
                         every anticipated thermal must have at least one commitment window",
                        thermal_id.0
                    ),
                );
            }
            Some(records) => {
                if let Some(horizon_end) = horizon_end
                    && !check_no_straddling_commitment_window(thermal_id, records, horizon_end, ctx)
                {
                    continue;
                }
                let Some(calendar) = calendar.as_ref() else {
                    continue;
                };
                let k_i = lead_delivery_stage_count(*cfg, &study_durations, n_stages);
                if check_commitment_coverage(
                    thermal_id,
                    records,
                    calendar,
                    k_i,
                    &study_stage_ids,
                    ctx,
                ) {
                    check_committed_value_bounds(thermal, thermal_id, records, ctx);
                    check_seed_within_window(
                        thermal,
                        thermal_id,
                        records,
                        calendar,
                        &study_stage_ids,
                        ctx,
                    );
                }
            }
        }
    }

    let mut reported: HashSet<EntityId> = HashSet::new();
    for history in &ic.past_anticipated_commitments {
        if !anticipated_thermal_ids.contains(&history.thermal_id)
            && reported.insert(history.thermal_id)
        {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "initial_conditions.json",
                Some(format!(
                    "initial_conditions.past_anticipated_commitments[thermal_id={}]",
                    history.thermal_id.0
                )),
                format!(
                    "Thermal {}: referenced in past_anticipated_commitments \
                     but is not an anticipated thermal (anticipated_config is None or thermal does not exist)",
                    history.thermal_id.0
                ),
            );
        }
    }
}

/// Advisory (`ModelQuality`): a `lead_stages`-configured thermal whose active
/// window — decision stage `t` through delivery `t + lead_stages`, `t` ranging
/// over the plant's commissioning window and the delivery side clamped to the
/// study horizon — spans a pair of adjacent study stages with differing
/// durations. A fixed stage-count lead delivers a different physical lead on
/// each side of such a cadence change; `anticipated_config.lead_time` anchors
/// the lead to physical hours instead and is immune to this. Never a hard error.
pub(super) fn check_anticipated_cadence_transition(data: &ParsedData, ctx: &mut ValidationContext) {
    let study_durations = study_stage_durations(data);
    let n_stages = study_durations.len();
    if n_stages < 2 {
        return;
    }

    for thermal in &data.thermals {
        let Some(cfg) = thermal.anticipated_config else {
            continue;
        };
        let Some(k) = cfg.lead_stages() else {
            continue;
        };
        let thermal_id = thermal.id.0;
        let k_u = usize::try_from(k).unwrap_or(usize::MAX);

        let decision_start = usize::try_from(thermal.entry_stage_id.unwrap_or(0).max(0))
            .unwrap_or(0)
            .min(n_stages - 1);
        let decision_end_id = thermal.exit_stage_id.map_or_else(
            || i32::try_from(n_stages - 1).unwrap_or(i32::MAX),
            |exit| exit - 1,
        );
        if decision_end_id < 0 {
            continue;
        }
        let decision_end = usize::try_from(decision_end_id)
            .unwrap_or(0)
            .min(n_stages - 1);
        if decision_start > decision_end {
            continue;
        }
        let window_end = decision_end.saturating_add(k_u).min(n_stages - 1);

        let entity_str = format!("thermals[id={thermal_id}].anticipated_config.lead_stages");
        for i in decision_start..window_end {
            let (prev, next) = (study_durations[i], study_durations[i + 1]);
            if (prev - next).abs() > 1e-9 {
                ctx.add_warning(
                    ErrorKind::ModelQuality,
                    "system/thermals.json",
                    Some(&entity_str),
                    format!(
                        "Thermal {thermal_id}: anticipated_config.lead_stages={k} active window \
                         spans a stage-cadence transition between stage {i} ({prev}h) and stage \
                         {} ({next}h); a fixed stage-count lead delivers a different physical \
                         lead on each side of the transition. Consider anticipated_config.lead_time, \
                         which anchors the lead to physical hours instead of a stage count.",
                        i + 1
                    ),
                );
                break;
            }
        }
    }
}

/// Group `histories` by `thermal_id`, preserving each plant's windows in
/// declared order. Shared by [`check_anticipated_thermals`] (study-side
/// coverage) and [`check_post_study_stages`] (post-study-side coverage) so
/// the two never drift on how a plant's windows are gathered.
fn group_commitments_by_thermal(
    histories: &[AnticipatedCommitmentHistory],
) -> HashMap<EntityId, Vec<&AnticipatedCommitmentHistory>> {
    let mut windows_by_id: HashMap<EntityId, Vec<&AnticipatedCommitmentHistory>> = HashMap::new();
    for history in histories {
        windows_by_id
            .entry(history.thermal_id)
            .or_default()
            .push(history);
    }
    windows_by_id
}

/// Study-stage (`id >= 0`) durations in canonical (ascending `id`) order, each
/// summed from its blocks. Computed independently of
/// `travel_time::study_stage_durations` (same shape, own walk) rather than
/// shared across files.
fn study_stage_durations(data: &ParsedData) -> Vec<f64> {
    data.stages
        .stages
        .iter()
        .filter(|s| s.id >= 0)
        .map(|s| s.blocks.iter().map(|b| b.duration_hours).sum())
        .collect()
}

/// Calendar-derived count of leading pre-study-committed delivery stages (the
/// study-only prefix `past_anticipated_commitments` must tile): `LeadStages(l)`
/// clamps `l` to `n_stages`; `LeadTime(delta)` counts the leading study stages
/// whose stage-end cumulative hours are `<= delta` (tie-inclusive). Both
/// deciders are monotonic in stage-end cumulative hours, so the pre-study run is
/// always the leading prefix `0..k`. The delivery-anchored reach INTO the
/// post-study calendar is resolved by `classify_deliveries`/`extended_deciders`
/// over the concatenated study + post-study calendar; this count stays
/// study-only. Computed independently of the solver crate's point-commitment
/// resolver (cobre-io is upstream and cannot depend on it), mirroring
/// `check_defluence_coverage`'s own calendar walk
/// (`validation/semantic/travel_time.rs`). Do not shortcut `LeadTime` to a stage
/// count from a window length — on a non-uniform calendar the cumulative-hours
/// walk and a bare length diverge.
fn lead_delivery_stage_count(
    mode: AnticipatedConfig,
    study_durations: &[f64],
    n_stages: usize,
) -> usize {
    match mode {
        AnticipatedConfig::LeadStages(lead_stages) => (lead_stages as usize).min(n_stages),
        AnticipatedConfig::LeadTime(delta_hours) => {
            let mut cumulative_hours = 0.0_f64;
            let mut count = 0usize;
            for &duration in study_durations.iter().take(n_stages) {
                cumulative_hours += duration;
                if cumulative_hours > delta_hours {
                    break;
                }
                count += 1;
            }
            count
        }
    }
}

/// The concatenated study + post-study delivery axis: extended per-stage
/// durations (hours) and the continued stage-id sequence, both length
/// `n_stages + n_post`. `None` when the study declares no `post_study_stages`,
/// so the delivery axis is the study axis and no lead can reach post-study.
///
/// Durations use each post-study stage's raw `duration_hours` and the ids
/// continue the study sequence (`max_study_id + 1 ..`), matching the solver's
/// own extended-axis concatenation and delivery-stage id sequence so the reach
/// resolved here and the ring the solver builds agree on which post-study stage
/// each delivery lands in.
struct ExtendedDeliveryAxis {
    /// Per-delivery-stage total hours, study durations then post-study durations.
    durations: Vec<f64>,
    /// Per-delivery-stage id, study ids then the continued post-study sequence.
    stage_ids: Vec<i32>,
    /// In-study (decision) stage count — the `[0, n_stages)` decision prefix.
    n_stages: usize,
}

/// Build the concatenated delivery axis, or `None` when `post_study_stages` is
/// absent. See `ExtendedDeliveryAxis` for the concatenation contract.
fn build_extended_delivery_axis(data: &ParsedData) -> Option<ExtendedDeliveryAxis> {
    let post_study = data.post_study_stages.as_ref()?;
    let study_durations = study_stage_durations(data);
    let n_stages = study_durations.len();
    let study_ids: Vec<i32> = data
        .stages
        .stages
        .iter()
        .filter(|s| s.id >= 0)
        .map(|s| s.id)
        .collect();
    let max_study_id = study_ids.last().copied().unwrap_or(-1);
    let durations: Vec<f64> = study_durations
        .iter()
        .copied()
        .chain(post_study.stages.iter().map(|s| s.duration_hours))
        .collect();
    let stage_ids: Vec<i32> = study_ids
        .into_iter()
        .chain(
            (0..post_study.stages.len())
                .map(|j| max_study_id + 1 + i32::try_from(j).unwrap_or(i32::MAX)),
        )
        .collect();
    Some(ExtendedDeliveryAxis {
        durations,
        stage_ids,
        n_stages,
    })
}

/// Delivery-anchored decider `c(m)` for each delivery stage `m` over the
/// concatenated calendar, mirroring the solver's `resolve_decider_*`:
/// `LeadStages(l)` shifts by a bare stage count (`c(m) = m − l`); `LeadTime(δ)`
/// anchors at the delivery stage's cumulative end (`c(m)` = the stage containing
/// `end_m − δ`, boundary ties resolving to the earlier stage). `None` is a
/// pre-study (initial-conditions) decider. Computed independently of the solver
/// crate's `resolve_point` (cobre-io is upstream and cannot depend on it). Do
/// not shortcut `LeadTime` to a bare window length — on a non-uniform calendar
/// the cumulative-hours walk and a bare length diverge.
fn extended_deciders(mode: AnticipatedConfig, durations: &[f64]) -> Vec<Option<usize>> {
    let n_delivery = durations.len();
    match mode {
        AnticipatedConfig::LeadStages(lead_stages) => {
            let lead = lead_stages as usize;
            (0..n_delivery).map(|m| m.checked_sub(lead)).collect()
        }
        AnticipatedConfig::LeadTime(delta_hours) => {
            let mut boundaries = Vec::with_capacity(n_delivery + 1);
            let mut cumulative = 0.0_f64;
            boundaries.push(cumulative);
            for &duration in durations {
                cumulative += duration;
                boundaries.push(cumulative);
            }
            (0..n_delivery)
                .map(|m| {
                    let target = boundaries[m + 1] - delta_hours;
                    boundaries
                        .partition_point(|&boundary| boundary < target)
                        .checked_sub(1)
                })
                .collect()
        }
    }
}

/// Post-study-relative classification of an anticipated plant's extended
/// delivery axis. Every post-study index `j` lands in exactly one of
/// `fixed_post_study`, `carried`, `beyond_reach`, and
/// `commissioning_inactive`; `leading_in_study` counts a disjoint, in-study
/// range.
struct DeliveryClasses {
    /// In-study deliveries decided pre-study — always the leading prefix
    /// `[0, k)`, since both deciders are monotonic in stage-end cumulative
    /// hours. Not yet read by a validator; reserved for the rule that will
    /// require a fixed commitment for this prefix.
    // RATIONALE: reserved seam (see field doc) plus a live debug-only consumer —
    // `classify_deliveries`'s `debug_assert_eq!` cross-checks it against the `None`
    // run of `extended_deciders`, and that read compiles out in release, so the
    // field reads as dead there. Removing it drops both the reserved seam and the
    // consistency check.
    #[allow(dead_code)]
    leading_in_study: usize,
    /// Post-study deliveries decided at a pre-study stage — each requires a
    /// tiled commitment window (V2).
    fixed_post_study: Vec<usize>,
    /// Post-study deliveries reached from an in-study, commissioning-active
    /// decision (a carrier — each needs a
    /// `PostStudyThermalBound(thermal_id, j)`).
    carried: Vec<usize>,
    /// Post-study deliveries decided post-study: past the plant's decision
    /// reach, unrepresentable by any in-study decision variable.
    beyond_reach: Vec<usize>,
    /// Post-study stages the plant's commissioning window excludes — where
    /// today's walk silently skips the index. Read by
    /// [`check_fixed_commitment_within_window`] to reject a non-zero fixed
    /// value there.
    commissioning_inactive: Vec<usize>,
}

/// Classify `window`'s deliveries over `axis` (`None` when the study declares
/// no post-study stages): `leading_in_study` resolves from
/// `lead_delivery_stage_count` regardless of `axis`; the four post-study
/// vectors resolve from `mode`'s extended decider and are empty when `axis`
/// is `None`. The commissioning gate keys on the DELIVERY stage's continued
/// id (`axis.stage_ids[m]`), uniformly at every delivery stage — a plant
/// whose `exit_stage_id` lies inside the study is inactive for every later
/// delivery, study or post-study — mirroring the solver's own
/// delivery-anchored gate. Do not shortcut `LeadTime` to a stage count from a
/// window length — on a non-uniform calendar the cumulative-hours walk and a
/// bare length diverge (the classifier reuses `lead_delivery_stage_count`'s
/// and `extended_deciders`' arithmetic, so the same trap applies here).
fn classify_deliveries(
    mode: AnticipatedConfig,
    axis: Option<&ExtendedDeliveryAxis>,
    study_durations: &[f64],
    n_stages: usize,
    window: (Option<i32>, Option<i32>),
) -> DeliveryClasses {
    let leading_in_study = lead_delivery_stage_count(mode, study_durations, n_stages);

    let Some(axis) = axis else {
        return DeliveryClasses {
            leading_in_study,
            fixed_post_study: Vec::new(),
            carried: Vec::new(),
            beyond_reach: Vec::new(),
            commissioning_inactive: Vec::new(),
        };
    };

    let (entry, exit) = window;
    let deciders = extended_deciders(mode, &axis.durations);
    // leading_in_study (a cumulative-hours count) and the None run over
    // deciders[..axis.n_stages] (a boundary partition_point) are two
    // independent walks that must agree; a drift here leaves the post-study
    // classes below keying on the wrong study/post-study boundary.
    debug_assert_eq!(
        leading_in_study,
        deciders[..axis.n_stages]
            .iter()
            .filter(|decider| decider.is_none())
            .count(),
        "leading_in_study must match the None run of extended_deciders over the study prefix"
    );

    let mut fixed_post_study = Vec::new();
    let mut carried = Vec::new();
    let mut beyond_reach = Vec::new();
    let mut commissioning_inactive = Vec::new();
    // `j` (the enumerate index over the post-study suffix) IS the post-study stage
    // index; `stage_ids[n_stages..]` and `deciders[n_stages..]` are the same length.
    for (j, (&stage_id, decider)) in axis.stage_ids[axis.n_stages..]
        .iter()
        .zip(&deciders[axis.n_stages..])
        .enumerate()
    {
        if !commissioning_active(entry, exit, stage_id) {
            commissioning_inactive.push(j);
            continue;
        }
        match decider {
            Some(c) if *c < axis.n_stages => carried.push(j),
            None => fixed_post_study.push(j),
            Some(_) => beyond_reach.push(j),
        }
    }

    debug_assert_eq!(
        fixed_post_study.len() + carried.len() + beyond_reach.len() + commissioning_inactive.len(),
        axis.stage_ids.len() - axis.n_stages,
        "the four post-study classes must partition every post-study index exactly once"
    );

    DeliveryClasses {
        leading_in_study,
        fixed_post_study,
        carried,
        beyond_reach,
        commissioning_inactive,
    }
}

/// Horizon-straddle guard (item 2 of [`check_anticipated_thermals`]): rejects
/// every window in `records` whose `[start_date, end_date)` span crosses
/// `horizon_end` (`start_date < horizon_end && end_date > horizon_end`) — a
/// single window cannot deliver both in-study and post-study coverage, and
/// left unchecked the post-study tail is silently priced at zero rather than
/// rejected. A window ending exactly at `horizon_end` (purely in-study) or
/// starting exactly at it (purely post-study) is accepted; the two are
/// semantically distinct coverages and must be declared as separate windows
/// split at the horizon. Returns whether every window passed, gating the
/// bijection/bounds/seed checks the caller runs next for this plant.
fn check_no_straddling_commitment_window(
    thermal_id: EntityId,
    records: &[&AnticipatedCommitmentHistory],
    horizon_end: NaiveDate,
    ctx: &mut ValidationContext,
) -> bool {
    let mut valid = true;
    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    for record in records {
        if record.start_date < horizon_end && record.end_date > horizon_end {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "initial_conditions.json",
                Some(&entity_str),
                format!(
                    "Thermal {}: past_anticipated_commitments window [{}, {}) straddles the \
                     study horizon end ({horizon_end}); a single window may not cover both \
                     in-study and post-study delivery. Declare two windows split at the \
                     horizon instead: one ending at {horizon_end} for the in-study coverage, \
                     one starting at {horizon_end} for the post-study coverage.",
                    thermal_id.0, record.start_date, record.end_date
                ),
            );
            valid = false;
        }
    }
    valid
}

/// A thermal's commitment windows must tile its leading `k_i` delivery stages
/// exactly: every leading stage covered at fraction `1.0` (via
/// [`StageCalendar::covers_exactly`]), and no window reaching any stage at or
/// beyond `k_i`. Emits a named `BusinessRuleViolation` for an uncovered leading
/// stage (gap) or a stage covered beyond the horizon (over-coverage); overlap
/// is rejected earlier by the shared windowed-record validator. Returns whether
/// coverage is exact, gating the per-window bounds/commissioning checks.
///
/// This is the study-side half of the coverage rule, checked against the study
/// [`StageCalendar`] only; the post-study half lives in
/// [`check_post_study_stages`]. Do not widen the range checked here onto a
/// post-horizon gap — this function has no post-study calendar to check it
/// against.
#[allow(clippy::float_cmp)] // whole-day-hours coverage keeps the per-stage tiling fraction bit-exact (mirrors covers_exactly)
fn check_commitment_coverage(
    thermal_id: EntityId,
    records: &[&AnticipatedCommitmentHistory],
    calendar: &StageCalendar,
    k_i: usize,
    study_stage_ids: &[i32],
    ctx: &mut ValidationContext,
) -> bool {
    let windows: Vec<DatedWindow> = records
        .iter()
        .map(|r| DatedWindow {
            start_date: r.start_date,
            end_date: r.end_date,
        })
        .collect();

    let mut per_stage = vec![0.0_f64; study_stage_ids.len()];
    for window in &windows {
        for (total, fraction) in per_stage.iter_mut().zip(calendar.coverage(window)) {
            *total += fraction;
        }
    }

    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    let mut valid = true;

    if !calendar.covers_exactly(&windows, k_i) {
        let uncovered: Vec<i32> = (0..k_i)
            .filter(|&i| per_stage[i] != 1.0)
            .map(|i| study_stage_ids[i])
            .collect();
        ctx.add_error(
            ErrorKind::BusinessRuleViolation,
            "initial_conditions.json",
            Some(&entity_str),
            format!(
                "Thermal {}: past_anticipated_commitments do not tile the leading {k_i} \
                 delivery stage(s) at coverage 1.0; study stage id(s) {uncovered:?} are not \
                 covered exactly once. Write a commitment window (a committed 0 MW is explicit) \
                 for every leading delivery stage.",
                thermal_id.0
            ),
        );
        valid = false;
    }

    let over_covered: Vec<i32> = (k_i..study_stage_ids.len())
        .filter(|&i| per_stage[i] != 0.0)
        .map(|i| study_stage_ids[i])
        .collect();
    if !over_covered.is_empty() {
        ctx.add_error(
            ErrorKind::BusinessRuleViolation,
            "initial_conditions.json",
            Some(&entity_str),
            format!(
                "Thermal {}: past_anticipated_commitments cover study stage id(s) {over_covered:?} \
                 beyond the leading {k_i} calendar-derived delivery stage(s); a commitment window \
                 may not cover a study stage the study itself decides. Shorten the plant's \
                 anticipated_config lead so its window stays within the leading {k_i} delivery \
                 stage(s).",
                thermal_id.0
            ),
        );
        valid = false;
    }

    valid
}

/// Every window's `value_mw` must lie within
/// `[min_generation_mw, max_generation_mw]`, within a relative-with-floor
/// tolerance at each boundary (a value set exactly at a bound may drift a hair
/// outside it in whatever pipeline generated it). For a window delivering
/// in-study, an out-of-tolerance value makes the LP infeasible at every
/// covered stage's fishing equality; for a window delivering post-horizon,
/// there is no LP to reject it — the value instead reaches the
/// terminal-boundary valuation and the reported outputs as generation the
/// plant cannot produce. `records` carries every window of the plant,
/// in-study and post-horizon alike, and this check never filters by which —
/// gated on the study-side coverage rule (`check_commitment_coverage`)
/// passing, never on the post-study coverage rules. `value_mw` finiteness is
/// the parse layer's contract (`initial_conditions.rs`'s call into
/// `crate::windowed_history::validate_windowed_records`), not re-checked
/// here.
fn check_committed_value_bounds(
    thermal: &Thermal,
    thermal_id: EntityId,
    records: &[&AnticipatedCommitmentHistory],
    ctx: &mut ValidationContext,
) {
    let min_mw = thermal.min_generation_mw;
    let max_mw = thermal.max_generation_mw;
    let min_tolerance = envelope_tolerance(min_mw);
    let max_tolerance = envelope_tolerance(max_mw);
    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    for record in records {
        let v = record.value_mw;
        if v < min_mw - min_tolerance || v > max_mw + max_tolerance {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "initial_conditions.json",
                Some(&entity_str),
                format!(
                    "Thermal {}: past_anticipated_commitments window [{}, {}) value_mw = {v} \
                     is outside the plant's generation bounds [{min_mw}, {max_mw}]; \
                     the LP delivery equality on the covered stage(s) cannot be \
                     satisfied and the LP will be infeasible",
                    thermal_id.0, record.start_date, record.end_date
                ),
            );
        }
    }
}

/// For a windowed anticipated thermal, reject any nonzero `value_mw` maturing at
/// a covered study stage outside the operation window: the matured generation
/// column is pinned to `[0, 0]` there, so the always-active fishing equality
/// reads `0 == seed` — an infeasible LP. A zero rate is consistent at any stage
/// and allowed.
///
/// The window predicate is the LP builder's own
/// `cobre_core::commissioning::commissioning_active`, so validation and the
/// builder cannot drift on what an infeasible seed is. Each window's covered
/// study stages are resolved through the shared [`StageCalendar`], so a window
/// straddling the commissioning boundary is checked stage-by-stage.
#[allow(clippy::float_cmp)] // day-aligned coverage is exactly 0 or nonzero per stage; the zero-rate skip is a bit-exact test
fn check_seed_within_window(
    thermal: &Thermal,
    thermal_id: EntityId,
    records: &[&AnticipatedCommitmentHistory],
    calendar: &StageCalendar,
    study_stage_ids: &[i32],
    ctx: &mut ValidationContext,
) {
    let entry = thermal.entry_stage_id;
    let exit = thermal.exit_stage_id;
    if entry.is_none() && exit.is_none() {
        return;
    }
    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    for record in records {
        let v = record.value_mw;
        if v == 0.0 {
            continue;
        }
        let window = DatedWindow {
            start_date: record.start_date,
            end_date: record.end_date,
        };
        for (i, fraction) in calendar.coverage(&window).into_iter().enumerate() {
            if fraction == 0.0 {
                continue;
            }
            let stage_id = study_stage_ids[i];
            if !commissioning_active(entry, exit, stage_id) {
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "initial_conditions.json",
                    Some(&entity_str),
                    format!(
                        "Thermal {}: past_anticipated_commitments window [{}, {}) value_mw = {v} \
                         matures at study stage id {stage_id}, which is outside the \
                         plant's commissioning window [entry={entry:?}, exit={exit:?}); \
                         the matured generation column is pinned to [0, 0] there, so the \
                         fishing equality reads 0 == {v} and the LP is infeasible. \
                         Commit a zero rate at this stage or widen the window.",
                        thermal_id.0, record.start_date, record.end_date
                    ),
                );
            }
        }
    }
}

/// The post-study counterpart of [`check_seed_within_window`]: a non-zero
/// fixed value maturing at a `commissioning_inactive` post-study stage is a
/// modelling contradiction — the plant is not in service for that stage, so
/// the value can never be delivered. Unlike the in-study rule, there is no LP
/// column here to make infeasible; left unchecked, the value would instead be
/// folded into the terminal-boundary valuation and reported as a delivery
/// from a plant that is not in service. A zero-valued window over an
/// inactive stage stays legitimate (a blanket zero across the plant's
/// post-study span).
///
/// `commissioning_inactive` is read from [`DeliveryClasses`], never
/// re-derived: it is already keyed on the delivery stage's continued id, the
/// same predicate the solver's own commissioning gate uses. Coverage is
/// computed per record, not read from the accumulated per-stage vector V2/V3
/// share — naming the offending window's dates needs to know which window
/// covered the stage, which the accumulated vector cannot say.
#[allow(clippy::float_cmp)] // whole-day-hours coverage keeps the per-stage fraction bit-exact (mirrors check_seed_within_window)
fn check_fixed_commitment_within_window(
    thermal: &Thermal,
    thermal_id: EntityId,
    records: &[&AnticipatedCommitmentHistory],
    post_calendar: &StageCalendar,
    commissioning_inactive: &[usize],
    ctx: &mut ValidationContext,
) {
    let entry = thermal.entry_stage_id;
    let exit = thermal.exit_stage_id;
    if entry.is_none() && exit.is_none() {
        return;
    }
    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    for record in records {
        let v = record.value_mw;
        if v == 0.0 {
            continue;
        }
        let window = DatedWindow {
            start_date: record.start_date,
            end_date: record.end_date,
        };
        let coverage = post_calendar.coverage(&window);
        for &j in commissioning_inactive {
            if coverage[j] == 0.0 {
                continue;
            }
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "post_study_stages.json",
                Some(&entity_str),
                format!(
                    "Thermal {}: past_anticipated_commitments window [{}, {}) value_mw = {v} \
                     covers post-study stage index {j}, which is outside the plant's \
                     commissioning window [entry={entry:?}, exit={exit:?}); the plant is not \
                     in service for this stage and the fixed commitment cannot be delivered. \
                     Declare a zero commitment at this stage, or widen the commissioning window.",
                    thermal_id.0, record.start_date, record.end_date
                ),
            );
        }
    }
}

/// Layer 5a — rejects use of `anticipated_decision(N)` in a generic constraint
/// when thermal `N` does not have `anticipated_config: Some(_)`.
///
/// `anticipated_decision` is an LP column that only exists for plants committed
/// in advance. Referencing a non-anticipated thermal via this variant is always
/// a model error: the column does not appear in the LP and the constraint would
/// silently become an equality 0 = bound, which is either trivially satisfied
/// or immediately infeasible.
pub(super) fn check_anticipated_decision_target_is_anticipated(
    data: &ParsedData,
    ctx: &mut ValidationContext,
) {
    let anticipated_ids: HashSet<EntityId> = data
        .thermals
        .iter()
        .filter(|t| t.anticipated_config.is_some())
        .map(|t| t.id)
        .collect();

    for constraint in &data.generic_constraints {
        for term in &constraint.expression.terms {
            if let VariableRef::AnticipatedDecision { thermal_id } = term.variable
                && !anticipated_ids.contains(&thermal_id)
            {
                let entity_str = format!("constraint[id={}]", constraint.id.0);
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "constraints/generic_constraints.json",
                    Some(&entity_str),
                    format!(
                        "Constraint \"{}\": anticipated_decision({}) references Thermal {} \
                             which is not an anticipated thermal (anticipated_config is None). \
                             The anticipated_decision column only exists for plants with \
                             anticipated_config set.",
                        constraint.name, thermal_id.0, thermal_id.0,
                    ),
                );
            }
        }
    }
}

/// Layer 5a — warns when `thermal_generation(N)` is used in a generic
/// constraint and thermal `N` is anticipated.
///
/// `thermal_generation` for an anticipated thermal references the per-block
/// generation at the *delivery* stage, not the *commitment* made at the current
/// stage. This is valid but surprising; to constrain the commitment use
/// `anticipated_decision(N)` instead. Emits a `SemanticAmbiguity` warning.
pub(super) fn warn_thermal_generation_on_anticipated_thermal(
    data: &ParsedData,
    ctx: &mut ValidationContext,
) {
    let anticipated_ids: HashSet<EntityId> = data
        .thermals
        .iter()
        .filter(|t| t.anticipated_config.is_some())
        .map(|t| t.id)
        .collect();

    if anticipated_ids.is_empty() {
        return;
    }

    for constraint in &data.generic_constraints {
        for term in &constraint.expression.terms {
            if let VariableRef::ThermalGeneration { thermal_id, .. } = term.variable
                && anticipated_ids.contains(&thermal_id)
            {
                let entity_str = format!("constraint[id={}]", constraint.id.0);
                ctx.add_warning(
                    ErrorKind::SemanticAmbiguity,
                    "constraints/generic_constraints.json",
                    Some(&entity_str),
                    format!(
                        "Constraint \"{}\": thermal_generation({id}) references an \
                             anticipated thermal. thermal_generation refers to the \
                             per-block generation at the delivery stage, not the \
                             forward commitment. If you intend to constrain the \
                             commitment itself, use anticipated_decision({id}) instead.",
                        constraint.name,
                        id = thermal_id.0,
                    ),
                );
            }
        }
    }
}

/// Layer 5a — rejects per-stage thermal bound overrides whose `stage_id` is
/// outside the study horizon `[0, n_stages)`.
///
/// The thermal-bounds resolution table is padded with each plant's base entity
/// values for stages `[n_stages, n_stages + K_max)` to support
/// anticipated-delivery lookups. Overrides in that padded region would be
/// silently dropped by `resolve_bounds` (the `stage_index` only covers study
/// stages); this validator surfaces them as a user-visible error.
pub(super) fn check_thermal_bounds_override_stage_range(
    data: &ParsedData,
    ctx: &mut ValidationContext,
) {
    // Study stages only (id >= 0), matching the resolver's `stage_index`; a
    // mismatch here would reject overrides the resolver actually applies.
    let n_stages = data.stages.stages.iter().filter(|s| s.id >= 0).count();
    let n_stages_i = i64::try_from(n_stages).unwrap_or(i64::MAX);
    for row in &data.thermal_bounds {
        let s = i64::from(row.stage_id);
        if s < 0 || s >= n_stages_i {
            let entity_str = format!("thermal_id={}, stage_id={}", row.thermal_id.0, row.stage_id);
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "constraints/thermal_bounds.parquet",
                Some(&entity_str),
                format!(
                    "Thermal {}: thermal_bounds override at stage_id={} is \
                     outside the study horizon [0, {}); per-stage thermal \
                     overrides past the horizon are not allowed",
                    row.thermal_id.0, row.stage_id, n_stages
                ),
            );
        }
    }
}

/// Layer 5a — validates the standalone `post_study_stages.json` boundary input,
/// the sole post-horizon surface, against the study calendar.
///
/// Rejects unless:
/// - (a) the post-study stages are date-contiguous and the first `start_date`
///   equals the study horizon end (`study_stages.last().end_date`);
/// - **Rule 1 (missing bound cell)** — every post-study stage index `j` an
///   anticipated thermal's extended lead reaches (from an in-study,
///   commissioning-active decision, resolved by `classify_deliveries`) has a
///   `PostStudyThermalBound(thermal_id, j)`. A missing cell is the sole surface's
///   analogue of the retired lane subsystem's silent `[0, 0]` degradation
///   (finiteness / `min_mw <= max_mw` remain the reader's parse-layer contract).
/// - **V2 (fixed post-horizon tiling)** — every post-study stage index in the
///   plant's `fixed_post_study` class (deliveries decided at a pre-study
///   stage) is tiled by `initial_conditions.past_anticipated_commitments` at
///   coverage `1.0` over the post-study calendar, an explicit `0 MW` window
///   included — the same commitment-window convention
///   [`check_anticipated_thermals`] already applies to the study side. A
///   `commissioning_inactive` post-study stage is never a member of
///   `fixed_post_study`, so V2 never demands a window there; do not read V2 as
///   requiring tiling over every post-study stage — only class 4 is covered.
/// - **V3 (no window on an unreachable stage)** — no commitment window covers a
///   post-study stage in the plant's `carried` class (the study itself decides
///   that delivery) or its `beyond_reach` class (past the plant's decision
///   reach, unrepresentable). The two causes are reported as distinct errors —
///   their remedies are opposite (lengthen vs. shorten the lead). A
///   `commissioning_inactive` post-study stage is exempt from V3: a declared
///   window there is inert, not contradictory (a later rule rejects a
///   *nonzero* value there instead). Together, V2 and V3 complete the
///   coverage rule: a plant's covered post-study stages must be *exactly* its
///   `fixed_post_study` class — V2 supplies "at least", V3 supplies "at most".
/// - **V5 (fixed value outside the commissioning window)** — a non-zero fixed
///   value covering a `commissioning_inactive` post-study stage is rejected: the
///   plant is not in service for that stage, so the value can never be
///   delivered. Mirrors the in-study seed rule
///   ([`check_seed_within_window`]) without its infeasibility claim — there is
///   no LP column post-horizon. An explicit zero-valued window over an
///   inactive stage stays legitimate.
///
/// Each failure is a `BusinessRuleViolation` naming the offending plant (and the
/// post-study stage(s), for Rule 1 / V2 / V3 / V5 / for (a)). No rule short-circuits
/// another; a study without `post_study_stages.json` is validated in
/// [`check_anticipated_thermals`] (a `lead > horizon` plant with no post-study
/// stages is a hard reject there). A `past_anticipated_commitments` window
/// straddling the study horizon is also rejected there, before this
/// function's coverage rules run, so V2/V3 may assume no window straddles the
/// horizon end.
pub(super) fn check_post_study_stages(data: &ParsedData, ctx: &mut ValidationContext) {
    let Some(post_study) = data.post_study_stages.as_ref() else {
        return;
    };

    let study_end = data
        .stages
        .stages
        .iter()
        .rfind(|s| s.id >= 0)
        .map(|s| s.end_date);

    let (calendar_stages, well_formed) = build_post_study_calendar(post_study, study_end, ctx);
    if !well_formed || calendar_stages.is_empty() {
        return;
    }

    let Some(axis) = build_extended_delivery_axis(data) else {
        return;
    };
    let study_durations = study_stage_durations(data);

    let bound_cells: HashSet<(EntityId, usize)> = post_study
        .thermal_bounds
        .iter()
        .map(|b| (b.thermal_id, b.post_study_stage_index))
        .collect();

    let windows_by_id =
        group_commitments_by_thermal(&data.initial_conditions.past_anticipated_commitments);
    let post_calendar = StageCalendar::new(&calendar_stages);

    for thermal in &data.thermals {
        let Some(cfg) = thermal.anticipated_config else {
            continue;
        };
        let classes = classify_deliveries(
            cfg,
            Some(&axis),
            &study_durations,
            axis.n_stages,
            (thermal.entry_stage_id, thermal.exit_stage_id),
        );
        let entity_str = format!("thermals[id={}].anticipated_config", thermal.id.0);

        for &j in &classes.carried {
            if !bound_cells.contains(&(thermal.id, j)) {
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "post_study_stages.json",
                    Some(&entity_str),
                    format!(
                        "Thermal {}: anticipated lead reaches post-study stage index {j}, but \
                         post_study_stages.json has no thermal_bounds entry for (thermal_id {}, \
                         post_study_stage_index {j}).",
                        thermal.id.0, thermal.id.0
                    ),
                );
            }
        }

        let windows = windows_by_id
            .get(&thermal.id)
            .map(Vec::as_slice)
            .unwrap_or_default();
        let per_stage =
            post_study_coverage_per_stage(windows, &post_calendar, calendar_stages.len());
        check_fixed_post_study_tiling(thermal.id, &per_stage, &classes.fixed_post_study, ctx);
        check_post_study_window_excludes_unreachable_stages(
            thermal.id,
            &per_stage,
            &classes.carried,
            &classes.beyond_reach,
            ctx,
        );
        check_fixed_commitment_within_window(
            thermal,
            thermal.id,
            windows,
            &post_calendar,
            &classes.commissioning_inactive,
            ctx,
        );
    }
}

/// Per-post-study-stage coverage fraction from `windows`, accumulated once
/// over `post_calendar`. V2's tiling check and V3's carried/beyond-reach
/// rejection both read this same vector rather than each re-walking the
/// windows, so the two rules can never disagree about which calendar is in
/// play.
fn post_study_coverage_per_stage(
    windows: &[&AnticipatedCommitmentHistory],
    post_calendar: &StageCalendar,
    n_post_study_stages: usize,
) -> Vec<f64> {
    let dated: Vec<DatedWindow> = windows
        .iter()
        .map(|r| DatedWindow {
            start_date: r.start_date,
            end_date: r.end_date,
        })
        .collect();

    let mut per_stage = vec![0.0_f64; n_post_study_stages];
    for window in &dated {
        for (total, fraction) in per_stage.iter_mut().zip(post_calendar.coverage(window)) {
            *total += fraction;
        }
    }
    per_stage
}

/// V2: every index in `fixed_post_study` must be tiled by `per_stage` at
/// coverage `1.0`, mirroring [`check_commitment_coverage`]'s study-side walk
/// on the other calendar. Emits one `BusinessRuleViolation` naming every
/// uncovered index; a `commissioning_inactive` post-study stage is never a
/// member of `fixed_post_study`, so it is never demanded here. No-op when
/// `fixed_post_study` is empty — the common case, every existing deck.
#[allow(clippy::float_cmp)] // whole-day-hours coverage keeps the per-stage tiling fraction bit-exact (mirrors check_commitment_coverage)
fn check_fixed_post_study_tiling(
    thermal_id: EntityId,
    per_stage: &[f64],
    fixed_post_study: &[usize],
    ctx: &mut ValidationContext,
) {
    if fixed_post_study.is_empty() {
        return;
    }

    let uncovered: Vec<usize> = fixed_post_study
        .iter()
        .copied()
        .filter(|&j| per_stage[j] != 1.0)
        .collect();
    if uncovered.is_empty() {
        return;
    }

    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);
    ctx.add_error(
        ErrorKind::BusinessRuleViolation,
        "post_study_stages.json",
        Some(&entity_str),
        format!(
            "Thermal {}: past_anticipated_commitments do not tile post-study stage \
             index(es) {uncovered:?} at coverage 1.0; declare the fixed commitment for \
             each (a committed 0 MW is explicit).",
            thermal_id.0
        ),
    );
}

/// V3: a commitment window may not cover a post-study stage the study itself
/// decides (`carried`) or one past the plant's decision reach
/// (`beyond_reach`); the remedies are opposite — lengthen the lead so a
/// carried stage becomes pre-study-decided, or shorten it so a beyond-reach
/// stage falls back inside reach — so each cause is reported as its own
/// error, never merged. A `commissioning_inactive` stage is exempt: a
/// declared window there is inert, not contradictory. No-op when neither
/// class has a covered index — the common case, every existing deck.
#[allow(clippy::float_cmp)] // whole-day-hours coverage keeps the per-stage tiling fraction bit-exact (mirrors check_commitment_coverage)
fn check_post_study_window_excludes_unreachable_stages(
    thermal_id: EntityId,
    per_stage: &[f64],
    carried: &[usize],
    beyond_reach: &[usize],
    ctx: &mut ValidationContext,
) {
    let entity_str = format!("thermals[id={}].anticipated_config", thermal_id.0);

    let covered_carried: Vec<usize> = carried
        .iter()
        .copied()
        .filter(|&j| per_stage[j] != 0.0)
        .collect();
    if !covered_carried.is_empty() {
        ctx.add_error(
            ErrorKind::BusinessRuleViolation,
            "post_study_stages.json",
            Some(&entity_str),
            format!(
                "Thermal {}: past_anticipated_commitments cover post-study stage \
                 index(es) {covered_carried:?}, which the study itself decides; a declared \
                 fixed value there contradicts the study's own decision. Remove the window, \
                 or lengthen anticipated_config's lead so the delivery becomes \
                 pre-study-decided.",
                thermal_id.0
            ),
        );
    }

    let covered_beyond_reach: Vec<usize> = beyond_reach
        .iter()
        .copied()
        .filter(|&j| per_stage[j] != 0.0)
        .collect();
    if !covered_beyond_reach.is_empty() {
        ctx.add_error(
            ErrorKind::BusinessRuleViolation,
            "post_study_stages.json",
            Some(&entity_str),
            format!(
                "Thermal {}: past_anticipated_commitments cover post-study stage \
                 index(es) {covered_beyond_reach:?}, which are past the plant's decision \
                 reach and cannot be represented. Remove the window, or shorten \
                 anticipated_config's lead so the delivery falls inside the reach.",
                thermal_id.0
            ),
        );
    }
}

/// Build the post-study calendar as `Stage`s (each `end_date` = `start_date`
/// advanced by `duration_hours` rounded to whole days — the whole-day alignment
/// [`StageCalendar`] coverage needs, mirroring the pre-study duration→days round
/// in `travel_time`), enforcing invariant (a). Returns the stages and whether
/// they are well-formed; a non-well-formed calendar suppresses the coverage pass
/// so its errors are not noise on a broken calendar.
fn build_post_study_calendar(
    post_study: &PostStudyStages,
    study_end: Option<NaiveDate>,
    ctx: &mut ValidationContext,
) -> (Vec<Stage>, bool) {
    let mut calendar_stages: Vec<Stage> = Vec::with_capacity(post_study.stages.len());
    let mut well_formed = true;

    for (i, stage) in post_study.stages.iter().enumerate() {
        match post_study_end_date(stage.start_date, stage.duration_hours) {
            Some(end_date) if end_date > stage.start_date => {
                calendar_stages.push(make_calendar_stage(
                    i,
                    stage.start_date,
                    end_date,
                    stage.duration_hours,
                ));
            }
            _ => {
                ctx.add_error(
                    ErrorKind::BusinessRuleViolation,
                    "post_study_stages.json",
                    Some(format!("stages[{i}]")),
                    format!(
                        "post-study stage starting {} has duration_hours {} that rounds to a \
                         non-positive whole-day span; declare a duration of at least a day.",
                        stage.start_date, stage.duration_hours
                    ),
                );
                well_formed = false;
            }
        }
    }

    match (calendar_stages.first(), study_end) {
        (Some(first), Some(end)) if first.start_date != end => {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "post_study_stages.json",
                Some("stages[0].start_date"),
                format!(
                    "first post-study stage starts {} but the study horizon ends {}; the \
                     post-study calendar must begin exactly at the study horizon end.",
                    first.start_date, end
                ),
            );
            well_formed = false;
        }
        (Some(_), None) => {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "post_study_stages.json",
                Some("stages"),
                "post_study_stages.json is declared but the study has no study stages to anchor \
                 the post-study calendar against."
                    .to_string(),
            );
            well_formed = false;
        }
        _ => {}
    }

    for pair in calendar_stages.windows(2) {
        if pair[0].end_date != pair[1].start_date {
            ctx.add_error(
                ErrorKind::BusinessRuleViolation,
                "post_study_stages.json",
                Some(format!("stages start_date={}", pair[1].start_date)),
                format!(
                    "post-study stages are not date-contiguous: the stage starting {} ends {} \
                     but the next stage starts {}; each stage must end exactly where the next \
                     begins.",
                    pair[0].start_date, pair[0].end_date, pair[1].start_date
                ),
            );
            well_formed = false;
        }
    }

    (calendar_stages, well_formed)
}

/// Post-study stage end date: `start_date` advanced by `duration_hours` rounded
/// to whole days. `None` only on calendar overflow.
#[allow(clippy::cast_possible_truncation)] // a validated finite positive duration yields a small non-negative day count
fn post_study_end_date(start_date: NaiveDate, duration_hours: f64) -> Option<NaiveDate> {
    let days = (duration_hours / 24.0).round() as i64;
    start_date.checked_add_signed(TimeDelta::days(days))
}

/// Synthesize a `Stage` carrying only the fields [`StageCalendar`] reads
/// (`start_date`, `end_date`, `blocks`); the rest are inert placeholders.
fn make_calendar_stage(
    index: usize,
    start_date: NaiveDate,
    end_date: NaiveDate,
    duration_hours: f64,
) -> Stage {
    Stage {
        index,
        id: i32::try_from(index).unwrap_or(i32::MAX),
        start_date,
        end_date,
        season_id: None,
        blocks: vec![Block {
            index: 0,
            name: "post_study".to_string(),
            duration_hours,
        }],
        block_mode: BlockMode::Parallel,
        state_config: StageStateConfig {
            storage: true,
            inflow_lags: false,
        },
        risk_config: StageRiskConfig::Expectation,
        scenario_config: ScenarioSourceConfig {
            branching_factor: 1,
            noise_method: NoiseMethod::Saa,
        },
    }
}

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::panic,
    clippy::too_many_lines,
    clippy::doc_markdown,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss
)]
mod tests {
    use cobre_core::temporal::{Block, PolicyGraphType, Stage};
    use cobre_core::{
        AnticipatedCommitmentHistory, AnticipatedConfig, EntityId, HorizonGraph, PostStudyStage,
        PostStudyStages, PostStudyThermalBound, Thermal,
    };

    use chrono::{NaiveDate, TimeDelta};

    use super::super::test_support::*;
    use super::super::validate_semantic_hydro_thermal;
    use super::{
        ExtendedDeliveryAxis, build_extended_delivery_axis, check_anticipated_thermals,
        check_post_study_stages, classify_deliveries, extended_deciders, lead_delivery_stage_count,
    };
    use crate::stages::StagesData;
    use crate::validation::schema::ParsedData;
    use crate::validation::{ErrorKind, ValidationContext};

    // ── Helper: build a thermal with anticipated_config ───────────────────────

    fn make_anticipated_thermal(
        id: i32,
        lead_stages: u32,
        entry_stage_id: Option<i32>,
        exit_stage_id: Option<i32>,
    ) -> Thermal {
        Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(lead_stages)),
            entry_stage_id,
            exit_stage_id,
            ..make_thermal(id, 0.0, 500.0)
        }
    }

    /// Build a `LeadTime`-configured thermal.
    fn make_lead_time_anticipated_thermal(
        id: i32,
        lead_time_hours: f64,
        entry_stage_id: Option<i32>,
        exit_stage_id: Option<i32>,
    ) -> Thermal {
        Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadTime(lead_time_hours)),
            entry_stage_id,
            exit_stage_id,
            ..make_thermal(id, 0.0, 500.0)
        }
    }

    /// Anchor of every anticipated-thermal test calendar; stage 0 starts here.
    fn calendar_anchor() -> NaiveDate {
        NaiveDate::from_ymd_opt(2024, 1, 1).unwrap()
    }

    /// Contiguous stage boundary dates for a calendar whose stage `i` spans
    /// `durations_hours[i] / 24` whole days from [`calendar_anchor`]; length is
    /// `durations_hours.len() + 1`. Every fixture duration is a whole-day
    /// multiple so the date span and block hours agree, the alignment
    /// [`StageCalendar`] coverage needs.
    fn stage_boundaries(durations_hours: &[f64]) -> Vec<NaiveDate> {
        let mut cursor = calendar_anchor();
        let mut dates = vec![cursor];
        for &hours in durations_hours {
            cursor += TimeDelta::days((hours / 24.0) as i64);
            dates.push(cursor);
        }
        dates
    }

    /// Contiguous study stages (ids `0..durations_hours.len()`), stage `i` a
    /// single block of `durations_hours[i]` over `[boundary[i], boundary[i+1])`.
    fn contiguous_stages(durations_hours: &[f64]) -> Vec<Stage> {
        let boundaries = stage_boundaries(durations_hours);
        durations_hours
            .iter()
            .enumerate()
            .map(|(i, &hours)| {
                let mut stage = make_stage(i as i32);
                stage.index = i;
                stage.start_date = boundaries[i];
                stage.end_date = boundaries[i + 1];
                stage.blocks = vec![Block {
                    index: 0,
                    name: "S".to_string(),
                    duration_hours: hours,
                }];
                stage
            })
            .collect()
    }

    /// One commitment window per value, tiling the leading `values.len()` stages
    /// of the contiguous calendar defined by `durations_hours`. `values.len()`
    /// may differ from `durations_hours.len()` (fewer → gap; more → beyond the
    /// horizon) to build the coverage-failure fixtures.
    fn commitments_on(
        thermal_id: i32,
        values: &[f64],
        durations_hours: &[f64],
    ) -> Vec<AnticipatedCommitmentHistory> {
        let boundaries = stage_boundaries(durations_hours);
        values
            .iter()
            .enumerate()
            .map(|(i, &value_mw)| AnticipatedCommitmentHistory {
                thermal_id: EntityId::from(thermal_id),
                start_date: boundaries[i],
                end_date: boundaries[i + 1],
                value_mw,
            })
            .collect()
    }

    /// One commitment window per value on the uniform 30-day calendar
    /// [`make_data_anticipated`] builds — value `i` delivers over study stage
    /// `i`.
    fn commitments(thermal_id: i32, values: &[f64]) -> Vec<AnticipatedCommitmentHistory> {
        commitments_on(thermal_id, values, &vec![720.0; values.len().max(1)])
    }

    /// Assemble `ParsedData` from a contiguous stage calendar and commitments.
    fn anticipated_data(
        thermals: Vec<Thermal>,
        durations_hours: &[f64],
        past_anticipated_commitments: Vec<AnticipatedCommitmentHistory>,
    ) -> ParsedData {
        let stages_data = StagesData {
            openings_declared: std::collections::HashSet::new(),
            stages: contiguous_stages(durations_hours),
            policy_graph: HorizonGraph {
                stage_discount_rate_overrides: std::collections::HashMap::new(),
                graph_type: PolicyGraphType::FiniteHorizon,
                annual_discount_rate: 0.06,
                transitions: vec![],
                nodes: Vec::new(),
                season_map: None,
            },
        };
        let mut data = make_data(vec![], thermals, vec![], stages_data, vec![], vec![]);
        data.initial_conditions.past_anticipated_commitments = past_anticipated_commitments;
        data
    }

    /// Build `ParsedData` for anticipated-thermal tests on a non-uniform
    /// per-stage calendar (`durations_hours`, one entry per study stage,
    /// `id = 0..durations_hours.len()`).
    fn make_data_anticipated_with_durations(
        thermals: Vec<Thermal>,
        durations_hours: &[f64],
        past_anticipated_commitments: Vec<AnticipatedCommitmentHistory>,
    ) -> ParsedData {
        anticipated_data(thermals, durations_hours, past_anticipated_commitments)
    }

    /// Build `ParsedData` for anticipated-thermal tests on a uniform 30-day
    /// (720 h) calendar of `n_stages` stages with IDs `0..n_stages`.
    fn make_data_anticipated(
        thermals: Vec<Thermal>,
        n_stages: usize,
        past_anticipated_commitments: Vec<AnticipatedCommitmentHistory>,
    ) -> ParsedData {
        anticipated_data(
            thermals,
            &vec![720.0; n_stages],
            past_anticipated_commitments,
        )
    }

    /// Build a `PostStudyStages` whose calendar is date-contiguous from the study
    /// horizon end (`stage_boundaries(study_durations)` last date), one stage per
    /// `post_durations` entry; `bounds` is a slice of
    /// `(thermal_id, post_study_stage_index, min_mw, max_mw)`.
    fn post_study_from(
        study_durations: &[f64],
        post_durations: &[f64],
        bounds: &[(i32, usize, f64, f64)],
    ) -> PostStudyStages {
        let boundaries = stage_boundaries(study_durations);
        let mut cursor = boundaries[study_durations.len()];
        let mut stages = Vec::with_capacity(post_durations.len());
        for &hours in post_durations {
            stages.push(PostStudyStage {
                start_date: cursor,
                duration_hours: hours,
            });
            cursor += TimeDelta::days((hours / 24.0) as i64);
        }
        let thermal_bounds = bounds
            .iter()
            .map(|&(thermal_id, j, min_mw, max_mw)| PostStudyThermalBound {
                thermal_id: EntityId::from(thermal_id),
                post_study_stage_index: j,
                cost_per_mwh: 100.0,
                min_mw,
                max_mw,
            })
            .collect();
        PostStudyStages {
            stages,
            thermal_bounds,
        }
    }

    /// [`make_data_anticipated_with_durations`] with a `post_study_stages`
    /// attached.
    fn data_with_post_study(
        thermals: Vec<Thermal>,
        durations_hours: &[f64],
        past_anticipated_commitments: Vec<AnticipatedCommitmentHistory>,
        post_study: PostStudyStages,
    ) -> ParsedData {
        let mut data = make_data_anticipated_with_durations(
            thermals,
            durations_hours,
            past_anticipated_commitments,
        );
        data.post_study_stages = Some(post_study);
        data
    }

    // ── AC-1: valid anticipated thermal — no errors ──────────────────────────

    /// Given a valid anticipated thermal (lead_stages=2, n_stages=5, no entry/exit,
    /// two all-zero commitment windows tiling stages 0..2), semantic validation
    /// returns no errors.
    #[test]
    fn test_valid_anticipated_thermal_ok() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "expected no errors, got: {:?}",
            ctx.errors()
        );
    }

    // ── LeadTime coverage ─────────────────────────────────────────────────────

    /// Given an otherwise-valid `LeadTime`-configured thermal on the
    /// weekly-then-monthly PMO calendar (calendar-covered commitments), when
    /// semantic validation runs, then no `NotImplemented` error is produced and
    /// the study passes validation entirely: `LeadTime` falls through to the
    /// shared coverage/bounds/window checks unchanged.
    #[test]
    fn test_lead_time_thermal_accepted() {
        let thermal = make_lead_time_anticipated_thermal(1, 720.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.kind == ErrorKind::NotImplemented),
            "LeadTime must no longer be rejected as NotImplemented, got: {:?}",
            ctx.errors()
        );
        assert!(
            !ctx.has_errors(),
            "a valid LeadTime thermal with calendar-covered commitments must pass \
             validation entirely, got: {:?}",
            ctx.errors()
        );
    }

    /// Given a valid single-decider `LeadTime(744.0)` thermal on a uniform
    /// 3×744h calendar with a matching one-entry `past_anticipated_commitments`
    /// history, when semantic validation runs, then the study passes validation
    /// with no errors — the first `LeadTime` config the gate admits through to
    /// setup.
    #[test]
    fn lead_time_single_decider_passes_validation() {
        let thermal = make_lead_time_anticipated_thermal(1, 744.0, None, None);
        let durations = [744.0, 744.0, 744.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a valid single-decider LeadTime thermal must pass validation, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC-2: missing history entry ───────────────────────────────────────────

    /// Given an anticipated thermal with no matching entry in
    /// past_anticipated_commitments, a `BusinessRuleViolation` names the
    /// thermal id and "missing".
    #[test]
    fn test_missing_history_entry_error() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 5, vec![]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| e.kind == ErrorKind::BusinessRuleViolation)
            .collect();
        assert!(
            !relevant.is_empty(),
            "expected BusinessRuleViolation, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("Thermal 1"),
            "message should contain 'Thermal 1', got: {msg}"
        );
        assert!(
            msg.contains("missing"),
            "message should contain 'missing', got: {msg}"
        );
        let file = relevant[0].file.to_string_lossy();
        assert!(
            file.contains("initial_conditions"),
            "file path should reference initial_conditions, got: {file}"
        );
        let entity = relevant[0].entity.as_deref().unwrap_or("");
        assert!(
            entity.contains("initial_conditions.past_anticipated_commitments"),
            "entity should contain 'initial_conditions.past_anticipated_commitments', got: {entity}"
        );
    }

    // ── AC-3: history entry for non-anticipated thermal ───────────────────────

    /// Given a history entry whose thermal_id references a thermal with
    /// anticipated_config == None, a `BusinessRuleViolation` names "not an
    /// anticipated thermal".
    #[test]
    fn test_history_entry_for_non_anticipated_thermal_error() {
        // thermal 1 is NOT anticipated
        let thermal = make_thermal(1, 0.0, 500.0);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[100.0, 200.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| e.kind == ErrorKind::BusinessRuleViolation)
            .collect();
        assert!(
            !relevant.is_empty(),
            "expected BusinessRuleViolation, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("not an anticipated thermal"),
            "message should contain 'not an anticipated thermal', got: {msg}"
        );
    }

    // ── AC-4: windows beyond the lead horizon (over-coverage) ────────────────

    /// Given lead_stages=2 but three tiling windows (covering stages 0..3), the
    /// window on stage 2 lies beyond the leading K=2 delivery horizon and is
    /// rejected with a named over-coverage error.
    #[test]
    fn test_over_coverage_beyond_lead_horizon_rejected() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[100.0, 200.0, 300.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("beyond the leading")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one over-coverage error, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains('2'),
            "message should name over-covered study stage id 2, got: {msg}"
        );
    }

    // ── AC-5: gap in the lead horizon (under-coverage) ───────────────────────

    /// Given lead_stages=2 but only one tiling window (covering stage 0), study
    /// stage 1 is uncovered and rejected with a named under-coverage error.
    #[test]
    fn test_under_coverage_gap_in_lead_horizon_rejected() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[100.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("do not tile the leading")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one under-coverage error, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains('1'),
            "message should name the uncovered study stage id 1, got: {msg}"
        );
    }

    // ── study-side coverage boundary: post-horizon windows are legal ─────────

    /// Given a plant with `k_i == 2` over four study stages, windows tiling
    /// study stages `0` and `1`, and one additional window covering only
    /// dates on the post-study calendar, `check_anticipated_thermals` emits no
    /// error: a window entirely past the study horizon contributes nothing to
    /// the study-side coverage sums and is not reported as a gap or as
    /// over-coverage.
    #[test]
    fn commitment_coverage_accepts_a_window_past_the_study_horizon() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let study_durations = vec![720.0; 4];
        let post_study = post_study_from(&study_durations, &[720.0], &[]);
        let mut commitments = commitments_on(1, &[0.0, 0.0], &study_durations);
        commitments.push(AnticipatedCommitmentHistory {
            thermal_id: EntityId::from(1),
            start_date: post_study.stages[0].start_date,
            end_date: post_study.stages[0].start_date + TimeDelta::days(30),
            value_mw: 0.0,
        });
        let data = data_with_post_study(vec![thermal], &study_durations, commitments, post_study);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a window past the study horizon must not be reported as a gap or as \
             over-coverage, got: {:?}",
            ctx.errors()
        );
    }

    /// Given a plant with `k_i == 2` over four study stages and a window
    /// covering study stage `2`, `check_anticipated_thermals` emits a
    /// `BusinessRuleViolation` naming study stage id `2`, whose message
    /// contains neither "past the pre-study delivery horizon" nor any claim
    /// that a window may not extend past the horizon.
    #[test]
    fn commitment_coverage_rejects_a_window_on_a_study_decided_stage() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 4, commitments(1, &[0.0, 0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("beyond the leading")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one over-coverage error, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains('2'),
            "message should name over-covered study stage id 2, got: {msg}"
        );
        assert!(
            !msg.contains("past the pre-study delivery horizon"),
            "the retired horizon phrasing must not appear, got: {msg}"
        );
        assert!(
            !msg.contains("extend past the horizon"),
            "the message must not claim a window may not extend past the horizon, got: {msg}"
        );
    }

    /// The gap-error path is untouched by the over-coverage message rewrite:
    /// given `k_i == 3` and windows tiling only study stages `0` and `1`,
    /// `check_anticipated_thermals` emits the gap error naming uncovered study
    /// stage id `2`, byte-identical to its pre-existing text.
    #[test]
    fn commitment_coverage_gap_message_is_unchanged() {
        let thermal = make_anticipated_thermal(1, 3, None, None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("do not tile the leading")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one gap error, got: {errors:?}"
        );
        assert_eq!(
            relevant[0].message,
            "Thermal 1: past_anticipated_commitments do not tile the leading 3 delivery \
             stage(s) at coverage 1.0; study stage id(s) [2] are not covered exactly once. \
             Write a commitment window (a committed 0 MW is explicit) for every leading \
             delivery stage."
        );
    }

    // ── AC-6: lead_stages exceeds study horizon ───────────────────────────────

    /// Given lead_stages=10 and n_stages=5, a `BusinessRuleViolation` names
    /// "lead_stages exceeds study horizon".
    #[test]
    fn test_lead_stages_exceeds_study_horizon_error() {
        let thermal = make_anticipated_thermal(1, 10, None, None);
        let data = make_data_anticipated(vec![thermal], 5, vec![]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_stages exceeds study horizon")
            })
            .collect();
        assert!(
            !relevant.is_empty(),
            "expected BusinessRuleViolation with 'lead_stages exceeds study horizon', got: {errors:?}"
        );
    }

    // ── Boundary: lead_stages == n_stages is accepted (strict-greater check) ──

    /// Boundary case for AC-6: lead_stages == n_stages must NOT error.
    /// The horizon check is `lead_stages > n_stages` (strict). A plant whose
    /// first delivery lands on the final study stage is a valid configuration.
    #[test]
    fn test_lead_stages_equal_n_stages_ok() {
        let thermal = make_anticipated_thermal(1, 5, None, None);
        let data =
            make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0, 0.0, 0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "lead_stages == n_stages must be accepted, got: {:?}",
            ctx.errors()
        );
    }

    // ── lead_time exceeds study horizon ───────────────────────────────────────

    /// Given a `LeadTime(delta_hours)` thermal whose `delta_hours` strictly
    /// exceeds the summed study-stage durations, when semantic validation runs,
    /// then exactly one `BusinessRuleViolation` is appended naming the thermal
    /// id, `delta_hours`, and the total horizon hours.
    #[test]
    fn test_lead_time_exceeds_study_horizon_error() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &[168.0, 168.0, 168.0, 168.0, 720.0, 720.0],
            vec![],
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_time exceeds study horizon")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation with 'lead_time exceeds study horizon', got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("Thermal 1"),
            "message should contain 'Thermal 1', got: {msg}"
        );
        assert!(
            msg.contains("3000"),
            "message should contain delta_hours 3000, got: {msg}"
        );
        assert!(
            msg.contains("2112"),
            "message should contain the total horizon hours 2112, got: {msg}"
        );
    }

    // ── Boundary: lead_time == total horizon is accepted (strict-greater check) ──

    /// Boundary case: `delta_hours == total_horizon_hours` must NOT error. The
    /// horizon check is `delta_hours > total_horizon_hours` (strict), mirroring
    /// the `LeadStages` boundary — a delivery landing exactly on the final study
    /// stage is a valid configuration.
    #[test]
    fn test_lead_time_equal_total_horizon_ok() {
        let thermal = make_lead_time_anticipated_thermal(1, 2112.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "delta_hours == total_horizon_hours must be accepted, got: {:?}",
            ctx.errors()
        );
    }

    // ── Post-horizon delivery exemption from the lead-horizon cap ────────────

    /// Given a `LeadTime(delta_hours)` thermal whose `delta_hours` strictly
    /// exceeds the summed study-stage durations, when the study declares a
    /// post-study stage its extended lead reaches (decided in-study, delivered
    /// post-horizon), then no `BusinessRuleViolation` naming "lead_time exceeds
    /// study horizon" is produced — the re-keyed lead-cap exemption.
    #[test]
    fn test_lead_time_exceeding_horizon_with_reachable_post_study_accepted() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        // A 60-day post-study stage: the 3000h lead, decided at study stage 3,
        // delivers into post-study stage 0.
        let post_study = post_study_from(&durations, &[1440.0], &[(1, 0, 0.0, 500.0)]);
        let data = data_with_post_study(vec![thermal], &durations, vec![], post_study);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        let errors = ctx.errors();
        let lead_cap_errors: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_time exceeds study horizon")
            })
            .collect();
        assert!(
            lead_cap_errors.is_empty(),
            "a thermal whose lead reaches a declared post-study stage must be exempt from the \
             lead-horizon cap, got: {errors:?}"
        );
    }

    /// Given the same over-horizon `LeadTime` thermal but with NO post-study
    /// stages declared, the lead-horizon cap still rejects it: the exemption is
    /// scoped to a study that declares a reachable post-study stage, never a
    /// blanket relaxation of the cap.
    #[test]
    fn test_lead_time_exceeding_horizon_without_post_study_still_rejected() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let data = make_data_anticipated_with_durations(vec![thermal], &durations, vec![]);
        assert!(
            data.post_study_stages.is_none(),
            "fixture must declare no post-study stages"
        );
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_time exceeds study horizon")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation with 'lead_time exceeds study horizon', got: {errors:?}"
        );
    }

    /// Given a `LeadTime` lead whose reach is entirely class-4 (empty
    /// `carried`, non-empty `fixed_post_study` — the full-anticipation regime),
    /// when `check_anticipated_thermals` runs, then the widened
    /// `reaches_post_study` predicate exempts it from the lead-horizon cap: no
    /// "lead_time exceeds study horizon" error is emitted. A single 720h study
    /// stage with `LeadTime(2000)` decides its only post-study stage pre-study.
    #[test]
    fn lead_exceeding_the_horizon_is_accepted_when_it_reaches_a_fixed_post_study_stage() {
        let thermal = make_lead_time_anticipated_thermal(1, 2000.0, None, None);
        let durations = [720.0];
        let post_study = post_study_from(&durations, &[720.0], &[(1, 0, 0.0, 500.0)]);
        let data = data_with_post_study(vec![thermal], &durations, vec![], post_study);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        let errors = ctx.errors();
        let lead_cap_errors: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_time exceeds study horizon")
            })
            .collect();
        assert!(
            lead_cap_errors.is_empty(),
            "a thermal whose lead reaches only a class-4 (pre-study-decided) post-study stage \
             must be exempt from the lead-horizon cap, got: {errors:?}"
        );
    }

    /// Given a `LeadTime` lead exceeding the study horizon with NO post-study
    /// stages declared at all, when `check_anticipated_thermals` runs, then the
    /// lead-horizon cap still rejects it — the pre-existing guard for a plant
    /// that genuinely can never deliver.
    #[test]
    fn lead_exceeding_the_horizon_without_post_study_stages_is_still_rejected() {
        let thermal = make_lead_time_anticipated_thermal(1, 2000.0, None, None);
        let durations = [720.0];
        let data = make_data_anticipated_with_durations(vec![thermal], &durations, vec![]);
        assert!(
            data.post_study_stages.is_none(),
            "fixture must declare no post-study stages"
        );
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("lead_time exceeds study horizon")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation with 'lead_time exceeds study horizon', got: {errors:?}"
        );
    }

    /// Given a `LeadTime` thermal exceeding the horizon whose extended lead
    /// reaches a declared post-study stage AND `past_anticipated_commitments`
    /// tiling every leading study stage at 0 MW (`lead_delivery_stage_count`
    /// resolves to `n_stages` whenever `delta_hours` exceeds the horizon),
    /// `check_anticipated_thermals` validates end-to-end with no errors: the
    /// re-keyed lead-cap exemption composes cleanly with the full-tiling coverage
    /// contract.
    #[test]
    fn test_post_horizon_delivery_thermal_tiling_all_study_stages_validates() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let post_study = post_study_from(&durations, &[1440.0], &[(1, 0, 0.0, 500.0)]);
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &durations),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a post-horizon-delivery thermal tiling every leading study stage must validate \
             cleanly through check_anticipated_thermals, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC: the widened `LeadStages` guard matches `LeadTime` (full anticipation) ──

    /// Given a `LeadStages(7)` thermal on a uniform 4×720h study horizon
    /// (`n_stages = 4`) whose extended lead reaches only post-study stages —
    /// three pre-study-decided (`fixed_post_study`, tiled by
    /// `past_anticipated_commitments`) and one study-decided (`carried`,
    /// bound by a declared `PostStudyThermalBound`) —
    /// `validate_semantic_hydro_thermal` returns no errors: the `lead_stages`
    /// guard now shares the `lead_time` guard's `reaches_post_study`
    /// exemption instead of unconditionally rejecting `lead_stages >
    /// n_stages`.
    #[test]
    fn full_anticipation_lead_stages_reaching_only_post_study_stages_validates() {
        let thermal = make_anticipated_thermal(1, 7, None, None);
        let study_durations = [720.0; 4];
        let post_durations = [720.0; 4];
        let post_study = post_study_from(&study_durations, &post_durations, &[(1, 3, 0.0, 500.0)]);
        let concatenated: Vec<f64> = study_durations
            .iter()
            .copied()
            .chain(post_durations[..3].iter().copied())
            .collect();
        let commitments = commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 500.0], &concatenated);
        let data = data_with_post_study(vec![thermal], &study_durations, commitments, post_study);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a full-anticipation LeadStages thermal reaching only post-study stages must \
             validate cleanly end-to-end, got: {:?}",
            ctx.errors()
        );
    }

    /// Given a `LeadStages(5)` thermal on the same 4×720h study horizon whose
    /// extended lead exceeds `n_stages` but reaches a `carried` (study-decided)
    /// post-study stage with no declared `PostStudyThermalBound` cell, the
    /// widened guard does not reject it (the plant IS reachable), but
    /// `check_post_study_stages`'s Rule 1 still reports the missing bound cell:
    /// the guard widening exempts a reachable plant from the horizon cap
    /// without masking the genuine missing-bound defect.
    #[test]
    fn lead_stages_short_lead_reaching_carried_stage_without_bound_still_rejected() {
        let thermal = make_anticipated_thermal(1, 5, None, None);
        let study_durations = [720.0; 4];
        let post_durations = [720.0, 720.0];
        let post_study = post_study_from(&study_durations, &post_durations, &[]);
        let concatenated: Vec<f64> = study_durations
            .iter()
            .copied()
            .chain(post_durations[..1].iter().copied())
            .collect();
        let commitments = commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0], &concatenated);
        let data = data_with_post_study(vec![thermal], &study_durations, commitments, post_study);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        assert!(
            !errors
                .iter()
                .any(|e| e.message.contains("lead_stages exceeds study horizon")),
            "the widened guard must not fire when the plant reaches a carried post-study \
             stage, got: {errors:?}"
        );
        assert!(
            errors
                .iter()
                .any(|e| e.message.contains("no thermal_bounds entry")
                    && e.message.contains("post_study_stage_index 1")),
            "check_post_study_stages must still reject the missing bound cell on the \
             reached carried stage, got: {errors:?}"
        );
    }

    /// `LeadStages(7)` and the equivalent `LeadTime(5040.0)` (`7 × 720h`) on the
    /// identical uniform 4×720h study + 4×720h post-study calendar resolve to
    /// the same delivery classification and both validate with no errors: the
    /// two lead modes hit the widened horizon guard identically (AC4).
    #[test]
    fn lead_stages_and_lead_time_resolve_the_horizon_guard_identically() {
        let study_durations = [720.0; 4];
        let post_durations = [720.0; 4];
        let values = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 500.0];
        let concatenated: Vec<f64> = study_durations
            .iter()
            .copied()
            .chain(post_durations[..3].iter().copied())
            .collect();

        let lead_stages_thermal = make_anticipated_thermal(1, 7, None, None);
        let post_study_a =
            post_study_from(&study_durations, &post_durations, &[(1, 3, 0.0, 500.0)]);
        let data_a = data_with_post_study(
            vec![lead_stages_thermal],
            &study_durations,
            commitments_on(1, &values, &concatenated),
            post_study_a,
        );
        let mut ctx_a = ValidationContext::new();
        validate_semantic_hydro_thermal(&data_a, &mut ctx_a);
        assert!(
            !ctx_a.has_errors(),
            "LeadStages(7) must validate cleanly, got: {:?}",
            ctx_a.errors()
        );

        let lead_time_thermal = make_lead_time_anticipated_thermal(1, 5040.0, None, None);
        let post_study_b =
            post_study_from(&study_durations, &post_durations, &[(1, 3, 0.0, 500.0)]);
        let data_b = data_with_post_study(
            vec![lead_time_thermal],
            &study_durations,
            commitments_on(1, &values, &concatenated),
            post_study_b,
        );
        let mut ctx_b = ValidationContext::new();
        validate_semantic_hydro_thermal(&data_b, &mut ctx_b);
        assert!(
            !ctx_b.has_errors(),
            "the equivalent LeadTime(5040.0) must validate cleanly identically, got: {:?}",
            ctx_b.errors()
        );
    }

    // ── The concatenated-calendar walk: extended_deciders / classify_deliveries ──

    /// `extended_deciders` mirrors the solver's `resolve_point` on the PMO
    /// calendar (weekly-then-monthly), producing the same delivery-anchored
    /// decider shape `[None×4, Some(3), Some(4), Some(5)]` — the fixture pins
    /// cobre-io's independent walk to the solver's resolution shape.
    #[test]
    fn test_extended_deciders_lead_time_pmo_matches_solver_resolution() {
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0, 720.0];
        let deciders = extended_deciders(AnticipatedConfig::LeadTime(720.0), &durations);
        assert_eq!(
            deciders,
            vec![None, None, None, None, Some(3), Some(4), Some(5)]
        );
    }

    /// `extended_deciders` for `LeadStages(l)` is a bare stage shift `c(m) = m − l`
    /// (calendar never consulted), independent of the (non-uniform) durations.
    #[test]
    fn test_extended_deciders_lead_stages_is_bare_shift() {
        let durations = [168.0, 720.0, 168.0, 720.0, 168.0, 720.0];
        let deciders = extended_deciders(AnticipatedConfig::LeadStages(2), &durations);
        assert_eq!(
            deciders,
            vec![None, None, Some(0), Some(1), Some(2), Some(3)]
        );
    }

    /// Uniform post-study durations: an over-horizon lead splits the post-study
    /// deliveries into a pre-study-decided prefix (`fixed_post_study`) and an
    /// in-study-decided suffix (`carried`). Two study stages (ids 0,1) plus two
    /// continued post-study stages (ids 2,3); `LeadTime(2500)` on a `720`h
    /// calendar decides post-study stage 0 pre-study and post-study stage 1 at
    /// study stage 0.
    #[test]
    fn test_classify_deliveries_uniform_splits_carried_and_fixed_post_study() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![720.0, 720.0, 720.0, 720.0],
            stage_ids: vec![0, 1, 2, 3],
            n_stages: 2,
        };
        let classes = classify_deliveries(
            AnticipatedConfig::LeadTime(2500.0),
            Some(&axis),
            &[720.0, 720.0],
            2,
            (None, None),
        );
        assert_eq!(classes.carried, vec![1]);
        assert_eq!(classes.fixed_post_study, vec![0]);
    }

    /// Non-uniform post-study durations: `LeadTime(1000)` on a `[168,720|720,720]`
    /// extended calendar reaches post-study stage 0 from an in-study decision
    /// (study stage 1) and no pre-study-decided prefix.
    #[test]
    fn test_classify_deliveries_non_uniform_reaches_first_post_study_stage() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![168.0, 720.0, 720.0, 720.0],
            stage_ids: vec![0, 1, 2, 3],
            n_stages: 2,
        };
        let classes = classify_deliveries(
            AnticipatedConfig::LeadTime(1000.0),
            Some(&axis),
            &[168.0, 720.0],
            2,
            (None, None),
        );
        assert_eq!(classes.carried, vec![0]);
        assert!(classes.fixed_post_study.is_empty());
    }

    /// The commissioning gate keys on the DELIVERY stage's continued id: an
    /// `exit_stage_id` that decommissions the plant at a post-study id drops the
    /// later post-study delivery from `carried`, even though its in-study decider
    /// exists (mirrors the solver's delivery-anchored gate).
    #[test]
    fn test_classify_deliveries_commissioning_gate_drops_decommissioned_delivery() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![720.0, 720.0, 720.0, 720.0],
            stage_ids: vec![0, 1, 2, 3],
            n_stages: 2,
        };
        // exit=3 decommissions the plant at continued post-study id 3, so the
        // delivery at delivery stage 3 (post-study index 1) is inactive.
        let classes = classify_deliveries(
            AnticipatedConfig::LeadTime(2500.0),
            Some(&axis),
            &[720.0, 720.0],
            2,
            (None, Some(3)),
        );
        assert!(
            classes.carried.is_empty(),
            "the post-study-index-1 delivery is commissioning-inactive, got: {:?}",
            classes.carried
        );
        assert_eq!(classes.fixed_post_study, vec![0]);
        assert_eq!(classes.commissioning_inactive, vec![1]);
    }

    // ── classify_deliveries: the five-class split and the leading-count mirror ──

    /// A four-study/seven-post-study `LeadTime` decider (`None` for `m in 0..7`,
    /// `Some(t)` with `t < 4` for `m in 7..11`) splits the post-study range into
    /// a pre-study-decided prefix (`fixed_post_study`) and an in-study-decided
    /// suffix (`carried`), with no reach beyond the horizon and no commissioning
    /// exclusion on a windowless plant.
    #[test]
    fn classify_deliveries_splits_fixed_and_carried_post_study_stages() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![720.0; 11],
            stage_ids: (0..11).collect(),
            n_stages: 4,
        };
        let classes = classify_deliveries(
            AnticipatedConfig::LeadTime(5040.0),
            Some(&axis),
            &[720.0; 4],
            4,
            (None, None),
        );
        assert_eq!(classes.leading_in_study, 4);
        assert_eq!(classes.fixed_post_study, vec![0, 1, 2]);
        assert_eq!(classes.carried, vec![3, 4, 5, 6]);
        assert!(classes.beyond_reach.is_empty());
        assert!(classes.commissioning_inactive.is_empty());
    }

    /// A post-study index whose decider resolves in-study but at or beyond
    /// `n_stages` (a post-study decision for a post-study delivery) lands in
    /// `beyond_reach` and none of the other three vectors.
    #[test]
    fn classify_deliveries_records_a_beyond_reach_post_study_stage() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![100.0, 100.0, 100.0],
            stage_ids: vec![0, 1, 2],
            n_stages: 1,
        };
        let classes = classify_deliveries(
            AnticipatedConfig::LeadStages(1),
            Some(&axis),
            &[100.0],
            1,
            (None, None),
        );
        assert_eq!(classes.beyond_reach, vec![1]);
        assert!(!classes.carried.contains(&1));
        assert!(!classes.fixed_post_study.contains(&1));
        assert!(!classes.commissioning_inactive.contains(&1));
    }

    /// An `exit_stage_id` inside the study decommissions the plant for every
    /// later delivery; all three post-study indices land in
    /// `commissioning_inactive` and the other three vectors stay empty.
    #[test]
    fn classify_deliveries_records_a_commissioning_inactive_post_study_stage() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![100.0, 100.0, 100.0, 100.0, 100.0],
            stage_ids: vec![0, 1, 2, 3, 4],
            n_stages: 2,
        };
        let classes = classify_deliveries(
            AnticipatedConfig::LeadStages(1),
            Some(&axis),
            &[100.0, 100.0],
            2,
            (None, Some(1)),
        );
        assert_eq!(classes.commissioning_inactive, vec![0, 1, 2]);
        assert!(classes.fixed_post_study.is_empty());
        assert!(classes.carried.is_empty());
        assert!(classes.beyond_reach.is_empty());
    }

    /// A study with no `post_study_stages` (`axis = None`) reports every
    /// post-study vector empty and resolves `leading_in_study` exactly as
    /// `lead_delivery_stage_count` does for the same plant.
    #[test]
    fn classify_deliveries_without_a_post_study_axis_reports_only_the_leading_count() {
        let study_durations = vec![100.0; 5];
        let classes = classify_deliveries(
            AnticipatedConfig::LeadStages(2),
            None,
            &study_durations,
            5,
            (None, None),
        );
        assert_eq!(
            classes.leading_in_study,
            lead_delivery_stage_count(AnticipatedConfig::LeadStages(2), &study_durations, 5)
        );
        assert!(classes.fixed_post_study.is_empty());
        assert!(classes.carried.is_empty());
        assert!(classes.beyond_reach.is_empty());
        assert!(classes.commissioning_inactive.is_empty());
    }

    /// `leading_in_study` (a cumulative-hours count) matches the `None` run of
    /// `extended_deciders` over the study prefix (a boundary `partition_point`)
    /// — the mirror `classify_deliveries`'s internal `debug_assert_eq!` guards —
    /// for both `LeadStages` and `LeadTime`.
    #[test]
    fn classify_deliveries_leading_count_matches_the_extended_decider_none_run() {
        let axis = ExtendedDeliveryAxis {
            durations: vec![720.0; 5],
            stage_ids: (0..5).collect(),
            n_stages: 3,
        };
        let study_durations = [720.0; 3];

        for mode in [
            AnticipatedConfig::LeadStages(2),
            AnticipatedConfig::LeadTime(1000.0),
        ] {
            let classes = classify_deliveries(mode, Some(&axis), &study_durations, 3, (None, None));
            let none_run = extended_deciders(mode, &axis.durations)[..axis.n_stages]
                .iter()
                .filter(|decider| decider.is_none())
                .count();
            assert_eq!(
                classes.leading_in_study, none_run,
                "leading_in_study must match the extended_deciders None run for {mode:?}"
            );
        }
    }

    /// A study with no `post_study_stages` yields no delivery axis, so nothing
    /// reaches post-study — the `None` return the lead-cap reject keys on.
    #[test]
    fn test_extended_delivery_axis_absent_without_post_study() {
        let data =
            make_data_anticipated(vec![make_anticipated_thermal(1, 2, None, None)], 3, vec![]);
        assert!(build_extended_delivery_axis(&data).is_none());
    }

    /// `build_extended_delivery_axis` concatenates the study durations/ids with
    /// the post-study durations and the continued id sequence
    /// (`max_study_id + 1 ..`).
    #[test]
    fn test_extended_delivery_axis_concatenates_and_continues_ids() {
        let durations = [720.0, 720.0];
        let post_study = post_study_from(&durations, &[696.0, 744.0], &[]);
        let data = data_with_post_study(
            vec![make_anticipated_thermal(1, 1, None, None)],
            &durations,
            commitments_on(1, &[0.0], &durations),
            post_study,
        );
        let Some(axis) = build_extended_delivery_axis(&data) else {
            panic!("post-study declared, so the axis must build");
        };
        assert_eq!(axis.n_stages, 2);
        assert_eq!(axis.durations, vec![720.0, 720.0, 696.0, 744.0]);
        assert_eq!(axis.stage_ids, vec![0, 1, 2, 3]);
    }

    // ── Rule 1 (missing bound cell) and V2 (fixed post-horizon tiling) ────────

    /// Rule 1 failing fixture: an anticipated thermal whose extended lead reaches
    /// post-study stage 0 with no `PostStudyThermalBound(id, 0)` is rejected,
    /// naming the plant and the stage.
    #[test]
    fn test_missing_post_study_bound_cell_rejected() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        // Post-study stage 0 is reached (see the exemption test) but no bound cell
        // is declared for it.
        let post_study = post_study_from(&durations, &[1440.0], &[]);
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &durations),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_post_study_stages(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("no thermal_bounds entry")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one missing-bound-cell rejection, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("Thermal 1") && msg.contains("post_study_stage_index 0"),
            "message should name the plant and post-study stage 0, got: {msg}"
        );
    }

    /// Rule 1 passing sibling: adding the `PostStudyThermalBound(1, 0)` cell makes
    /// the reached delivery valid — no missing-bound-cell rejection.
    #[test]
    fn test_present_post_study_bound_cell_accepted() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let post_study = post_study_from(&durations, &[1440.0], &[(1, 0, 0.0, 500.0)]);
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &durations),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_post_study_stages(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a reached delivery with its bound cell present must not be rejected, got: {:?}",
            ctx.errors()
        );
    }

    /// V2 passing fixture — the retired no-carrier reject's positive inverse: a
    /// `LeadTime` lead so long its FIRST post-study delivery is decided at a
    /// pre-study stage loads cleanly once a commitment window tiles that stage.
    /// `[720,720|720,720]` with `LeadTime(2500)` decides post-study stage 0
    /// pre-study; the third window (reusing `commitments_on` over a 3-stage
    /// duration list) lands exactly on post-study stage 0's dates.
    #[test]
    fn test_pre_study_decided_post_study_delivery_loads_when_tiled() {
        let thermal = make_lead_time_anticipated_thermal(1, 2500.0, None, None);
        let durations = [720.0, 720.0];
        let post_study = post_study_from(
            &durations,
            &[720.0, 720.0],
            &[(1, 0, 0.0, 500.0), (1, 1, 0.0, 500.0)],
        );
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0], &[720.0, 720.0, 720.0]),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_post_study_stages(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a pre-study-decided post-study delivery tiled by a commitment window must not be \
             rejected, got: {:?}",
            ctx.errors()
        );
    }

    /// V2 stays silent when `fixed_post_study` is empty: shortening the lead so
    /// every post-study delivery is decided in-study needs no tiling window.
    /// `LeadTime(800)` on the same calendar decides post-study stage 0 at study
    /// stage 0.
    #[test]
    fn test_in_study_decided_post_study_delivery_accepted() {
        let thermal = make_lead_time_anticipated_thermal(1, 800.0, None, None);
        let durations = [720.0, 720.0];
        let post_study = post_study_from(
            &durations,
            &[720.0, 720.0],
            &[(1, 0, 0.0, 500.0), (1, 1, 0.0, 500.0)],
        );
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0], &durations),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_post_study_stages(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "an in-study-decided post-study delivery must not be rejected, got: {:?}",
            ctx.errors()
        );
    }

    /// Invariant (a) is retained: a post-study calendar whose first stage does not
    /// start at the study horizon end is still rejected.
    #[test]
    fn test_post_study_calendar_anchor_still_enforced() {
        let thermal = make_lead_time_anticipated_thermal(1, 3000.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let mut post_study = post_study_from(&durations, &[1440.0], &[(1, 0, 0.0, 500.0)]);
        // Shift the anchor a day past the study horizon end.
        post_study.stages[0].start_date += TimeDelta::days(1);
        let data = data_with_post_study(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0], &durations),
            post_study,
        );
        let mut ctx = ValidationContext::new();
        check_post_study_stages(&data, &mut ctx);
        assert!(
            ctx.errors()
                .iter()
                .any(|e| e.message.contains("post-study calendar must begin exactly")),
            "invariant (a) anchor check must still fire, got: {:?}",
            ctx.errors()
        );
    }

    // ── Cadence-transition advisory (check_anticipated_cadence_transition) ────

    /// Given a `lead_stages=2` thermal whose active window spans a
    /// weekly (168h) -> monthly (744h) stage-cadence transition, when
    /// semantic validation runs, then exactly one advisory is produced naming
    /// the thermal and citing `lead_time`, and validation still succeeds.
    #[test]
    fn lead_stages_cadence_transition_emits_advisory() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let durations = [168.0, 168.0, 168.0, 744.0, 744.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "a cadence transition is advisory-only, never an error; got: {:?}",
            ctx.errors()
        );
        let relevant: Vec<_> = ctx
            .warnings()
            .into_iter()
            .filter(|w| w.kind == ErrorKind::ModelQuality && w.message.contains("Thermal 1"))
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one cadence-transition advisory, got: {:?}",
            ctx.warnings()
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("lead_time"),
            "advisory must cite lead_time as the physically-anchored alternative, got: {msg}"
        );
        assert!(
            msg.contains("stage 2") && msg.contains("stage 3"),
            "advisory must cite the transition stage pair, got: {msg}"
        );
    }

    /// Given a `lead_stages=2` thermal whose active window spans only
    /// equal-duration (uniform) stages, when semantic validation runs, then no
    /// cadence-transition advisory is produced.
    #[test]
    fn lead_stages_uniform_calendar_no_advisory() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let durations = [744.0, 744.0, 744.0, 744.0, 744.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);

        assert!(
            !ctx.has_errors(),
            "a uniform calendar is valid, got: {:?}",
            ctx.errors()
        );
        assert!(
            !ctx.warnings()
                .iter()
                .any(|w| w.kind == ErrorKind::ModelQuality && w.message.contains("cadence")),
            "a uniform calendar must not trigger a cadence-transition advisory, got: {:?}",
            ctx.warnings()
        );
    }

    // ── lead_delivery_stage_count: direct unit tests ─────────────────────────

    /// Weekly-then-monthly PMO calendar `[168,168,168,168,720,720]` h with
    /// `LeadTime(720.0)`: the leading count is 4 (`S_{m+1} <= 720` holds for
    /// `m = 0..=3` only; `S_5 = 1392 > 720`).
    #[test]
    fn test_lead_delivery_stage_count_lead_time_pmo_calendar() {
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let count = lead_delivery_stage_count(
            AnticipatedConfig::LeadTime(720.0),
            &durations,
            durations.len(),
        );
        assert_eq!(count, 4);
    }

    /// Uniform 5x720h calendar with `LeadTime(1440.0)`: the count is 2
    /// (`S_{m+1} <= 1440` holds for `m = 0, 1` only; tie-inclusive at `m = 1`).
    #[test]
    fn test_lead_delivery_stage_count_lead_time_uniform_calendar() {
        let durations = [720.0; 5];
        let count = lead_delivery_stage_count(
            AnticipatedConfig::LeadTime(1440.0),
            &durations,
            durations.len(),
        );
        assert_eq!(count, 2);
    }

    /// `LeadStages` ignores durations entirely and clamps to `n_stages`.
    #[test]
    fn test_lead_delivery_stage_count_lead_stages_clamped() {
        let count = lead_delivery_stage_count(AnticipatedConfig::LeadStages(2), &[720.0; 5], 5);
        assert_eq!(count, 2);
    }

    // ── Calendar-derived coverage: LeadTime on a non-uniform calendar ────────

    /// Given a `LeadTime(720.0)` plant on the weekly-then-monthly PMO calendar
    /// `[168,168,168,168,720,720]` h whose four windows tile the leading four
    /// delivery stages exactly, no coverage error fires.
    #[test]
    fn test_anticipated_lead_time_coverage_pmo_calendar() {
        let thermal = make_lead_time_anticipated_thermal(1, 720.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0, 0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let coverage_errors: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && (e.message.contains("do not tile the leading")
                        || e.message.contains("beyond the leading"))
            })
            .collect();
        assert!(
            coverage_errors.is_empty(),
            "expected no coverage error, got: {errors:?}"
        );
    }

    /// Given the same PMO calendar and `LeadTime(720.0)` plant but windows
    /// tiling only the leading two of the four calendar-derived delivery stages,
    /// exactly one `BusinessRuleViolation` fires naming the uncovered stages.
    #[test]
    fn test_anticipated_lead_time_coverage_pmo_calendar_under_coverage_rejected() {
        let thermal = make_lead_time_anticipated_thermal(1, 720.0, None, None);
        let durations = [168.0, 168.0, 168.0, 168.0, 720.0, 720.0];
        let data = make_data_anticipated_with_durations(
            vec![thermal],
            &durations,
            commitments_on(1, &[0.0, 0.0], &durations),
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let coverage_errors: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("do not tile the leading")
            })
            .collect();
        assert_eq!(
            coverage_errors.len(),
            1,
            "expected exactly one under-coverage error, got: {errors:?}"
        );
        let msg = &coverage_errors[0].message;
        assert!(
            msg.contains('2') && msg.contains('3'),
            "message should name the uncovered study stage ids 2 and 3, got: {msg}"
        );
    }

    // ── AC-7: entry_stage_id window on an anticipated thermal is ACCEPTED ─────

    /// An anticipated thermal that sets `entry_stage_id` is accepted: the window
    /// composes with the K-stage delivery lookahead via the shifted decision gate.
    /// With all-zero seeds the seed-vs-window rule does not fire (a zero seed is
    /// consistent with the `[0, 0]` pin at a dormant stage).
    #[test]
    fn test_entry_window_on_anticipated_thermal_accepted() {
        let thermal = make_anticipated_thermal(1, 3, Some(4), None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "an entry window on an anticipated thermal must be accepted, got: {:?}",
            ctx.errors()
        );
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("not supported on anticipated thermals")),
            "the removed window rejection must not fire"
        );
    }

    // ── AC-8: exit_stage_id window on an anticipated thermal is ACCEPTED ──────

    /// An anticipated thermal that sets `exit_stage_id` is accepted. With all-zero
    /// seeds the seed-vs-window rule does not fire.
    #[test]
    fn test_exit_window_on_anticipated_thermal_accepted() {
        let thermal = make_anticipated_thermal(1, 3, None, Some(2));
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "an exit window on an anticipated thermal must be accepted, got: {:?}",
            ctx.errors()
        );
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("not supported on anticipated thermals")),
            "the removed window rejection must not fire"
        );
    }

    // ── Seed-vs-window: nonzero seed maturing outside the window is rejected ──

    /// A windowed anticipated thermal whose nonzero seed matures OUTSIDE the
    /// operation window is rejected. K=2, n_stages=5, commissioning window
    /// `[entry=2, exit=4)`, commitment windows `[100.0, 0.0]` over study stages
    /// 0 and 1: the 100 MW window delivers at study stage id 0, before
    /// `entry=2`, so `commissioning_active(2, 4, 0) == false` and the nonzero
    /// rate forces an infeasible `0 == 100` fishing equality. The 0 MW window is
    /// consistent at any stage and emits no error.
    #[test]
    fn test_nonzero_seed_outside_window_rejected() {
        let thermal = make_anticipated_thermal(1, 2, Some(2), Some(4));
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[100.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message
                        .contains("outside the plant's commissioning window")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one seed-vs-window error (stage 0 only), got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("study stage id 0") && msg.contains("Thermal 1"),
            "error must identify study stage 0 of Thermal 1, got: {msg}"
        );
    }

    /// A windowed anticipated thermal whose nonzero seeds all mature INSIDE the
    /// window is accepted. K=1, n_stages=5, commissioning window
    /// `[entry=0, exit=5)`, a single 50 MW window over study stage id 0 ∈
    /// `[0, 5)`, so `commissioning_active(0, 5, 0) == true` and no seed-vs-window
    /// error fires.
    #[test]
    fn test_nonzero_seed_inside_window_accepted() {
        let thermal = make_anticipated_thermal(1, 1, Some(0), Some(5));
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[50.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.errors().iter().any(|e| e
                .message
                .contains("outside the plant's commissioning window")),
            "an in-window nonzero seed must not be rejected, got: {:?}",
            ctx.errors()
        );
    }

    // ── Commissioning window on a PLAIN thermal is accepted (applied, not warned) ─

    /// A non-anticipated thermal that sets a commissioning window is accepted:
    /// the window is applied at the LP fill site (dormant column pinned to
    /// `[0, 0]`), so the anticipated-only rejection must NOT fire and no error
    /// is emitted.
    #[test]
    fn test_window_on_plain_thermal_accepted() {
        let thermal = Thermal {
            entry_stage_id: Some(1),
            exit_stage_id: Some(2),
            ..make_thermal(1, 0.0, 100.0)
        };
        let data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(vec![0, 1, 2]),
            vec![],
            vec![],
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a window on a plain (non-anticipated) thermal must not error, got: {:?}",
            ctx.errors()
        );
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("not supported on anticipated thermals")),
            "the anticipated-only window rejection must not fire for a plain thermal"
        );
    }

    /// An anticipated thermal with NO commissioning window is accepted: the
    /// rejection is gated on a window being set, so a windowless anticipated
    /// plant passes (regression guard against a blanket reject).
    #[test]
    fn test_anticipated_thermal_without_window_accepted() {
        let thermal = make_anticipated_thermal(1, 2, None, None);
        let data = make_data_anticipated(vec![thermal], 5, commitments(1, &[0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("not supported on anticipated thermals")),
            "a windowless anticipated thermal must not be rejected, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC-9: a window value above bounds → bounds error, in-bounds window passes ─

    /// Given windows `[600.0, 200.0]` against a plant with max_generation_mw =
    /// 500.0, the validator emits exactly one bounds-violation error for the
    /// 600 MW window (600.0 > 500.0). The 200 MW window is within [0.0, 500.0]
    /// and passes silently.
    ///
    /// Expected: one BusinessRuleViolation whose message contains
    /// "outside the plant's generation bounds", names "Thermal 3", and the
    /// offending window.
    #[test]
    fn test_committed_value_out_of_bounds_error() {
        let thermal = make_anticipated_thermal(3, 2, None, None); // min=0.0, max=500.0
        let data = make_data_anticipated(vec![thermal], 5, commitments(3, &[600.0, 200.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one bounds-violation error (600 MW window only), got: {errors:?}"
        );
        let msg0 = &relevant[0].message;
        assert!(
            msg0.contains("Thermal 3"),
            "message should contain 'Thermal 3', got: {msg0}"
        );
        assert!(
            msg0.contains("2024-01-01"),
            "message should identify the offending window by its start date, got: {msg0}"
        );
        assert!(
            msg0.contains("600"),
            "message should contain the offending value 600, got: {msg0}"
        );
        let file = relevant[0].file.to_string_lossy();
        assert!(
            file.contains("initial_conditions"),
            "file path should reference initial_conditions, got: {file}"
        );
        let entity = relevant[0].entity.as_deref().unwrap_or("");
        assert!(
            entity.contains("thermals[id=3].anticipated_config"),
            "entity should reference the thermal anticipated_config, got: {entity}"
        );
    }

    // ── AC-10: a window value below min_gen → bounds error for that window ────

    /// Given windows `[200.0, 50.0]` against a plant with min_generation_mw =
    /// 100.0 and max_generation_mw = 500.0, the validator emits exactly one
    /// bounds-violation error for the 50 MW window (50.0 < 100.0). The 200 MW
    /// window is within [100.0, 500.0] and passes silently.
    #[test]
    fn test_committed_value_below_min_gen_bounds_error() {
        // Build a thermal with min_mw=100.0.
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(2)),
            ..make_thermal(5, 100.0, 500.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(5, &[200.0, 50.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one bounds-violation error (50 MW window only), got: {errors:?}"
        );
        let msg1 = &relevant[0].message;
        assert!(
            msg1.contains("Thermal 5"),
            "message should contain 'Thermal 5', got: {msg1}"
        );
        assert!(
            msg1.contains("50"),
            "message should contain the offending value 50, got: {msg1}"
        );
    }

    // ── AC-11: all values zero — passes (within [min_gen, max_gen]) ──────────

    /// Given all-zero window values and min_gen = 0.0, no bounds error is
    /// emitted (0.0 is within [0.0, 400.0]).
    #[test]
    fn test_committed_values_all_zero_ok() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(3)),
            ..make_thermal(7, 0.0, 400.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(7, &[0.0, 0.0, 0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "expected no errors for all-zero window values, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC-12: boundary — value == min_gen (0.0) is accepted ─────────────────

    /// Given a single window value == 0.0 and min_gen == 0.0, no bounds error is
    /// emitted (the minimum is inclusive).
    #[test]
    fn test_committed_value_zero_accepted() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(9, 0.0, 400.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(9, &[0.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "zero value must be accepted, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC-13: single value above max_generation_mw → bounds error ───────────

    /// Given a single window value 400.0 against max_generation_mw = 350.0, the
    /// validator emits exactly one bounds-violation error because
    /// 400.0 > 350.0 is outside [100.0, 350.0].
    #[test]
    fn test_committed_value_above_max_bounds_error() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(11, 100.0, 350.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(11, &[400.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one bounds-violation error, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("Thermal 11"),
            "message should contain 'Thermal 11', got: {msg}"
        );
        assert!(
            msg.contains("400"),
            "message should contain the offending value 400, got: {msg}"
        );
    }

    /// A window value a hair above `max_generation_mw` — within the
    /// relative-with-floor tolerance — must not be rejected (a value generated by
    /// some upstream pipeline may drift a hair past a bound it was meant to sit on).
    #[test]
    fn test_committed_value_within_tolerance_above_max_accepted() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(13, 100.0, 350.0)
        };
        // 1e-8 above max_generation_mw: an order of magnitude below the 3.5e-7 tolerance.
        let data = make_data_anticipated(vec![thermal], 5, commitments(13, &[350.0 + 1e-8]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a value within relative tolerance of max_generation_mw must not be rejected, \
             got: {:?}",
            ctx.errors()
        );
    }

    /// A window value a hair below `min_generation_mw` — within the
    /// relative-with-floor tolerance — must not be rejected.
    #[test]
    fn test_committed_value_within_tolerance_below_min_accepted() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(14, 100.0, 350.0)
        };
        // 1e-8 below min_generation_mw: an order of magnitude below the 1e-7 tolerance.
        let data = make_data_anticipated(vec![thermal], 5, commitments(14, &[100.0 - 1e-8]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            !ctx.has_errors(),
            "a value within relative tolerance of min_generation_mw must not be rejected, \
             got: {:?}",
            ctx.errors()
        );
    }

    /// A window value beyond the tolerance above `max_generation_mw` (an order of
    /// magnitude larger than the tolerance) is still rejected — the tolerance
    /// must have power, not just admit a hairline drift.
    #[test]
    fn test_committed_value_beyond_tolerance_above_max_still_rejected() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(15, 100.0, 350.0)
        };
        // 3.5e-6 above max_generation_mw: an order of magnitude above the 3.5e-7 tolerance.
        let data = make_data_anticipated(vec![thermal], 5, commitments(15, &[350.0 + 3.5e-6]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let relevant: Vec<_> = ctx
            .errors()
            .into_iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "a value beyond tolerance above max_generation_mw must still be rejected, \
             got: {:?}",
            ctx.errors()
        );
    }

    // ── The envelope check is window-agnostic: it applies identically to a ───
    // ── window dated past the study horizon, with no post-study calendar ─────
    // ── declared at all.  ──────────────────────────────────────────────────

    /// A window tiling leading study stage 0 (in bounds) plus a second window
    /// dated a full year past the study horizon — no `post_study_stages` is
    /// declared, so `check_commitment_coverage` never sees it either — carries
    /// an out-of-envelope `value_mw`. The envelope check does not filter by
    /// date: it is rejected exactly as an in-study window would be.
    #[test]
    fn committed_value_bounds_reject_an_out_of_envelope_post_horizon_window() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(21, 0.0, 200.0)
        };
        let mut records = commitments(21, &[0.0]);
        records.push(AnticipatedCommitmentHistory {
            thermal_id: EntityId::from(21),
            start_date: NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(),
            end_date: NaiveDate::from_ymd_opt(2025, 2, 1).unwrap(),
            value_mw: 350.0,
        });
        let data = make_data_anticipated(vec![thermal], 2, records);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        let relevant: Vec<_> = ctx
            .errors()
            .into_iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one envelope violation for the post-horizon window, got: {:?}",
            ctx.errors()
        );
        assert!(
            relevant[0].message.contains("350"),
            "message should contain the offending value 350, got: {}",
            relevant[0].message
        );
    }

    /// The same fixture with the post-horizon window's `value_mw` inside
    /// `[0.0, 200.0]`: no envelope error is emitted.
    #[test]
    fn committed_value_bounds_accept_an_in_envelope_post_horizon_window() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(22, 0.0, 200.0)
        };
        let mut records = commitments(22, &[0.0]);
        records.push(AnticipatedCommitmentHistory {
            thermal_id: EntityId::from(22),
            start_date: NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(),
            end_date: NaiveDate::from_ymd_opt(2025, 2, 1).unwrap(),
            value_mw: 150.0,
        });
        let data = make_data_anticipated(vec![thermal], 2, records);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("outside the plant's generation bounds")),
            "an in-envelope post-horizon window must not be rejected, got: {:?}",
            ctx.errors()
        );
    }

    /// The post-horizon window declares an explicit `0.0` while
    /// `min_generation_mw` is also `0.0`: the boundary value is accepted, not
    /// mistaken for a missing declaration.
    #[test]
    fn committed_value_bounds_accept_an_explicit_zero_at_the_lower_bound() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(23, 0.0, 200.0)
        };
        let mut records = commitments(23, &[100.0]);
        records.push(AnticipatedCommitmentHistory {
            thermal_id: EntityId::from(23),
            start_date: NaiveDate::from_ymd_opt(2025, 1, 1).unwrap(),
            end_date: NaiveDate::from_ymd_opt(2025, 2, 1).unwrap(),
            value_mw: 0.0,
        });
        let data = make_data_anticipated(vec![thermal], 2, records);
        let mut ctx = ValidationContext::new();
        check_anticipated_thermals(&data, &mut ctx);
        assert!(
            !ctx.errors()
                .iter()
                .any(|e| e.message.contains("outside the plant's generation bounds")),
            "an explicit zero at the lower bound on a post-horizon window must not be \
             rejected, got: {:?}",
            ctx.errors()
        );
    }

    // ── AC-14: non-zero in-bounds window value K=1 — accepted ────────────────

    /// K=1 case: a single window value 204.5647 against `max_generation_mw =
    /// 350.0`. The value lies within [0.0, 350.0], so the bounds check passes
    /// and the validator emits no errors.
    #[test]
    fn test_nonzero_value_in_bounds_accepted_k1() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(2, 0.0, 350.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(2, &[204.5647]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            ctx.errors().is_empty(),
            "expected no errors for an in-bounds window value, got: {:?}",
            ctx.errors()
        );
    }

    /// K=2 acceptance: two non-zero windows, both within
    /// `[min_generation_mw, max_generation_mw]`, are accepted with zero errors.
    /// The pre-horizon-seeding contract delivers each window's rate over its
    /// covered study stage as a sunk-cost commitment; in-bounds seeds carry no
    /// validator errors.
    #[test]
    fn test_k2_two_in_bounds_nonzero_values_accepted() {
        let thermal = make_anticipated_thermal(5, 2, None, None); // min=0.0, max=500.0
        let data = make_data_anticipated(vec![thermal], 5, commitments(5, &[50.0, 30.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            ctx.errors().is_empty(),
            "expected no errors for in-bounds K=2 windows, got: {:?}",
            ctx.errors()
        );
    }

    /// Regression lock: `check_committed_value_bounds` must not emit any
    /// `SemanticAmbiguity` warning for an in-bounds non-zero seed — guards against
    /// reintroducing a same-dispatch-as-zero-seed warning.
    #[test]
    fn test_nonzero_in_bounds_seed_emits_no_semantic_ambiguity_warning() {
        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(2)),
            ..make_thermal(3, 0.0, 350.0)
        };
        let data = make_data_anticipated(vec![thermal], 5, commitments(3, &[100.0, 200.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let all_warnings = ctx.warnings();
        let ambiguity_warnings: Vec<_> = all_warnings
            .iter()
            .filter(|w| {
                w.kind == ErrorKind::SemanticAmbiguity
                    && w.file.to_string_lossy().contains("initial_conditions.json")
            })
            .collect();
        assert!(
            ambiguity_warnings.is_empty(),
            "expected no SemanticAmbiguity warning from initial_conditions.json \
             for an in-bounds non-zero seed, got: {ambiguity_warnings:?}"
        );
    }

    /// K=2 acceptance: mixed in-bounds and out-of-bounds windows. Only the
    /// out-of-bounds window produces an error; the in-bounds window (a zero
    /// value) passes silently. Verifies that the bounds check is per-window, not
    /// per-history.
    #[test]
    fn test_k2_mixed_in_bounds_and_out_of_bounds_only_oob_reported() {
        let thermal = make_anticipated_thermal(7, 2, None, None); // min=0.0, max=500.0
        let data = make_data_anticipated(vec![thermal], 5, commitments(7, &[0.0, 600.0]));
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.message.contains("outside the plant's generation bounds")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one bounds error (600 MW window only), got: {errors:?}"
        );
        assert!(
            relevant[0].message.contains("600"),
            "error must contain value 600, got: {}",
            relevant[0].message
        );
    }

    // ── Bounds test ───────────────────────────────────────────────────────────

    /// min_generation_mw > max_generation_mw produces InvalidValue with "Thermal <id>".
    #[test]
    fn test_thermal_generation_min_greater_than_max() {
        let thermal = make_thermal(10, 500.0, 100.0); // min > max — violation
        let data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(vec![0]),
            vec![],
            vec![],
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(ctx.has_errors());
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| e.kind == ErrorKind::InvalidValue)
            .collect();
        assert_eq!(relevant.len(), 1, "exactly 1 InvalidValue error expected");
        let msg = &relevant[0].message;
        assert!(
            msg.contains("Thermal 10"),
            "message should contain 'Thermal 10', got: {msg}"
        );
    }

    /// min_generation_mw == max_generation_mw produces no error.
    #[test]
    fn test_thermal_generation_equal_bounds_valid() {
        let thermal = make_thermal(11, 200.0, 200.0);
        let data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(vec![0]),
            vec![],
            vec![],
        );
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(!ctx.has_errors());
    }

    // ── Layer 5a rule 16: thermal_bounds override stage_id within [0, n_stages)

    /// Build a `ThermalBoundsRow` with the given thermal_id and stage_id and
    /// no override values set.
    fn make_thermal_bounds_row(thermal_id: i32, stage_id: i32) -> crate::ThermalBoundsRow {
        crate::ThermalBoundsRow {
            thermal_id: EntityId::from(thermal_id),
            stage_id,
            min_generation_mw: None,
            max_generation_mw: None,
            cost_per_mwh: None,
            block_id: None,
        }
    }

    /// Build a `ParsedData` with `n_stages` study stages, one thermal,
    /// and the given `thermal_bounds` rows.
    fn make_data_thermal_bounds(n_stages: usize, rows: Vec<crate::ThermalBoundsRow>) -> ParsedData {
        let thermal = make_thermal(1, 0.0, 100.0);
        let stage_ids: Vec<i32> = (0..n_stages as i32).collect();
        let mut data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(stage_ids),
            vec![],
            vec![],
        );
        data.thermal_bounds = rows;
        data
    }

    /// `n_stages = 5`, row `stage_id = 4` is within `[0, 5)` — accepted.
    #[test]
    fn test_thermal_bounds_override_stage_within_horizon_accepted() {
        let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, 4)]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.file
                    .to_string_lossy()
                    .contains("constraints/thermal_bounds.parquet")
            })
            .collect();
        assert!(
            relevant.is_empty(),
            "expected no thermal_bounds.parquet errors, got: {relevant:?}"
        );
    }

    /// `n_stages = 5`, row `stage_id = 5` is the first invalid index — rejected.
    #[test]
    fn test_thermal_bounds_override_stage_equals_n_rejected() {
        let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, 5)]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.file
                        .to_string_lossy()
                        .contains("constraints/thermal_bounds.parquet")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation, got: {relevant:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("stage_id=5"),
            "message should contain 'stage_id=5', got: {msg}"
        );
        assert!(
            msg.contains("[0, 5)"),
            "message should contain '[0, 5)', got: {msg}"
        );
        assert!(
            msg.contains("not allowed"),
            "message should contain 'not allowed', got: {msg}"
        );
    }

    /// `stage_id = -1` (pre-study stage) — rejected.
    #[test]
    fn test_thermal_bounds_override_stage_negative_rejected() {
        let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, -1)]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.file
                        .to_string_lossy()
                        .contains("constraints/thermal_bounds.parquet")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation for stage_id=-1, got: {relevant:?}"
        );
    }

    /// Three rows, two offending (`stage_id == n_stages` and
    /// `stage_id > n_stages`), one valid. Exactly two errors are emitted.
    #[test]
    fn test_thermal_bounds_override_multiple_offending_rows() {
        let rows = vec![
            make_thermal_bounds_row(1, 0), // valid
            make_thermal_bounds_row(1, 5), // invalid: equals n_stages
            make_thermal_bounds_row(1, 9), // invalid: past n_stages
        ];
        let data = make_data_thermal_bounds(5, rows);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.file
                        .to_string_lossy()
                        .contains("constraints/thermal_bounds.parquet")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            2,
            "expected exactly two BusinessRuleViolations, got: {relevant:?}"
        );
    }

    /// `n_stages = 0`: the half-open interval `[0, 0)` is empty, so any row
    /// at any non-negative stage_id is rejected.
    #[test]
    fn test_thermal_bounds_override_zero_n_stages_all_rejected() {
        let data = make_data_thermal_bounds(0, vec![make_thermal_bounds_row(1, 0)]);
        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.file
                        .to_string_lossy()
                        .contains("constraints/thermal_bounds.parquet")
            })
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one BusinessRuleViolation when n_stages=0, got: {relevant:?}"
        );
    }

    // ── boundary_tests sub-module ─────────────────────────────────────────────
    //
    // These mirror the strict-inequality boundary tests above for the guard
    // `stage_id < 0 || stage_id >= n_stages`; the originals above are intentional
    // duplicate coverage — do not delete them.
    mod boundary_tests {
        use super::*;

        /// `n_stages = 5`, `stage_id = 4` is within `[0, 5)` — accepted.
        #[test]
        fn override_at_t_minus_1_acceptance_boundary() {
            let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, 4)]);
            let mut ctx = ValidationContext::new();
            validate_semantic_hydro_thermal(&data, &mut ctx);
            let errors = ctx.errors();
            let relevant: Vec<_> = errors
                .iter()
                .filter(|e| {
                    e.file
                        .to_string_lossy()
                        .contains("constraints/thermal_bounds.parquet")
                })
                .collect();
            assert!(
                relevant.is_empty(),
                "stage_id=4 with n_stages=5 must be accepted, got: {relevant:?}"
            );
        }

        /// `n_stages = 5`, `stage_id = 5` is the first invalid index — rejected.
        #[test]
        fn override_at_t_rejection_boundary() {
            let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, 5)]);
            let mut ctx = ValidationContext::new();
            validate_semantic_hydro_thermal(&data, &mut ctx);
            let errors = ctx.errors();
            let relevant: Vec<_> = errors
                .iter()
                .filter(|e| {
                    e.kind == ErrorKind::BusinessRuleViolation
                        && e.file
                            .to_string_lossy()
                            .contains("constraints/thermal_bounds.parquet")
                })
                .collect();
            assert_eq!(
                relevant.len(),
                1,
                "expected exactly one BusinessRuleViolation at stage_id=5, got: {relevant:?}"
            );
        }

        /// `n_stages = 5`, `stage_id = 6` (one past the rejection boundary)
        /// — rejected. Interior rejection to complement the boundary
        /// rejection at `stage_id == n_stages`.
        #[test]
        fn override_at_t_plus_one_rejection() {
            let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, 6)]);
            let mut ctx = ValidationContext::new();
            validate_semantic_hydro_thermal(&data, &mut ctx);
            let errors = ctx.errors();
            let relevant: Vec<_> = errors
                .iter()
                .filter(|e| {
                    e.kind == ErrorKind::BusinessRuleViolation
                        && e.file
                            .to_string_lossy()
                            .contains("constraints/thermal_bounds.parquet")
                })
                .collect();
            assert_eq!(
                relevant.len(),
                1,
                "expected exactly one BusinessRuleViolation at stage_id=6, got: {relevant:?}"
            );
        }

        /// `stage_id = -1` (pre-study) — rejected.
        #[test]
        fn override_negative_stage_rejection() {
            let data = make_data_thermal_bounds(5, vec![make_thermal_bounds_row(1, -1)]);
            let mut ctx = ValidationContext::new();
            validate_semantic_hydro_thermal(&data, &mut ctx);
            let errors = ctx.errors();
            let relevant: Vec<_> = errors
                .iter()
                .filter(|e| {
                    e.kind == ErrorKind::BusinessRuleViolation
                        && e.file
                            .to_string_lossy()
                            .contains("constraints/thermal_bounds.parquet")
                })
                .collect();
            assert_eq!(
                relevant.len(),
                1,
                "expected exactly one BusinessRuleViolation at stage_id=-1, got: {relevant:?}"
            );
        }
    }

    // ── AD-1: anticipated_decision on non-anticipated thermal → hard error ─────

    /// AD-1: A generic constraint that references `anticipated_decision(N)` where
    /// thermal `N` is NOT anticipated produces a `BusinessRuleViolation` naming
    /// the constraint and the thermal ID.
    #[test]
    fn test_anticipated_decision_on_non_anticipated_thermal_error() {
        use cobre_core::{
            ConstraintExpression, GenericConstraint, LinearTerm, SlackConfig, VariableRef,
        };

        let thermal = make_thermal(7, 0.0, 500.0); // NOT anticipated
        let constraint = GenericConstraint {
            id: EntityId::from(1),
            name: "bad_constraint".to_string(),
            description: None,
            expression: ConstraintExpression {
                terms: vec![LinearTerm::literal(
                    1.0,
                    VariableRef::AnticipatedDecision {
                        thermal_id: EntityId::from(7),
                    },
                )],
            },
            slack: SlackConfig {
                enabled: false,
                penalty: None,
            },
            bound_lower_affine: None,
            bound_upper_affine: None,
        };
        let stage_ids: Vec<i32> = (0..5).collect();
        let mut data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(stage_ids),
            vec![],
            vec![],
        );
        data.generic_constraints = vec![constraint];

        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        assert!(
            ctx.has_errors(),
            "expected error for non-anticipated thermal"
        );
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| e.kind == ErrorKind::BusinessRuleViolation)
            .collect();
        assert!(
            !relevant.is_empty(),
            "expected BusinessRuleViolation, got: {errors:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("bad_constraint"),
            "message should contain constraint name, got: {msg}"
        );
        assert!(
            msg.contains('7'),
            "message should contain thermal id 7, got: {msg}"
        );
        assert!(
            msg.contains("not an anticipated thermal"),
            "message should explain the rule, got: {msg}"
        );
        let file = relevant[0].file.to_string_lossy();
        assert!(
            file.contains("generic_constraints.json"),
            "file should reference generic_constraints.json, got: {file}"
        );
    }

    // ── AD-2: anticipated_decision on anticipated thermal → no error ───────────

    /// AD-2: A generic constraint that references `anticipated_decision(N)` where
    /// thermal `N` IS anticipated produces no `BusinessRuleViolation` from the
    /// new validator.
    #[test]
    fn test_anticipated_decision_on_anticipated_thermal_ok() {
        use cobre_core::{
            ConstraintExpression, GenericConstraint, LinearTerm, SlackConfig, VariableRef,
            entities::AnticipatedConfig,
        };

        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(2)),
            ..make_thermal(3, 0.0, 500.0)
        };
        let constraint = GenericConstraint {
            id: EntityId::from(10),
            name: "valid_anticipated_constraint".to_string(),
            description: None,
            expression: ConstraintExpression {
                terms: vec![LinearTerm::literal(
                    1.0,
                    VariableRef::AnticipatedDecision {
                        thermal_id: EntityId::from(3),
                    },
                )],
            },
            slack: SlackConfig {
                enabled: false,
                penalty: None,
            },
            bound_lower_affine: None,
            bound_upper_affine: None,
        };
        let mut data = make_data_anticipated(vec![thermal], 5, commitments(3, &[0.0, 0.0]));
        data.generic_constraints = vec![constraint];

        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);
        let errors = ctx.errors();
        let relevant: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.kind == ErrorKind::BusinessRuleViolation
                    && e.file
                        .to_string_lossy()
                        .contains("generic_constraints.json")
            })
            .collect();
        assert!(
            relevant.is_empty(),
            "anticipated_decision on an anticipated thermal must not produce a BusinessRuleViolation, got: {relevant:?}"
        );
    }

    // ── TG-1: thermal_generation on anticipated thermal → SemanticAmbiguity ───

    /// TG-1: A generic constraint that references `thermal_generation(N)` where
    /// thermal `N` IS anticipated produces a `SemanticAmbiguity` warning naming
    /// the constraint and the thermal ID with a hint to use `anticipated_decision`.
    #[test]
    fn test_thermal_generation_on_anticipated_thermal_warns() {
        use cobre_core::{
            ConstraintExpression, GenericConstraint, LinearTerm, SlackConfig, VariableRef,
            entities::AnticipatedConfig,
        };

        let thermal = Thermal {
            anticipated_config: Some(AnticipatedConfig::LeadStages(1)),
            ..make_thermal(5, 0.0, 300.0)
        };
        let constraint = GenericConstraint {
            id: EntityId::from(20),
            name: "ambiguous_constraint".to_string(),
            description: None,
            expression: ConstraintExpression {
                terms: vec![LinearTerm::literal(
                    1.0,
                    VariableRef::ThermalGeneration {
                        thermal_id: EntityId::from(5),
                        block_id: None,
                    },
                )],
            },
            slack: SlackConfig {
                enabled: false,
                penalty: None,
            },
            bound_lower_affine: None,
            bound_upper_affine: None,
        };
        let mut data = make_data_anticipated(vec![thermal], 5, commitments(5, &[0.0]));
        data.generic_constraints = vec![constraint];

        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);

        // No hard errors from the new validator.
        let errors = ctx.errors();
        let hard: Vec<_> = errors
            .iter()
            .filter(|e| {
                e.file
                    .to_string_lossy()
                    .contains("generic_constraints.json")
            })
            .collect();
        assert!(
            hard.is_empty(),
            "thermal_generation on anticipated thermal must not produce a hard error, got: {hard:?}"
        );

        // Exactly one SemanticAmbiguity warning.
        let warnings = ctx.warnings();
        let relevant: Vec<_> = warnings
            .iter()
            .filter(|w| w.kind == ErrorKind::SemanticAmbiguity)
            .collect();
        assert_eq!(
            relevant.len(),
            1,
            "expected exactly one SemanticAmbiguity warning, got: {warnings:?}"
        );
        let msg = &relevant[0].message;
        assert!(
            msg.contains("ambiguous_constraint"),
            "warning should name the constraint, got: {msg}"
        );
        assert!(
            msg.contains('5'),
            "warning should mention thermal id 5, got: {msg}"
        );
        assert!(
            msg.contains("anticipated_decision"),
            "warning should suggest anticipated_decision, got: {msg}"
        );
        let file = relevant[0].file.to_string_lossy();
        assert!(
            file.contains("generic_constraints.json"),
            "file should reference generic_constraints.json, got: {file}"
        );
    }

    // ── TG-2: thermal_generation on non-anticipated thermal → no warning ──────

    /// TG-2: A generic constraint that references `thermal_generation(N)` where
    /// thermal `N` is NOT anticipated produces no `SemanticAmbiguity` warning.
    #[test]
    fn test_thermal_generation_on_non_anticipated_thermal_no_warn() {
        use cobre_core::{
            ConstraintExpression, GenericConstraint, LinearTerm, SlackConfig, VariableRef,
        };

        let thermal = make_thermal(9, 0.0, 200.0); // NOT anticipated
        let constraint = GenericConstraint {
            id: EntityId::from(30),
            name: "plain_thermal_constraint".to_string(),
            description: None,
            expression: ConstraintExpression {
                terms: vec![LinearTerm::literal(
                    1.0,
                    VariableRef::ThermalGeneration {
                        thermal_id: EntityId::from(9),
                        block_id: None,
                    },
                )],
            },
            slack: SlackConfig {
                enabled: false,
                penalty: None,
            },
            bound_lower_affine: None,
            bound_upper_affine: None,
        };
        let stage_ids: Vec<i32> = (0..5).collect();
        let mut data = make_data(
            vec![],
            vec![thermal],
            vec![],
            make_stages(stage_ids),
            vec![],
            vec![],
        );
        data.generic_constraints = vec![constraint];

        let mut ctx = ValidationContext::new();
        validate_semantic_hydro_thermal(&data, &mut ctx);

        let warnings = ctx.warnings();
        let relevant: Vec<_> = warnings
            .iter()
            .filter(|w| w.kind == ErrorKind::SemanticAmbiguity)
            .collect();
        assert!(
            relevant.is_empty(),
            "thermal_generation on a non-anticipated thermal must not emit SemanticAmbiguity, got: {relevant:?}"
        );
    }
}