Spaces:
Running

File size: 92,078 Bytes
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
3ccb7d5
6ab0441
 
 
 
 
 
 
62c7d86
 
c76c38e
 
 
 
 
 
 
 
 
62c7d86
c76c38e
 
62c7d86
 
3ccb7d5
c76c38e
 
 
62c7d86
 
6ab0441
c76c38e
 
 
 
 
62c7d86
 
 
 
 
 
 
3ccb7d5
 
62c7d86
 
c76c38e
 
62c7d86
3ccb7d5
6ab0441
 
 
 
3ccb7d5
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
6ab0441
 
 
3ccb7d5
 
6ab0441
 
abea671
 
 
0255559
 
 
 
 
 
 
abea671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
 
 
 
 
 
 
 
 
abea671
 
 
 
62c7d86
 
abea671
 
 
0255559
abea671
 
 
 
 
c76c38e
 
3ccb7d5
abea671
62c7d86
abea671
62c7d86
3ccb7d5
c76c38e
 
62c7d86
 
 
 
 
abea671
 
 
 
 
c76c38e
abea671
62c7d86
abea671
62c7d86
 
 
 
 
 
 
 
abea671
 
 
 
62c7d86
3ccb7d5
abea671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ffe48ab
3ccb7d5
6ab0441
3ccb7d5
 
6ab0441
3ccb7d5
 
 
 
 
 
ffe48ab
3ccb7d5
 
 
 
 
 
 
 
 
 
ffe48ab
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
4e633a9
 
 
 
6ab0441
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
4e633a9
 
 
 
 
 
 
6ab0441
 
4e633a9
 
6ab0441
 
 
 
 
4e633a9
 
6ab0441
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
4e633a9
 
6ab0441
4e633a9
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
 
 
4e633a9
 
 
 
6ab0441
 
 
4e633a9
6ab0441
4e633a9
 
6ab0441
 
 
 
 
 
 
 
4e633a9
 
 
 
6ab0441
 
 
 
 
4e633a9
 
6ab0441
 
 
4e633a9
 
6ab0441
 
 
 
 
 
4e633a9
 
 
 
6ab0441
4e633a9
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
4e633a9
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
 
6ab0441
 
 
 
 
 
4e633a9
 
6ab0441
 
 
 
 
 
4e633a9
 
 
6ab0441
4e633a9
 
6ab0441
 
 
 
 
 
3ccb7d5
 
 
 
6ab0441
3ccb7d5
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
abea671
 
 
 
 
 
0255559
abea671
 
 
 
0255559
 
 
 
 
 
 
 
 
 
abea671
 
 
 
 
 
 
 
 
4e633a9
 
abea671
 
 
 
 
 
 
4e633a9
 
abea671
 
 
 
 
4e633a9
 
 
abea671
 
 
 
4e633a9
 
 
abea671
 
 
 
4e633a9
 
abea671
 
 
 
 
 
4e633a9
 
abea671
 
 
 
 
 
 
4e633a9
 
abea671
0255559
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
abea671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e633a9
 
 
 
 
abea671
 
4e633a9
 
abea671
 
 
 
4e633a9
 
abea671
 
 
 
 
 
4e633a9
 
abea671
 
 
 
 
4e633a9
 
abea671
 
 
 
 
 
 
4e633a9
 
 
abea671
3ccb7d5
 
 
 
abea671
 
 
3ccb7d5
abea671
3ccb7d5
abea671
3ccb7d5
 
abea671
3ccb7d5
 
 
 
 
 
 
 
abea671
 
6ab0441
 
 
a5f5a54
 
6ab0441
 
 
 
 
 
a5f5a54
 
 
 
 
6ab0441
 
 
a5f5a54
 
6ab0441
 
 
 
 
 
 
 
 
ffe48ab
 
 
a5f5a54
 
 
 
 
 
 
 
 
 
 
6ab0441
 
ffe48ab
f5e049e
ffe48ab
f5e049e
 
ffe48ab
 
 
 
 
 
f5e049e
 
ffe48ab
 
 
6ab0441
 
 
 
 
 
 
 
a5f5a54
 
 
 
 
 
 
 
 
1f3c310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5d885d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94766b3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f3c310
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
abea671
0255559
 
abea671
 
 
 
0255559
abea671
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56acff6
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0386760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
0386760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
 
 
 
1f3c310
0386760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ccb7d5
 
0386760
 
3ccb7d5
 
 
0386760
3ccb7d5
 
 
0386760
 
 
 
 
 
a5f5a54
 
 
 
 
0386760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a5f5a54
 
0386760
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ab0441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
TAF Browser — Pyodide-compatible TAF formulas + recipes.

Pure-Python deterministic computations of TAF (Thermodynamic Attention Framework)
formulas, plus 5 cross-section recipes for the most common viability questions.

Author: Carles Marin <transformerkmarin@gmail.com>
License: Apache-2.0
"""
from __future__ import annotations
import math
import json

# Finite-family core (kept identical to cli/diagnose_model.py).
def finite_family(gamma, N):
    if isinstance(N, bool) or not isinstance(N, int) or N < 1:
        raise ValueError("N must be a positive integer")
    if isinstance(gamma, bool) or not isinstance(gamma, (int, float)) or not math.isfinite(gamma):
        raise ValueError("gamma must be a finite real number")
    logs = [math.log(d) for d in range(1, N + 1)]
    shift = -gamma * logs[-1] if gamma < 0 else 0.0
    if not math.isfinite(shift):
        raise ValueError("gamma*log(N) exceeds floating-point range")
    # Center before multiplication, avoiding overflow and cancellation for gamma<0.
    log_weights = [-gamma * (x - logs[-1] if gamma < 0 else x) for x in logs]
    weights = [math.exp(x) for x in log_weights]
    total = math.fsum(weights)
    p = [w / total for w in weights]
    logZ = shift + math.log(total)
    U = math.fsum(w * x for w, x in zip(p, logs))
    I = math.fsum(w * (x-U)**2 for w, x in zip(p, logs))
    S = -math.fsum(w * math.log(w) for w in p if w > 0)
    try:
        Z = math.exp(logZ)
    except OverflowError:
        Z = float('inf')
    return dict(Z=Z, logZ=logZ, U=U, I=I, Cv=(gamma*math.sqrt(I))**2,
                S=S, F=None if gamma == 0 else -logZ/gamma,
                probabilities=p, weights=weights, total=total)


def finite_quantile(gamma, N, f=0.90):
    if isinstance(f, bool) or not isinstance(f, (int, float)) or not math.isfinite(f) or not 0 < f < 1:
        raise ValueError("f must lie strictly between zero and one")
    family = finite_family(gamma, N)
    target = f * family['total']
    cumulative, correction = 0.0, 0.0
    for d, w in enumerate(family['weights'], 1):
        y = w-correction
        updated = cumulative+y
        correction = (updated-cumulative)-y
        cumulative = updated
        if cumulative >= target:
            return d
    return N



# ════════════════════════════════════════════════════════════════════════════
# Finite-family mathematics (standard identities)
# ════════════════════════════════════════════════════════════════════════════
def gamma_pade(theta: float, T_eval: int) -> float:
    """§26.1 — γ = (2θ - T√2)/(2θ + T√2)"""
    z_sqrt2 = T_eval * math.sqrt(2)
    return (2 * theta - z_sqrt2) / (2 * theta + z_sqrt2)


def gamma_decompose(gamma_pade_val, has_GQA=False, has_SWA=False, n_params=0.0,
                    *, apply_exploratory=False) -> dict:
    """§26.10 — 5-axis decomposition (n=23 OLS, paper sesión 28).

    Calibration audit (2026-05-02 panel re-check):
      δ_GQA      = +0.11   ✓ replicates (group-mean +0.115 on n=9/13)
      δ_SWA      = -0.21   ⚠ ORIGINALLY FIT ON n=1; demoted to None here
                              (insufficient data; group-mean +0.355 with single yes-case).
                              Returning δ_SWA = 0 with `delta_SWA_status: 'exploratory_n1'`
                              instead of applying an unreliable correction.
      δ_post_IH  = -0.15   ⚠ does NOT replicate (group-mean ≈ 0 on n=16/6);
                              recorded as a candidate; disabled by default.
      δ_instruct  not in this v1; v2 has -0.10 with n=3, p=0.06 caveat.
    """
    if not isinstance(apply_exploratory, bool):
        raise TypeError("apply_exploratory must be an explicit boolean")
    delta_GQA = +0.11 if has_GQA and apply_exploratory else 0.0
    # SWA: demoted — original constant rested on n=1.
    delta_SWA = 0.0
    delta_SWA_status = "exploratory_n1_disabled" if has_SWA else "not_applicable"
    post_candidate = -0.15 if n_params >= 4e8 else 0.0
    delta_post_IH = post_candidate if apply_exploratory else 0.0
    return {
        "pade_centroid":         gamma_pade_val,
        "delta_GQA":             delta_GQA,
        "delta_SWA":             delta_SWA,
        "delta_SWA_status":      delta_SWA_status,
        "delta_post_IH":         delta_post_IH,
        "delta_post_IH_status":  "exploratory_no_replication" if post_candidate else "not_applicable",
        "corrections": {
            "SWA": {"candidate": -0.21 if has_SWA else 0.0, "applied": False,
                    "applied_value": 0.0, "status": delta_SWA_status},
            "post_IH": {"candidate": post_candidate, "applied": bool(apply_exploratory and post_candidate),
                        "applied_value": delta_post_IH, "status": "exploratory_no_replication",
                        "eligibility": "parameter_count_proxy_only"},
            "GQA": {"candidate": 0.11 if has_GQA else 0.0, "applied": bool(delta_GQA),
                    "applied_value": delta_GQA, "status": "historical_hypothesis_no_universal_calibration"},
        },
        "experimental_corrections_requested": bool(apply_exploratory),
        "gamma_corrected":       gamma_pade_val + delta_GQA + delta_SWA + delta_post_IH,
        "calibration_warning":  ("SWA correction disabled (originally fit on n=1). "
                                 "post_IH is exploratory and requires explicit opt-in (group-mean ≈ 0). "
                                 "GQA is also disabled by default; explicit opt-in reproduces a historical hypothesis."),
    }


def d_horizon(theta: float, gamma: float):
    """Inverse context coordinate on -1<gamma<1; not a retrieval horizon."""
    if not math.isfinite(theta) or theta <= 0 or not math.isfinite(gamma) or not -1 < gamma < 1:
        return None
    return theta * (1 - gamma) * math.sqrt(2) / (1 + gamma)


def l_niah_c(d_horizon_val):
    """§26.5 — L_NIAH^c = 2·d_horizon."""
    return None if d_horizon_val is None else 2 * d_horizon_val


def chi_susceptibility(gamma: float) -> float:
    """§26.16 — χ = 1/|γ-1|."""
    return float('inf') if gamma == 1.0 else 1.0 / abs(gamma - 1.0)


def p_hallucinate(L: int, theta: float, gamma: float):
    """§26.9 — Horizon-overshoot probability."""
    dh = d_horizon(theta, gamma)
    if dh is None or L <= 0:
        return None
    chi = chi_susceptibility(gamma)
    if chi == float('inf'):
        return None
    geom = max(0.0, 1.0 - (dh / L) ** (1 - gamma))
    return geom * (math.sqrt(chi) / (1 + math.sqrt(chi)))


def theta_design(gamma_target: float, T_eval: int) -> float:
    """§26.3 — θ to land at γ_target at T_eval (Padé inverse)."""
    if gamma_target >= 1 or gamma_target <= -1:
        raise ValueError("gamma_target must be in (-1, 1)")
    return T_eval * math.sqrt(2) * (1 + gamma_target) / (2 * (1 - gamma_target))


def alpha_opt(gamma_target: float, T_eval: int, theta_nominal: float) -> float:
    """§26.4 — α = θ_design / θ_nominal."""
    return theta_design(gamma_target, T_eval) / theta_nominal


def df_window(gamma: float, N: int, f: float = 0.90):
    """Smallest prefix with family mass >=f; not an evaluated cache policy."""
    return finite_quantile(gamma, N, f)


def kv_soft_decay_regime(theta: float, gamma: float, T_train: int) -> str:
    """The historical three-model boundary has no validated operating regime."""
    return "requires_paired_evaluation"


# ════════════════════════════════════════════════════════════════════════════
# §28 — Sesión 29 (2026-04-28): learned-imprint, F2 Chinchilla, Δγ-IH probe
# ════════════════════════════════════════════════════════════════════════════
NU_IMPRINT = -1.0 / (2 * math.pi)  # §28 — learned-imprint slope. ✗ NOT IDENTIFIED
# BY THE DATA. Part II, verbatim: "nu remains unconstrained by the current data" —
# bootstrap 95% CI [-0.260, -0.008], only 11.1% of resamples within 1% of -1/(2pi),
# and pythia-31m drives much of the panel slope. The "0.3% match" framing was
# withdrawn in Part II. The Lean algebra holds and the AbsPE control passes
# (GPT-2, no 2pi period -> nu ~ 0). Consistent, but not strongly identified —
# kept so retired recipe X-21 stays reproducible. Do not build new results on it.
P_0_IMPRINT_M = 14.0                # baseline pythia-14m (smallest panel reference)


def gamma_random_predict(theta: float, T_eval: int, n_params_M: float) -> float:
    """§28.1 — Predicted γ on RANDOM-token input.

    γ_random = γ_pade(θ,T) + ν · log_10(P / P_0),  ν = -1/(2π) ≈ -0.1592.
    Empirical n=22 LLMs (sesión 29). Random-input γ scales with model size
    despite RoPE-Padé predicting only (θ,T) dependence — weights imprint
    a learned positional bias proportional to log(N_params).

    Predicted CI ≈ ±0.18 (95%).
    """
    g_pade = gamma_pade(theta, T_eval)
    return g_pade + NU_IMPRINT * math.log10(max(n_params_M, 1e-3) / P_0_IMPRINT_M)


def imprint_purity(gamma_random_obs: float, theta: float, T_eval: int,
                   n_params_M: float) -> dict:
    """§28.2 — Diagnostic: how clean is the model's RoPE-Padé prediction?

    Compares observed γ_random to predicted (γ_pade + ν·log_10(P/P_0)).
    Negative residual ⇒ extra-strong training imprint (less clean).
    Positive ⇒ weaker than expected imprint (cleaner / less trained).
    """
    g_pred = gamma_random_predict(theta, T_eval, n_params_M)
    g_pade_only = gamma_pade(theta, T_eval)
    residual = gamma_random_obs - g_pred
    return {
        "gamma_random_obs":      gamma_random_obs,
        "gamma_random_pred":     g_pred,
        "gamma_pade_only":       g_pade_only,
        "imprint_predicted":     g_pred - g_pade_only,
        "imprint_residual":      residual,
        "purity":                "clean (within CI)" if abs(residual) < 0.18 else
                                 ("over-imprinted" if residual < 0 else "under-imprinted"),
        "ci_95_half_width":      0.18,
    }


def compute_invariant_K(gamma: float, n_params_M: float,
                        D_tokens: float = None) -> dict:
    """§29 — F2 Chinchilla compute-context invariant.

    K = γ × log(N²·D),  D = 20·N (Chinchilla compute-optimal) if not given.
    Empirical: K ≈ 51.2 ± 16.8 (CV=0.329, n=22). In-distribution if K∈[34, 68].
    """
    N = n_params_M * 1e6
    if D_tokens is None:
        D_tokens = 20 * N
    K = gamma * math.log(N * N * D_tokens)
    panel_mean, panel_std = 51.2, 16.8
    z = (K - panel_mean) / panel_std
    return {
        "K":                K,
        "panel_mean":       panel_mean,
        "panel_std":        panel_std,
        "z_score":          z,
        "in_distribution":  abs(z) <= 1.0,
        "interpretation":   "in-band" if abs(z) <= 1.0 else
                            ("high-K outlier" if z > 0 else "low-K outlier"),
    }


def ih_phase_check(gamma_text, gamma_random, n_params_M=None):
    """Descriptive paired contrast. Legacy sign is preserved explicitly."""
    if not all(math.isfinite(g) for g in (gamma_text, gamma_random)):
        raise ValueError("Both measurements must be finite")
    return {"delta_gamma": gamma_text-gamma_random,
            "delta_convention": "legacy_text_minus_random",
            "gamma_random_minus_text": gamma_random-gamma_text,
            "canonical_convention": "random_minus_text",
            "phase_observed": None, "phase_expected_by_size": None,
            "consistent": None, "status": "circuit_not_identified"}


def gamma_decompose_v2(gamma_pade_val: float, n_params_M: float,
                       has_GQA: bool = False, has_SWA: bool = False,
                       corpus: str = "text", is_instruct: bool = False,
                       *, apply_exploratory=False) -> dict:
    """§28.3 — 6-axis decomposition (sesión 29 update with imprint axis).

    γ_obs = γ_pade
           + ν·log_10(P/P_0)·𝟙[corpus=random]    ← imprint axis. ✗ NOT IDENTIFIED (see NU_IMPRINT)
           + Δ_corpus(text-rand)
           + δ_arch(GQA, SWA)
           + δ_circuit(IH phase)
           + δ_train(steps, RLHF, instruct)
           + ε

    Calibration audit 2026-05-02:
      δ_GQA exploratory and disabled by default; δ_SWA demoted (n=1); δ_post_IH exploratory; δ_instruct exploratory (n=3).
    """
    imprint_candidate = NU_IMPRINT * math.log10(max(n_params_M, 1e-3) / P_0_IMPRINT_M) \
                    if corpus == "random" else 0.0
    delta_imprint = 0.0  # Not identified; do not reactivate through the exploratory flag.
    delta_GQA = +0.11 if has_GQA and apply_exploratory else 0.0
    # SWA disabled: originally fit on n=1.
    delta_SWA = 0.0
    base = gamma_decompose(gamma_pade_val, has_GQA, has_SWA, n_params_M * 1e6,
                           apply_exploratory=apply_exploratory)
    delta_post_IH = base["delta_post_IH"]
    instruct_candidate = -0.10 if is_instruct else 0.0  # F9 tentative (n=3, p=0.06)
    delta_instruct = instruct_candidate if apply_exploratory else 0.0
    return {
        "pade_centroid":       gamma_pade_val,
        "delta_imprint":       delta_imprint,
        "delta_GQA":           delta_GQA,
        "delta_SWA":           delta_SWA,
        "delta_SWA_status":    "exploratory_n1_disabled" if has_SWA else "not_applicable",
        "delta_post_IH":       delta_post_IH,
        "delta_post_IH_status": base["delta_post_IH_status"],
        "delta_instruct":      delta_instruct,
        "delta_instruct_status": "tentative_n3_p0.06" if is_instruct else "not_applicable",
        "delta_imprint_status": "not_identified_disabled" if corpus == "random" else "not_applicable",
        "corrections": {**base["corrections"],
            "instruct": {"candidate": instruct_candidate, "applied": bool(apply_exploratory and instruct_candidate),
                         "applied_value": delta_instruct, "status": "tentative_n3_p0.06"},
            "imprint": {"candidate": imprint_candidate, "applied": False,
                        "applied_value": 0.0, "status": "not_identified_disabled"}},
        "experimental_corrections_requested": bool(apply_exploratory),
        "gamma_corrected":     gamma_pade_val + delta_imprint + delta_GQA
                                + delta_SWA + delta_post_IH + delta_instruct,
        "corpus":              corpus,
        "axes":                ["pade", "imprint", "GQA", "SWA", "IH", "instruct"],
        "calibration_warning":  ("SWA and unidentified imprint disabled. post_IH/instruct require explicit opt-in. "
                                 "GQA is also disabled by default; explicit opt-in reproduces a historical hypothesis."),
    }


def famous_constant_proximity(gamma: float, tolerance: float = 0.01) -> dict:
    """§31 — Detect proximity to famous constants in γ-cluster (sesión 29).

    Empirical hits (n=4 in panel):
      CodeLlama-13b   γ=0.3823 ≈ 1−1/φ = 0.3820 (golden conjugate)
      pythia-1.4b     γ=0.7051 ≈ 1/√2  = 0.7071
      Llama-2-7b      γ=0.2871 ≈ 1−1/√2 = 0.2929
      Mistral-Nemo    γ=0.4284 ≈ log_10(e) = 0.4343
    Returns nearest constant within tolerance, or None.
    """
    phi = (1 + math.sqrt(5)) / 2
    constants = {
        "1−1/φ (golden conjugate)": 1 - 1/phi,
        "1/√2":                     1 / math.sqrt(2),
        "1−1/√2":                   1 - 1/math.sqrt(2),
        "log_10(e)":                math.log10(math.e),
        "1/π":                      1 / math.pi,
        "2/π":                      2 / math.pi,
        "1/φ":                      1 / phi,
        "ln(2)":                    math.log(2),
        "z*_Cayley = (√17−3)/2":    (math.sqrt(17) - 3) / 2,
    }
    hits = []
    for name, val in constants.items():
        err = abs(gamma - val)
        if err <= tolerance:
            hits.append({"constant": name, "value": val, "error": err})
    hits.sort(key=lambda h: h["error"])
    return {
        "gamma":     gamma,
        "tolerance": tolerance,
        "n_hits":    len(hits),
        "hits":      hits[:3],
        "caveat":    "n=4 hits in panel; could be coincidence (continuous distribution)",
    }


# ════════════════════════════════════════════════════════════════════════════
# §17 — Pre-training viability formulas
# ════════════════════════════════════════════════════════════════════════════
def chinchilla_optimal_tokens(N_params: float, ratio: float = 20.0) -> float:
    """§17.30 — Chinchilla 20:1 token budget. D = ratio · N."""
    return ratio * N_params


def chinchilla_optimal_N(D_tokens: float, ratio: float = 20.0) -> float:
    """§17.30 inverse — given D tokens, optimal N = D/20."""
    return D_tokens / ratio


def training_flops(N_params: float, D_tokens: float) -> float:
    """§17.10 — C ≈ 6·N·D total training FLOPs."""
    return 6 * N_params * D_tokens


def training_memory_16N(N_params: float) -> dict:
    """§17.20 — total memory ≈ 16·N bytes (model + grads + Adam moments)."""
    bytes_total = 16 * N_params
    return {
        "bytes": bytes_total,
        "GB": bytes_total / 1e9,
    }


def emergent_threshold(N_params: float) -> str:
    """§17.60 — capability threshold heuristic (Wei 2022)."""
    if N_params >= 1e11:
        return "above 100B — strong reasoning capabilities expected"
    if N_params >= 1e10:
        return "above 10B — most emergent capabilities present"
    if N_params >= 1e9:
        return "above 1B — basic instruction-following, not strong reasoning"
    if N_params >= 1e8:
        return "above 100M — useful for narrow tasks, no emergence"
    return "below 100M — domain-specific tasks only"


def _emerg_tier(N_params: float) -> str:
    """i18n code companion of emergent_threshold (py.x3.i.emerg_* keys)."""
    if N_params >= 1e11:
        return "100b"
    if N_params >= 1e10:
        return "10b"
    if N_params >= 1e9:
        return "1b"
    if N_params >= 1e8:
        return "100m"
    return "sub100m"


# ════════════════════════════════════════════════════════════════════════════
# §19 — Inference economics
# ════════════════════════════════════════════════════════════════════════════
def kv_cache_memory(n_layers, n_kv_heads, d_head, seq_len, bytes_per_element=2.0) -> dict:
    """§19.1 — bytes = 2·L·n_kv·d_h·seq·B."""
    bytes_total = 2 * n_layers * n_kv_heads * d_head * seq_len * bytes_per_element
    return {"bytes": bytes_total, "MB": bytes_total / 1e6, "GB": bytes_total / 1e9}


def model_weights_memory(N_params, bytes_per_element=2.0) -> dict:
    """Inference memory for model weights only (BF16=2, INT8=1, INT4=0.5)."""
    return {"GB": N_params * bytes_per_element / 1e9}


def inference_decode_throughput(N_params, hbm_GB_per_s, bytes_per_element=2.0) -> float:
    """§19.7 — memory-bound decode: tokens/sec = HBM_BW / model_size."""
    model_GB = N_params * bytes_per_element / 1e9
    return hbm_GB_per_s / model_GB


# ════════════════════════════════════════════════════════════════════════════
# §20 — Hardware catalog (curated from vendor docs 2026)
# ════════════════════════════════════════════════════════════════════════════
GPU_CATALOG = {
    # name: {bf16_TFLOPs, hbm_GB, hbm_GB_s, cloud_USD_per_h_spot, tdp_W}
    "H100 SXM":  {"flops": 989,  "vram_GB": 80,  "bw_GB_s": 3350, "usd_h": 2.5,  "tdp": 700},
    "H100 PCIe": {"flops": 756,  "vram_GB": 80,  "bw_GB_s": 2000, "usd_h": 2.0,  "tdp": 350},
    "H200":      {"flops": 989,  "vram_GB": 141, "bw_GB_s": 4800, "usd_h": 3.5,  "tdp": 700},
    "B200":      {"flops": 2250, "vram_GB": 192, "bw_GB_s": 8000, "usd_h": 5.0,  "tdp": 1000},
    "A100 80GB": {"flops": 312,  "vram_GB": 80,  "bw_GB_s": 2000, "usd_h": 1.2,  "tdp": 400},
    "A100 40GB": {"flops": 312,  "vram_GB": 40,  "bw_GB_s": 1555, "usd_h": 1.0,  "tdp": 400},
    "L40S":      {"flops": 362,  "vram_GB": 48,  "bw_GB_s": 864,  "usd_h": 0.7,  "tdp": 350},
    "MI300X":    {"flops": 1307, "vram_GB": 192, "bw_GB_s": 5300, "usd_h": 2.1,  "tdp": 750},
    "RTX 4090":  {"flops": 165,  "vram_GB": 24,  "bw_GB_s": 1008, "usd_h": 0.4,  "tdp": 450},
    "RTX 5090":  {"flops": 419,  "vram_GB": 32,  "bw_GB_s": 1792, "usd_h": 0.7,  "tdp": 575},
    "RTX 5060Ti":{"flops": 36,   "vram_GB": 16,  "bw_GB_s": 448,  "usd_h": 0.0,  "tdp": 180},  # local
}


def cost_per_training_run(N_params: float, D_tokens: float, gpu: str = "H100 SXM",
                          n_gpus: int = 8, mfu: float = 0.45) -> dict:
    """§20.11 — cost = (flops_total / (peak·MFU·n_gpus)) · USD/h."""
    info = GPU_CATALOG.get(gpu)
    if info is None:
        return {"error": f"unknown gpu '{gpu}'", "available": list(GPU_CATALOG.keys())}
    total_flops = training_flops(N_params, D_tokens)  # absolute FLOPs
    effective_flops_per_sec = info["flops"] * 1e12 * mfu * n_gpus
    seconds = total_flops / effective_flops_per_sec
    hours = seconds / 3600
    usd = hours * info["usd_h"] * n_gpus
    return {
        "total_FLOPs": total_flops,
        "hours": hours,
        "days": hours / 24,
        "USD": usd,
        "gpu": gpu, "n_gpus": n_gpus, "mfu": mfu,
    }


def cost_per_inference_token(model_GB: float, gpu: str, batch: int = 1) -> dict:
    """§19.9 / §20.12 — derived $/Mtok from memory-bound decode."""
    info = GPU_CATALOG.get(gpu)
    if info is None:
        return {"error": f"unknown gpu '{gpu}'"}
    tok_per_sec = info["bw_GB_s"] / model_GB * batch
    sec_per_Mtok = 1e6 / tok_per_sec
    h_per_Mtok = sec_per_Mtok / 3600
    usd_per_Mtok = h_per_Mtok * info["usd_h"]
    return {
        "tok_per_sec": tok_per_sec,
        "USD_per_Mtok": usd_per_Mtok,
        "gpu": gpu, "batch": batch,
    }


# ════════════════════════════════════════════════════════════════════════════
# §24 — Cost / ROI
# ════════════════════════════════════════════════════════════════════════════
API_PRICING = {
    # USD per million tokens (input/output blended typical)
    "GPT-4o":         {"input": 2.5,  "output": 10.0},
    "GPT-4o-mini":    {"input": 0.15, "output": 0.60},
    "Claude-Opus-4":  {"input": 15.0, "output": 75.0},
    "Claude-Sonnet-4":{"input": 3.0,  "output": 15.0},
    "Claude-Haiku-4": {"input": 0.80, "output": 4.0},
    "Gemini-1.5-Pro": {"input": 1.25, "output": 5.0},
    "DeepSeek-V3":    {"input": 0.27, "output": 1.10},
    "Llama-3.3-70B (Together)": {"input": 0.88, "output": 0.88},
}


def break_even_volume(training_cost: float, self_inference_per_Mtok: float,
                      api_per_Mtok: float, blend_input_output: float = 0.5) -> dict:
    """§24.3 — monthly tokens at which custom training pays off."""
    savings_per_Mtok = api_per_Mtok - self_inference_per_Mtok
    if savings_per_Mtok <= 0:
        return {"error": "self-host more expensive than API per token; never breaks even"}
    Mtok_breakeven = training_cost / savings_per_Mtok
    return {
        "savings_per_Mtok": savings_per_Mtok,
        "Mtok_breakeven": Mtok_breakeven,
        "tokens_breakeven": Mtok_breakeven * 1e6,
    }


# ════════════════════════════════════════════════════════════════════════════
# RECIPES
# ════════════════════════════════════════════════════════════════════════════

# ─────────────────────────────────────────────────────────────────────
# X-2 — Long Context Viability
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x2(theta, T_train, T_eval, n_attention_heads, n_kv_heads,
                  d_head, n_layers, n_params, has_SWA=False,
                  bytes_per_element=2.0, gamma_obs=None, **_unused):
    """Report configuration and resources; retrieval needs a matched task test."""
    g_pade = gamma_pade(theta, T_eval)
    if gamma_obs is not None and not math.isfinite(gamma_obs):
        raise ValueError("gamma_obs must be finite or absent")
    kv = kv_cache_memory(n_layers, n_kv_heads, d_head, T_eval, bytes_per_element)
    chain = [_step(1, "§5", "gamma_P candidate", "(2theta-T*sqrt(2))/(2theta+T*sqrt(2))",
                  {"theta": theta, "T_eval": T_eval}, g_pade,
                  "Configuration function; not an observation."),
             _step(2, "§19.1", "KV memory", "2*bytes*layers*KV_heads*d_head*T",
                  {"bytes_per_element": bytes_per_element, "T_eval": T_eval}, kv,
                  "Allocation estimate per request; runtime overhead is additional.")]
    if gamma_obs is not None:
        chain.append(_step(3, "§9", "Observed slope", "provided gamma_obs",
                           {"gamma_obs": gamma_obs}, gamma_obs,
                           "Protocol-specific descriptor; not a retrieval score."))
    out = _wrap("X-2", "Long-context evaluation", locals(), chain, "NEEDS EVALUATION",
                "Configuration and a fitted slope do not determine retrieval success.",
                "Run a matched retrieval benchmark at the requested length and retain its protocol.",
                reason_code="alignment.x2.reason", mit_code="alignment.x2.next")
    out.update({"horizon_source": "not_identified", "gamma_observed": gamma_obs,
                "retrieval_prediction": None, "caveats": ["task_evaluation_required"],
                "confidence": _confidence([("benchmark_no", "warn")])})
    return out


# ─────────────────────────────────────────────────────────────────────
# X-1 — Custom training vs API for a domain task
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x1(N_params, D_tokens=None, gpu="H100 SXM", n_gpus=8, mfu=0.45,
                  api_model="GPT-4o", monthly_tokens_M=10.0, **_unused):
    """X-1: custom training (Chinchilla optimal) vs API."""
    chain = []

    # Step 1: Chinchilla optimal D
    if D_tokens is None:
        D_tokens = chinchilla_optimal_tokens(N_params)
    chain.append(_step(1, "§17.30", "Chinchilla optimal D", "D = 20·N",
                       {"N_params": N_params}, D_tokens,
                       f"recommended D = {D_tokens:.2e} tokens",
                       interp_code="x1.i.chinchilla",
                       interp_params={"D": f"{D_tokens:.2e}"}))

    # Step 2: training FLOPs
    flops = training_flops(N_params, D_tokens)
    chain.append(_step(2, "§17.10", "Training FLOPs", "C = 6·N·D",
                       {"N": N_params, "D": D_tokens}, flops,
                       f"{flops:.2e} FLOPs total",
                       interp_code="x1.i.flops",
                       interp_params={"flops": f"{flops:.2e}"}))

    # Step 3: training cost
    cost = cost_per_training_run(N_params, D_tokens, gpu=gpu, n_gpus=n_gpus, mfu=mfu)
    chain.append(_step(3, "§20.11", "Training cost",
                       "hours·USD/h·n_gpus = total $",
                       {"gpu": gpu, "n_gpus": n_gpus, "mfu": mfu}, cost,
                       f"${cost['USD']:,.0f} over {cost['days']:.1f} days",
                       interp_code="x1.i.cost",
                       interp_params={"usd": f"{cost['USD']:,.0f}",
                                      "days": f"{cost['days']:.1f}"}))

    # Step 4: model_GB and decode throughput
    model_GB = N_params * 2 / 1e9  # BF16
    inf = cost_per_inference_token(model_GB, gpu, batch=1)
    chain.append(_step(4, "§19.9 / §20.12", "Self-inference $/Mtok",
                       "BW / model_GB → tok/s → $/Mtok",
                       {"model_GB": model_GB, "gpu": gpu}, inf,
                       f"${inf['USD_per_Mtok']:.2f} per million tokens (single user)",
                       interp_code="x1.i.selfinf",
                       interp_params={"usd": f"{inf['USD_per_Mtok']:.2f}"}))

    # Step 5: API blended price
    api = API_PRICING.get(api_model, {"input": 2.0, "output": 8.0})
    api_blend = (api["input"] + api["output"]) / 2
    chain.append(_step(5, "§24.X", f"{api_model} blended price",
                       "(input + output) / 2 USD/Mtok",
                       {"api_model": api_model}, api_blend,
                       f"${api_blend:.2f}/Mtok blended",
                       interp_code="x1.i.apiblend",
                       interp_params={"usd": f"{api_blend:.2f}"}))

    # Step 6: break-even
    be = break_even_volume(cost["USD"], inf["USD_per_Mtok"], api_blend)
    if "error" in be:
        _be_ic, _be_ip = "x1.i.be_never", {}
    else:
        _be_months = be["Mtok_breakeven"] / max(monthly_tokens_M, 0.001)
        _be_ic = "x1.i.be"
        _be_ip = {"mtok": f"{be['Mtok_breakeven']:.0f}",
                  "months": f"{_be_months:.1f}", "monthly": monthly_tokens_M}
    chain.append(_step(6, "§24.3", "Break-even tokens", "training$ / (api - self) = Mtok",
                       {"training_cost": cost["USD"]}, be,
                       _be_interp(be, monthly_tokens_M),
                       interp_code=_be_ic, interp_params=_be_ip))

    # Verdict
    if "error" in be:
        verdict, reason = "NO", be["error"]
        mit = f"Stick with {api_model} API."
        _rc, _rp = "x1.r.never", {}
        _mc, _mp = "x1.m.stick_api", {"api_model": api_model}
    elif monthly_tokens_M >= be["Mtok_breakeven"]:
        verdict = "YES (custom)"
        months_to_payoff = be["Mtok_breakeven"] / monthly_tokens_M
        reason = (f"At {monthly_tokens_M} M tokens/month, break-even in "
                  f"{months_to_payoff:.1f} months. Long-term custom is cheaper.")
        mit = f"Train at {gpu}×{n_gpus}; serve self-hosted."
        _rc, _rp = "x1.r.yes", {"monthly": monthly_tokens_M,
                                "months": f"{months_to_payoff:.1f}"}
        _mc, _mp = "x1.m.train_self", {"gpu": gpu, "n_gpus": n_gpus}
    else:
        months = be["Mtok_breakeven"] / monthly_tokens_M
        verdict = "NO (API)"
        reason = (f"At {monthly_tokens_M} M tokens/month, break-even in "
                  f"{months:.1f} months — too slow.")
        mit = f"Use {api_model} API (cheaper for your volume)."
        _rc, _rp = "x1.r.no", {"monthly": monthly_tokens_M, "months": f"{months:.1f}"}
        _mc, _mp = "x1.m.use_api", {"api_model": api_model}

    return _wrap("X-1", "Custom training vs API", locals(), chain, verdict, reason, mit,
                 reason_code=_rc, reason_params=_rp, mit_code=_mc, mit_params=_mp)


def _be_interp(be, monthly):
    if "error" in be:
        return be["error"]
    months = be["Mtok_breakeven"] / max(monthly, 0.001)
    return f"break-even at {be['Mtok_breakeven']:.0f} Mtok ({months:.1f} months at {monthly} M/mo)"


# ─────────────────────────────────────────────────────────────────────
# X-3 — Pre-flight check on $5K training budget
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x3(USD_budget=5000.0, gpu="H100 SXM", mfu=0.45, n_gpus=1, **_unused):
    """X-3: given $ budget, what model can I train?"""
    chain = []
    info = GPU_CATALOG[gpu]

    # Step 1: GPU-hours we can afford
    hours = USD_budget / (info["usd_h"] * n_gpus)
    chain.append(_step(1, "§20.11", "Affordable GPU-hours", "USD / ($/h·n_gpus)",
                       {"USD": USD_budget, "gpu": gpu, "n_gpus": n_gpus}, hours,
                       f"{hours:.0f} GPU-hours total ({hours/24:.1f} days at full use)",
                       interp_code="x3.i.hours",
                       interp_params={"hours": f"{hours:.0f}", "days": f"{hours/24:.1f}"}))

    # Step 2: max FLOPs
    max_flops = info["flops"] * 1e12 * mfu * n_gpus * hours * 3600
    chain.append(_step(2, "§17.10", "Max training FLOPs",
                       "peak·MFU·n_gpus·seconds",
                       {"peak_TFLOPs": info["flops"], "MFU": mfu}, max_flops,
                       f"{max_flops:.2e} effective FLOPs",
                       interp_code="x3.i.flops",
                       interp_params={"flops": f"{max_flops:.2e}"}))

    # Step 3: Chinchilla-optimal N (with D=20N)
    # 6·N·D = max_flops, D=20N → 120·N² = max_flops → N = sqrt(max_flops/120)
    N_chinchilla = math.sqrt(max_flops / 120)
    D_chinchilla = 20 * N_chinchilla
    chain.append(_step(3, "§17.30", "Chinchilla-optimal N",
                       "N = √(C/120) at D=20N", {"max_FLOPs": max_flops},
                       N_chinchilla,
                       f"N ≈ {N_chinchilla:.2e} params with D = {D_chinchilla:.2e} tokens",
                       interp_code="x3.i.chinchilla",
                       interp_params={"N": f"{N_chinchilla:.2e}",
                                      "D": f"{D_chinchilla:.2e}"}))

    # Step 4: emergence check
    emerg = emergent_threshold(N_chinchilla)
    _tier = _emerg_tier(N_chinchilla)
    chain.append(_step(4, "§17.60", "Emergence threshold", "Wei 2022 capability",
                       {"N": N_chinchilla}, emerg, emerg,
                       interp_code=f"x3.i.emerg_{_tier}"))

    # Step 5: memory budget check
    mem = training_memory_16N(N_chinchilla)
    fits = mem["GB"] <= info["vram_GB"]
    chain.append(_step(5, "§17.20", "16N training memory",
                       "model + grads + AdamW",
                       {"N": N_chinchilla}, mem,
                       f"{mem['GB']:.1f} GB needed; "
                       f"{'fits in ' if fits else 'EXCEEDS '}{info['vram_GB']} GB VRAM",
                       interp_code=("x3.i.mem_fits" if fits else "x3.i.mem_exceeds"),
                       interp_params={"gb": f"{mem['GB']:.1f}",
                                      "vram": info["vram_GB"]}))

    # Verdict
    if N_chinchilla < 1e8:
        verdict, reason = "TINY-MODEL", f"Budget supports only ~{N_chinchilla:.0e} params"
        mit = "Use LoRA fine-tuning of larger pretrained model instead."
        _rc, _rp = "x3.r.tiny", {"N": f"{N_chinchilla:.0e}"}
        _mc, _mp = "x3.m.lora", {}
    elif not fits:
        verdict, reason = "MEMORY-LIMITED", f"Chinchilla N ({N_chinchilla:.1e}) doesn't fit one {gpu}"
        mit = f"Use ZeRO-3 across multiple GPUs (need ≥{math.ceil(mem['GB']/info['vram_GB'])}× {gpu}) OR train smaller N undertrained."
        _rc, _rp = "x3.r.memlimit", {"N": f"{N_chinchilla:.1e}", "gpu": gpu}
        _mc, _mp = "x3.m.zero3", {"n": math.ceil(mem['GB']/info['vram_GB']), "gpu": gpu}
    else:
        verdict = "GO"
        reason = (f"At ${USD_budget}, train {N_chinchilla:.1e}-param model on "
                  f"{D_chinchilla:.1e} tokens in ~{hours/24:.1f} days. "
                  f"Capability tier: {emerg.split('—')[0].strip()}.")
        mit = "None — proceed with Chinchilla-optimal recipe."
        _rc = f"x3.r.go_{_tier}"
        _rp = {"budget": USD_budget, "N": f"{N_chinchilla:.1e}",
               "D": f"{D_chinchilla:.1e}", "days": f"{hours/24:.1f}"}
        _mc, _mp = "x3.m.none", {}

    return _wrap("X-3", "Budget pre-flight", locals(), chain, verdict, reason, mit,
                 reason_code=_rc, reason_params=_rp, mit_code=_mc, mit_params=_mp)


# ─────────────────────────────────────────────────────────────────────
# X-5 — Hardware selection for serving
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x5(N_params, T_eval=4096, n_layers=32, n_kv_heads=8, d_head=128,
                  bytes_per_weight=2.0, target_tokens_per_day=10_000_000.0,
                  concurrent_users=1, **_unused):
    """X-5: which GPU should I use to serve N-param model at L context?"""
    chain = []

    # Step 1: weights memory
    w_mem = model_weights_memory(N_params, bytes_per_weight)
    chain.append(_step(1, "§19.X", "Model weights memory",
                       "N · bytes_per_weight",
                       {"N": N_params, "bytes": bytes_per_weight}, w_mem,
                       f"{w_mem['GB']:.1f} GB for weights",
                       interp_code="x5.i.weights",
                       interp_params={"gb": f"{w_mem['GB']:.1f}"}))

    # Step 2: KV cache per request
    kv = kv_cache_memory(n_layers, n_kv_heads, d_head, T_eval, bytes_per_weight)
    chain.append(_step(2, "§19.1", "KV cache (per request)",
                       "2·L·n_kv·d_h·seq·B",
                       {"n_layers": n_layers, "n_kv": n_kv_heads,
                        "d_head": d_head, "seq": T_eval}, kv,
                       f"{kv['GB']:.2f} GB per concurrent request",
                       interp_code="x5.i.kv",
                       interp_params={"gb": f"{kv['GB']:.2f}"}))

    # Step 3: total memory needed
    total_GB = w_mem["GB"] + kv["GB"] * concurrent_users
    chain.append(_step(3, "§20.3", "Total GPU memory",
                       "weights + KV·n_concurrent", {}, {"GB": total_GB},
                       f"{total_GB:.1f} GB for {concurrent_users} concurrent users",
                       interp_code="x5.i.total",
                       interp_params={"gb": f"{total_GB:.1f}", "n": concurrent_users}))

    # Step 4: scan GPU catalog
    candidates = []
    for name, info in GPU_CATALOG.items():
        if info["vram_GB"] < total_GB:
            continue
        # Decode throughput estimate (memory-bound)
        tok_per_s = info["bw_GB_s"] / w_mem["GB"]
        tok_per_day = tok_per_s * 86400
        capacity_users = tok_per_day / target_tokens_per_day
        usd_per_day = info["usd_h"] * 24
        usd_per_Mtok = (usd_per_day / (tok_per_day / 1e6)) if tok_per_day > 0 else float('inf')
        candidates.append({
            "gpu": name, "vram_GB": info["vram_GB"], "bw_GB_s": info["bw_GB_s"],
            "tok_per_sec": tok_per_s, "tok_per_day": tok_per_day,
            "USD_per_day": usd_per_day, "USD_per_Mtok": usd_per_Mtok,
            "users_supported": capacity_users,
        })
    candidates.sort(key=lambda c: c["USD_per_Mtok"])
    chain.append(_step(4, "§20", f"Eligible GPUs (≥{total_GB:.0f}GB)",
                       "filter + rank by $/Mtok",
                       {"min_VRAM": total_GB}, candidates[:5],
                       f"{len(candidates)} GPUs fit; cheapest: {candidates[0]['gpu'] if candidates else 'NONE'}",
                       interp_code=("x5.i.fit" if candidates else "x5.i.fit_none"),
                       interp_params=({"n": len(candidates), "gpu": candidates[0]["gpu"]}
                                      if candidates else {})))

    # Verdict
    if not candidates:
        verdict, reason = "NO", f"No single GPU has ≥{total_GB:.0f} GB VRAM."
        mit = (f"Use tensor parallelism across multiple GPUs "
               f"(e.g. 2× H100 = 160GB), or quantize to INT8 (halves memory).")
        _rc, _rp = "x5.r.no", {"gb": f"{total_GB:.0f}"}
        _mc, _mp = "x5.m.tp_or_quant", {}
    else:
        best = candidates[0]
        verdict = "YES"
        reason = (f"Best GPU: {best['gpu']} at ${best['USD_per_Mtok']:.2f}/Mtok. "
                  f"Supports {best['users_supported']:.1f}× your daily target.")
        mit = f"Provision {best['gpu']}, expected {best['tok_per_sec']:.0f} tok/s decode."
        _rc, _rp = "x5.r.yes", {"gpu": best["gpu"], "usd": f"{best['USD_per_Mtok']:.2f}",
                                "x": f"{best['users_supported']:.1f}"}
        _mc, _mp = "x5.m.provision", {"gpu": best["gpu"], "toks": f"{best['tok_per_sec']:.0f}"}

    return _wrap("X-5", "Hardware selection for serving", locals(), chain, verdict, reason, mit,
                 reason_code=_rc, reason_params=_rp, mit_code=_mc, mit_params=_mp)


# ─────────────────────────────────────────────────────────────────────
# X-19 — KV compression decision (ours vs literature)
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x19(theta, T_train, T_eval, n_attention_heads, n_kv_heads,
                   d_head, n_layers, n_params, has_SWA=False, gamma_obs=None, **_unused):
    """Family mass calculator and evaluation plan, without a quality guarantee."""
    g = gamma_pade(theta, T_eval) if gamma_obs is None else gamma_obs
    df = df_window(g, T_eval, 0.90)
    kv = kv_cache_memory(n_layers, n_kv_heads, d_head, T_eval)
    chain = [_step(1, "§11", "Derived family D_90", "min D: sum(d^-gamma,d<=D)/Z_N >= 0.9",
                   {"gamma": g, "N": T_eval, "f": .9}, df,
                   "Finite family on 1..N; not measured retained attention mass."),
             _step(2, "§19.1", "Baseline KV memory", "2*bytes*layers*KV_heads*d_head*T",
                   {"T_eval": T_eval}, kv, "Allocation estimate, not measured savings.")]
    out = _wrap("X-19", "KV policy evaluation", locals(), chain, "NEEDS EVALUATION",
                "The finite-family quantile is calculable; a cache policy needs paired quality and resource measurements.",
                "Compare full attention, hard cutoff and soft weights inside training context; measure actual eviction, memory and latency.",
                reason_code="alignment.x19.reason", mit_code="alignment.x19.next")
    out.update({"D90_kind": "derived_power_law", "gamma_source": "candidate" if gamma_obs is None else "provided_measurement",
                "policy_recommendation": None, "soft_weight_implementation": "add log(w) to scores; w=0 is a mask",
                "historical_soft_decay_scope": "4096-token extrapolation beyond Pythia training context 2048"})
    return out


# ─────────────────────────────────────────────────────────────────────
# X-21 — Imprint Purity Diagnostic (sesión 29 — uses §28 ν=−1/(2π))
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x21(theta, T_train, n_attention_heads, n_kv_heads,
                   d_head, n_layers, n_params, T_eval=None,
                   gamma_random_obs=None, **_unused):
    """X-21: how clean is the model's RoPE-Padé prediction?  ✗ RETIRED 2026-08.

    Predicts γ on RANDOM-token input via learned-imprint formula:
      γ_random = γ_pade(θ,T) + ν·log_10(P/14M),  ν = −1/(2π) ≈ −0.1592
    If user provides observed γ_random, returns purity diagnostic.

    RETIRED: not because ν is disproved, but because it is *not identified*.
    Part II states upfront "ν remains unconstrained by the current data":
    bootstrap 95% CI [−0.260, −0.008], only 11.1% of resamples within 1% of
    −1/(2π), pythia-31m driving much of the panel slope; and it withdrew the
    "0.3% match" framing by name. The Lean algebra holds and the AbsPE control
    passes (GPT-2, no 2π period → ν ≈ 0). A slope that is consistent but not
    strongly identified is too weak a footing for a shipped diagnostic. The
    function is kept callable so published runs stay reproducible; its verdict
    is prefixed "✗ RETIRED" and must not be acted on. See docs/LIMITATIONS.md §2.
    """
    chain = []
    if T_eval is None:
        T_eval = T_train

    # Step 1: γ_Padé baseline
    g_pade = gamma_pade(theta, T_eval)
    chain.append(_step(1, "§26.1", "γ_Padé", "(2θ-T√2)/(2θ+T√2)",
                       {"theta": theta, "T_eval": T_eval}, g_pade,
                       _phase_label(g_pade),
                       interp_code=_phase_code(g_pade)))

    # Step 2: predicted imprint shift
    n_params_M = n_params / 1e6
    imprint_shift = NU_IMPRINT * math.log10(max(n_params_M, 1e-3) / P_0_IMPRINT_M)
    chain.append(_step(2, "§28.1", "Imprint shift", "ν·log_10(P/P_0), ν=−1/(2π)",
                       {"P_M": n_params_M, "P_0_M": P_0_IMPRINT_M, "nu": NU_IMPRINT},
                       imprint_shift,
                       f"Bigger model → stronger imprint (more negative shift).",
                       interp_code="x21.i.shift"))

    # Step 3: predicted γ_random
    g_pred = g_pade + imprint_shift
    chain.append(_step(3, "§28.1", "γ_random predicted", "γ_pade + ν·log_10(P/P_0)",
                       {"gamma_pade": g_pade, "imprint": imprint_shift}, g_pred,
                       f"Predicted γ_random = {g_pred:.4f} ± 0.18 (95% CI)",
                       interp_code="x21.i.pred",
                       interp_params={"g": f"{g_pred:.4f}"}))

    # Step 4: purity diagnostic if observed value provided
    if gamma_random_obs is not None:
        purity = imprint_purity(gamma_random_obs, theta, T_eval, n_params_M)
        _res = purity["imprint_residual"]
        _purity_ic = ("x21.i.purity_clean" if abs(_res) < 0.18 else
                      ("x21.i.purity_over" if _res < 0 else "x21.i.purity_under"))
        chain.append(_step(4, "§28.2", "Imprint purity",
                           "obs − pred (purity = within ±0.18)",
                           {"gamma_random_obs": gamma_random_obs,
                            "gamma_random_pred": g_pred},
                           purity["imprint_residual"], purity["purity"],
                           interp_code=_purity_ic))
        verdict = "CLEAN" if abs(purity["imprint_residual"]) < 0.18 else \
                  ("OVER-IMPRINTED" if purity["imprint_residual"] < 0 else "UNDER-IMPRINTED")
        reason = (f"Residual γ_random_obs − γ_pred = {purity['imprint_residual']:+.4f}. "
                  f"95% CI is ±0.18.")
        mit = ("Models far from prediction may have anomalous training (e.g. heavy "
               "fine-tuning, format conversion). Compare to native checkpoint.")
        _rc, _rp = "x21.r.residual", {"res": f"{purity['imprint_residual']:+.4f}"}
        _mc, _mp = "x21.m.check_native", {}
    else:
        verdict = "PREDICTION ONLY"
        reason = (f"Predicted γ_random = {g_pred:.4f}. Provide gamma_random_obs to "
                  f"check purity (measure on RANDOM token sequences, e.g. via E4 protocol).")
        mit = ("To measure: run a 150-prompt forward pass on RANDOM-token sequences "
               "across distances d=10..1000 and fit power law. "
               "(See https://github.com/karlesmarin/tafagent for E4 protocol.)")
        _rc, _rp = "x21.r.pred_only", {"g": f"{g_pred:.4f}"}
        _mc, _mp = "x21.m.measure", {}

    # ── Retired 2026-08: the ν slope this recipe rests on is not identified by the data.
    # The verdict is prefixed rather than suppressed so that anyone calling the
    # function directly (CLI, notebook, cached UI) is told, instead of silently
    # receiving a number whose basis no longer stands.
    verdict = f"✗ RETIRED — {verdict}"
    reason = (f"{reason} ⚠ This recipe rests on the learned-imprint slope "
              f"ν = −1/(2π), which Part II states is 'unconstrained by the "
              f"current data' (bootstrap 95% CI [−0.260, −0.008]; 11.1% of "
              f"resamples within 1% of −1/(2π)). Consistent, but not strongly "
              f"identified. See docs/LIMITATIONS.md §2.")
    mit = (f"{mit} Do not act on this verdict. Measure γ directly (Recipe 1) "
           f"instead of predicting it from ν.")

    return _wrap("X-21", "Imprint Purity Diagnostic ✗ RETIRED", locals(), chain,
                 verdict, reason, mit,
                 reason_code=_rc, reason_params=_rp, mit_code=_mc, mit_params=_mp)


# ─────────────────────────────────────────────────────────────────────
# X-22 — Compute-Context Invariant Check (sesión 29 — F2 Chinchilla)
# ─────────────────────────────────────────────────────────────────────
def run_recipe_x22(theta, T_train, n_params, gamma_obs, D_tokens=None,
                   T_eval=None, **_unused):
    """X-22: does the model lie in the empirical Chinchilla invariant band?

    K = γ × log(N²·D),  D = 20·N if not given.
    Empirical: K ≈ 51.2 ± 16.8 (CV=0.329, n=22 panel).
    """
    chain = []
    if T_eval is None:
        T_eval = T_train

    n_params_M = n_params / 1e6
    if D_tokens is None:
        D_tokens = 20 * n_params  # Chinchilla compute-optimal

    # Step 1: K computation
    inv = compute_invariant_K(gamma_obs, n_params_M, D_tokens)
    chain.append(_step(1, "§29", "K = γ·log(N²·D)", "γ × ln(N²·D)",
                       {"gamma": gamma_obs, "N": n_params, "D": D_tokens},
                       inv["K"],
                       f"K = {inv['K']:.2f} (panel mean {inv['panel_mean']:.1f} ± "
                       f"{inv['panel_std']:.1f})",
                       interp_code="x22.i.k",
                       interp_params={"K": f"{inv['K']:.2f}",
                                      "mean": f"{inv['panel_mean']:.1f}",
                                      "std": f"{inv['panel_std']:.1f}"}))

    # Step 2: z-score interpretation
    _z_ic = ("x22.i.z_inband" if inv["in_distribution"] else
             ("x22.i.z_high" if inv["z_score"] > 0 else "x22.i.z_low"))
    chain.append(_step(2, "§29", "z-score vs panel", "(K − μ)/σ",
                       {"K": inv["K"], "mean": inv["panel_mean"],
                        "std": inv["panel_std"]},
                       inv["z_score"],
                       inv["interpretation"],
                       interp_code=_z_ic))

    # Step 3: γ_pade comparison (anomaly test)
    g_pade = gamma_pade(theta, T_eval)
    pade_diff = gamma_obs - g_pade
    chain.append(_step(3, "§26.1", "γ deviation from Padé", "γ_obs − γ_pade",
                       {"gamma_obs": gamma_obs, "gamma_pade": g_pade}, pade_diff,
                       "negative = anomaly (sub-Padé); positive = supra-Padé",
                       interp_code="x22.i.pade"))

    if inv["in_distribution"]:
        verdict = "IN-BAND"
        reason = f"K = {inv['K']:.2f} within ±1σ of panel mean {inv['panel_mean']:.1f}."
        mit = "Model conforms to compute-context invariant. No action needed."
        _rc, _rp = "x22.r.inband", {"K": f"{inv['K']:.2f}", "mean": f"{inv['panel_mean']:.1f}"}
        _mc, _mp = "x22.m.none", {}
    else:
        verdict = "OUTLIER"
        reason = (f"K = {inv['K']:.2f} ({inv['interpretation']}). "
                  f"|z| = {abs(inv['z_score']):.2f} > 1.")
        mit = ("High-K (over-concentrating attention for given compute) or low-K "
               "(under-using compute for attention concentration). Check tokenizer, "
               "training recipe, fine-tuning history.")
        _rc = "x22.r.outlier_high" if inv["z_score"] > 0 else "x22.r.outlier_low"
        _rp = {"K": f"{inv['K']:.2f}", "z": f"{abs(inv['z_score']):.2f}"}
        _mc, _mp = "x22.m.outlier", {}

    return _wrap("X-22", "Historical compute coordinate", locals(), chain,
                 "UNVALIDATED", "The panel coordinate is not a model-capacity invariant.",
                 "Use measured compute, task quality and context; no invariant-based recommendation.",
                 reason_code="alignment.x22.reason", mit_code="alignment.x22.next")


def run_recipe_x23(n_params, gamma_text=None, gamma_random=None, **_unused):
    """Two measured slopes do not identify induction-head formation."""
    chain = []
    contrast = None
    if gamma_text is not None and gamma_random is not None:
        contrast = ih_phase_check(gamma_text, gamma_random)
        chain.append(_step(1, "§9", "Canonical contrast", "gamma_random-gamma_text",
                           {"gamma_text": gamma_text, "gamma_random": gamma_random},
                           contrast["gamma_random_minus_text"],
                           "Compare only matched supports and protocols; circuit attribution needs functional tests."))
    out = _wrap("X-23", "Corpus contrast", locals(), chain, "NEEDS EVALUATION",
                "Neither parameter count nor the contrast sign identifies an induction circuit.",
                "Measure prefix matching/copying and interventions under a fixed protocol.",
                reason_code="alignment.x23.reason", mit_code="alignment.x23.next")
    out["contrast"] = contrast
    return out


# ════════════════════════════════════════════════════════════════════════════
# Helpers
# ════════════════════════════════════════════════════════════════════════════
def _step(n, sec, name, formula, inputs, result, interpretation=None, breakdown=None,
          interp_code=None, interp_params=None):
    s = {"step": n, "section": sec, "name": name, "formula": formula,
         "inputs": inputs, "result": result}
    if interpretation:
        s["interpretation"] = interpretation
    if breakdown:
        s["breakdown"] = breakdown
    # i18n: message code + params so the UI can localize; the English
    # `interpretation` text stays as fallback (incremental migration).
    if interp_code:
        s["interp_code"] = interp_code
        s["interp_params"] = interp_params or {}
    return s


def _wrap(rid, rname, locals_dict, chain, verdict, reason, mitigation,
          reason_code=None, reason_params=None, mit_code=None, mit_params=None):
    # Clean inputs (drop chain/internal vars)
    inputs = {k: v for k, v in locals_dict.items()
              if not k.startswith("_") and k not in
              ("chain", "verdict", "reason", "mit", "info", "be", "kv", "g_pade", "g_corr",
               "decomp", "dh", "l_niah", "p_hallu", "cost", "model_GB", "inf", "api",
               "api_blend", "fits", "mem", "emerg", "max_flops", "hours",
               "N_chinchilla", "D_chinchilla", "candidates", "best", "tok_per_s",
               "tok_per_day", "capacity_users", "usd_per_day", "usd_per_Mtok",
               "total_GB", "w_mem", "df", "df_zone_ok", "regime", "has_GQA",
               "margin", "months", "months_to_payoff", "name",
               "caveats", "horizon_source", "dh_native", "pdi", "pdi_info",
               "dh_obs", "gamma_obs")}
    out = {"recipe_id": rid, "recipe_name": rname, "inputs": inputs,
           "chain": chain, "verdict": verdict, "reason": reason,
           "mitigation": mitigation}
    # i18n codes (same incremental pattern as _step)
    if reason_code:
        out["reason_code"] = reason_code
        out["reason_params"] = reason_params or {}
    if mit_code:
        out["mit_code"] = mit_code
        out["mit_params"] = mit_params or {}
    return out


def _confidence(factors):
    """Heuristic evidence checklist — mirror of js/confidence.js.

    Scores listed (key, status) factors only; all Python weights are 1.
    The legacy pct field is a score alias, not a calibrated probability.
    """
    w = {"ok": 1.0, "warn": 0.5, "miss": 0.0}
    total = len(factors)
    score = sum(w.get(s, 0.0) for _, s in factors)
    pct = round(100 * score / total) if total else 0
    band = "high" if pct >= 80 else "medium" if pct >= 55 else "low"
    return {"score": pct, "max_score": 100, "kind": "evidence_checklist",
            "calibrated": False, "scope": "listed_factors_only", "pct": pct, "band": band,
            "factors": [{"key": k, "status": s} for k, s in factors]}


def _phase_label(g):
    if 0 < g < 1:
        return "Phase A (long-range OK)"
    if g >= 1:
        return "Phase B / Hagedorn"
    return "Phase B / catastrophic (negative γ — T too large for θ)"


def _phase_code(g):
    """i18n code companion of _phase_label (py.phase.* keys in the UI)."""
    if 0 < g < 1:
        return "phase.a"
    if g >= 1:
        return "phase.b"
    return "phase.catastrophic"


# ════════════════════════════════════════════════════════════════════════════
# §32 — Sesión 29 visual-diagnostic helpers (paper 2 §4 bimodal + Hagedorn)
# ════════════════════════════════════════════════════════════════════════════
def hagedorn_safety_alert(gamma: float) -> dict:
    """§32.1 — Classify γ into safety zones (paper 2 §4.2 finding F12).

    Empirical n=25 panel: 36% of LLMs operate at γ ≥ 0.95 (Hagedorn-zone risk).
    Models at γ ≥ 1.0 cannot serve long context without NTK extension.
    """
    if gamma is None or not isinstance(gamma, (int, float)):
        return {"level": "unknown", "color": "gray", "message": "no γ available"}
    if gamma >= 1.0:
        return {
            "level": "critical",
            "color": "red",
            "label": "🔴 HAGEDORN ZONE",
            "message": ("γ ≥ 1.0: attention concentrates locally. Long-context "
                        "retrieval will FAIL without NTK extension (α_opt > 1)."),
            "fraction_of_panel": "36% of n=25 LLMs are in this zone",
        }
    if gamma >= 0.95:
        return {
            "level": "warning",
            "color": "orange",
            "label": "🟠 HAGEDORN BOUNDARY",
            "message": ("γ ≥ 0.95: at the edge. Long context above T_train risky. "
                        "Run X-2 long-context viability before deploying."),
            "fraction_of_panel": "~24% of n=25 LLMs cluster here",
        }
    if gamma >= 0.65:
        return {
            "level": "ok",
            "color": "green",
            "label": "🟢 PHASE A NORMAL",
            "message": ("γ ∈ [0.65, 0.95]: long-context OK. KV compression via "
                        "D_f window applicable in [0.65, 0.85]."),
            "fraction_of_panel": "~40% of n=25 LLMs",
        }
    if gamma > 0:
        return {
            "level": "info",
            "color": "blue",
            "label": "🔵 PHASE A WIDE-FIELD",
            "message": ("γ < 0.65: very long-range attention. Model may be over-"
                        "trained on long context, or pre-IH (small model)."),
            "fraction_of_panel": "~12% of n=25 LLMs (mostly small or anomalous)",
        }
    return {
        "level": "catastrophic",
        "color": "darkred",
        "label": "❌ NEGATIVE γ",
        "message": "Negative γ means T_eval >> θ. Bad operating point. Use lower T or higher θ.",
        "fraction_of_panel": "0% of n=25 (pathological)",
    }


# ════════════════════════════════════════════════════════════════════════════
# §33 — Sesion 31 (2026-04-30) findings — added to TAF v0.4
# Architectural concentration law, PDI, 4-bit R²-direction rule, critical exponents
# ════════════════════════════════════════════════════════════════════════════

def architectural_concentration_predict(gamma_pade_val: float, n_kv: int) -> dict:
    """§33.1 — Architectural concentration law (paper 2 NEW, sesion 31).

    γ_text ≈ γ_Padé − 0.012·n_kv
    R² = 0.30 cross-panel (n=22) vs Padé alone R²=0.02.

    IMPORTANT: This is a CORRELATIONAL law, NOT per-model predictor.
    Mean per-model |err| = 0.27, WORSE than Padé alone (0.24).
    Use as CROSS-PANEL diagnostic, not individual prediction.
    """
    k_arch = 0.012  # panel-fit coefficient (n=22), not derived from first principles
    gamma_predicted = gamma_pade_val - k_arch * n_kv
    return {
        "gamma_pade": gamma_pade_val,
        "n_kv": n_kv,
        "k_arch": k_arch,
        "gamma_text_predicted": gamma_predicted,
        "caveat": "Correlational, not per-model predictor (R²=0.30, mean err 0.27)",
        "interpretation": (
            "GQA aggressive (low n_kv) → γ pushed up toward Hagedorn. "
            "MHA full (n_kv=32) → γ drops below Padé (sink-prone)."
        ),
    }


def padé_deviation_index(theta: float, gamma_obs: float, T_eval: int) -> dict:
    """§33.2 — PDI Padé Deviation Index (paper 2 NEW, sesion 31).

    PDI = d_horizon_obs / T_eval = θ(1−γ_obs)√2 / ((1+γ_obs)·T_eval)

    Identity (D-NEW-1): PDI = 1 ⟺ γ_obs = γ_Padé(θ, T_eval)
    Diagnostic value:
      PDI ≈ 1: canonical (model matches Padé)
      PDI > 1.5: γ_obs < γ_Padé (sink-dominated, code/instruct shift)
      PDI < 0.5: γ_obs > γ_Padé but < 1 (over-concentrated)
      PDI < 0: γ_obs > 1 (Phase B, formula sign-flips)

    Equivalent log scale: log(PDI) + ΔH_Cardy = 0 (D-DEEP-15).
    """
    if gamma_obs == -1.0:
        return {"PDI": float('inf'), "regime": "singular"}
    pdi = theta * (1 - gamma_obs) * math.sqrt(2) / ((1 + gamma_obs) * T_eval)
    if pdi < 0:
        regime = "Phase B (γ>1, formula sign-flip)"
        traffic = "🔴 RED — Phase B, NTK extension required"
    elif 0.5 <= pdi <= 1.5:
        regime = "canonical (γ_obs ≈ γ_Padé)"
        traffic = "🟢 GREEN — model matches Padé prediction"
    elif pdi > 1.5:
        regime = "γ_obs << γ_Padé (sink-dominated or extreme alignment)"
        traffic = "🟠 ORANGE — large positive deviation"
    else:  # 0 < pdi < 0.5
        regime = "γ_obs > γ_Padé (over-concentrated in Phase A)"
        traffic = "🟡 YELLOW — moderate deviation"
    return {
        "PDI": pdi,
        "log_PDI": math.log(pdi) if pdi > 0 else None,
        "regime": regime,
        "traffic_light": traffic,
        "identity": "log(PDI) + ΔH_Cardy = 0 (use either, log-inverse)",
    }


def precision_shift_predict_4bit(gamma_bf16: float, R2_bf16: float, is_GQA: bool) -> dict:
    """§33.3 — 4-bit precision shift direction predictor (paper 2 NEW, sesion 31).

    Empirical n=5 rule: bf16 R² of power-law fit predicts 4-bit shift direction.

    For MHA models:
      R²(bf16) < 0.9 (sink-dominated): 4-bit shifts γ UP toward γ_Padé
      R²(bf16) > 0.99 (clean): 4-bit shifts γ DOWN (introduces noise)
      0.95 ≤ R² ≤ 0.99: stable (~no shift)

    For GQA models: precision-robust regardless (|Δγ| < 0.05).
    """
    if is_GQA:
        return {
            "predicted_shift_direction": "stable",
            "expected_magnitude": "|Δγ| < 0.05",
            "reason": "GQA KV-sharing distributes attention; little long-tail to perturb",
            "recommendation": "Either bf16 or 4-bit OK for deployment",
        }
    # MHA case — depends on R²
    if R2_bf16 < 0.9:
        direction = "UP"
        magnitude = "+0.3 to +0.8 expected"
        reason = "Sink-dominated bf16: 4-bit truncates long-tail, reveals Padé prediction"
    elif R2_bf16 > 0.99:
        direction = "DOWN"
        magnitude = "−0.2 to −0.4 expected"
        reason = "Clean bf16: 4-bit further sparsifies, introduces non-monotonicity"
    else:
        direction = "stable"
        magnitude = "|Δγ| < 0.05"
        reason = "Borderline R², 4-bit minimal effect"
    return {
        "predicted_shift_direction": direction,
        "expected_magnitude": magnitude,
        "reason": reason,
        "evidence": "n=5 paired measurements (DeepSeek/Pythia-1B/Pythia-2.8B/Llama-3/Qwen-7B-Inst)",
        "caveat": "R²-direction rule is empirical, not formally derived",
    }


def critical_exponents_bundle(gamma: float) -> dict:
    """§33.4 — Critical exponents bundle (paper 2 NEW, sesion 31 + GAME-O).

    Returns ν_c (correlation length), β_c (order parameter), η_c (anomalous dim),
    α_C (specific heat), γ_susc (susceptibility) as functions of γ.

    Hyperscaling consistent (Rushbrooke + Josephson, d=1).

    NEW IDENTITY (GAME-P recursive):
      γ_susc(γ) = 1/(1−γ) + 2(1−γ) ≥ 2√2 (AM-GM bound)
      Minimum at γ = 1 − 1/√2 ≈ 0.293
      Equals c_central=3 at γ=0 AND γ=1/2
    """
    if gamma >= 1:
        return {"regime": "Hagedorn or beyond", "exponents": "diverge"}
    nu_c = 1 / (1 - gamma)
    beta_c = gamma - 1
    eta_c = gamma - 1  # CORRECTED from paper 1's η=2γ (Lévy mapping consistent with hyperscaling)
    alpha_C = 2 - 1 / (1 - gamma)
    gamma_susc = 1 / (1 - gamma) + 2 * (1 - gamma)

    # AM-GM bound check
    gamma_min = 1 - 1 / math.sqrt(2)
    gamma_susc_min = 2 * math.sqrt(2)

    return {
        "nu_correlation_length": nu_c,
        "beta_order_param": beta_c,
        "eta_anomalous_dim": eta_c,
        "eta_note": "η_c = γ−1 (Lévy-derived, hyperscaling-consistent). Paper 1 claim η=2γ is INCORRECT.",
        "alpha_specific_heat": alpha_C,
        "gamma_susceptibility": gamma_susc,
        "c_central_at_gamma_0": 3,  # γ_susc(γ=0) = 3 = c_central
        "AM_GM_bound": {
            "min_gamma_susc": gamma_susc_min,
            "min_at_gamma": gamma_min,
            "interpretation": (
                f"γ_susc has UNIVERSAL minimum {gamma_susc_min:.3f} at γ = {gamma_min:.4f} "
                "(AM-GM with ab=2 product constant)"
            ),
        },
        "hyperscaling_check": {
            "Rushbrooke (α + 2β + γ_susc = 2)": alpha_C + 2 * beta_c + gamma_susc,
            "expected": 2,
        },
        "warning_paper1_eta": "Paper 1's η_c = 2γ is INCORRECT. Use η_c = γ-1 (this function).",
    }


def verify_algebraic_consistency(gamma: float, tol: float = 1e-9) -> dict:
    """§34 v0.5 — Machine-verified framework consistency check.

    Verifies the 12 D-SAGE algebraic identities discovered by Sage Groebner basis
    and formally proven in Lean Mathlib4 (sesion 32, 2026-05-01).

    Each identity is a sanity check: given measured γ, the TAF critical exponents
    must satisfy these relations. Failures indicate γ measurement artifacts
    (bf16 outliers, quantization issues, Phase B regime).

    References:
      - sage_recursive_sweep_results.json (Sage Groebner verification)
      - lean_taf/taf/Taf/Identities.lean (Lean Mathlib4 machine-proof)
      - paper 2 appendix A.4 "Formal verification"
    """
    if gamma >= 1 or gamma <= 0:
        return {
            "status": "out_of_phase_A",
            "phase_A_range": "(0, 1)",
            "input_gamma": gamma,
            "message": "Verification requires γ ∈ (0, 1) Phase A regime."
        }

    nu = 1 / (1 - gamma)
    beta = gamma - 1
    eta = gamma - 1  # CORRECTED η=γ-1 (NOT paper 1's 2γ)
    alpha = 2 - 1 / (1 - gamma)
    chi = 1 / (1 - gamma)
    gamma_chi = 1 / (1 - gamma) + 2 * (1 - gamma)

    checks = {
        "D-SAGE-1": {
            "claim": "2η² + η·γ_χ + 1 = 0",
            "value": 2 * eta**2 + eta * gamma_chi + 1,
            "expected": 0.0,
            "passes": abs(2 * eta**2 + eta * gamma_chi + 1) < tol,
        },
        "D-SAGE-2": {
            "claim": "β·χ = -1",
            "value": beta * chi,
            "expected": -1.0,
            "passes": abs(beta * chi - (-1)) < tol,
        },
        "D-SAGE-4": {
            "claim": "α + χ = 2",
            "value": alpha + chi,
            "expected": 2.0,
            "passes": abs(alpha + chi - 2) < tol,
        },
        "D-SAGE-5": {
            "claim": "α + γ_χ = 2(2-γ)",
            "value": alpha + gamma_chi,
            "expected": 2 * (2 - gamma),
            "passes": abs(alpha + gamma_chi - 2 * (2 - gamma)) < tol,
        },
        "D-SAGE-6": {
            "claim": "β·γ_χ = -2γ²+4γ-3",
            "value": beta * gamma_chi,
            "expected": -2 * gamma**2 + 4 * gamma - 3,
            "passes": abs(beta * gamma_chi - (-2 * gamma**2 + 4 * gamma - 3)) < tol,
        },
        "Rushbrooke_tautology": {
            "claim": "2β + γ_χ - ν·d = 0 (d=1)",
            "value": 2 * beta + gamma_chi - nu,
            "expected": 0.0,
            "passes": abs(2 * beta + gamma_chi - nu) < tol,
        },
        "Josephson_tautology": {
            "claim": "2 - α - ν·d = 0 (d=1)",
            "value": 2 - alpha - nu,
            "expected": 0.0,
            "passes": abs(2 - alpha - nu) < tol,
        },
        "Fisher_independent": {
            "claim": "Fisher residual = γ(2γ-3)/(1-γ)  [NOT 0 generally]",
            "value": gamma_chi - (2 - eta) * nu,
            "expected_formula": gamma * (2 * gamma - 3) / (1 - gamma),
            "passes": abs((gamma_chi - (2 - eta) * nu) - gamma * (2 * gamma - 3) / (1 - gamma)) < tol,
        },
        "eta_2gamma_REFUTED": {
            "claim": "Paper 1's η=2γ residual > 0 in Phase A",
            "value": 2 * (2 * gamma)**2 + 2 * gamma * gamma_chi + 1,
            "expected": "positive (refutes η=2γ)",
            "passes": (2 * (2 * gamma)**2 + 2 * gamma * gamma_chi + 1) > 0,
        },
        "D-14_nu_imprint": {
            "claim": "ν_imprint · 2π = -1",
            "value": (-1 / (2 * math.pi)) * 2 * math.pi,
            "expected": -1.0,
            "passes": abs((-1 / (2 * math.pi)) * 2 * math.pi - (-1)) < tol,
        },
        "D-SAGE-7": {
            "claim": "c · |ν_imprint| · 2π = 3",
            "value": 3 * (1 / (2 * math.pi)) * 2 * math.pi,
            "expected": 3.0,
            "passes": abs(3 * (1 / (2 * math.pi)) * 2 * math.pi - 3) < tol,
        },
        "nu_beta_id": {
            "claim": "ν · β = -1",
            "value": nu * beta,
            "expected": -1.0,
            "passes": abs(nu * beta - (-1)) < tol,
        },
    }

    n_total = len(checks)
    n_passed = sum(1 for c in checks.values() if c["passes"])
    all_consistent = n_passed == n_total

    return {
        "input_gamma": gamma,
        "phase": "A (γ ∈ (0,1))",
        "n_checks_total": n_total,
        "n_checks_passed": n_passed,
        "all_consistent": all_consistent,
        "framework_verified_by": "Sage Groebner basis (PolynomialRing(ℚ)) + Lean Mathlib4 (dependent type theory)",
        "checks": checks,
        "interpretation": (
            f"All {n_total}/{n_total} D-SAGE identities consistent ✓ "
            "(framework algebraic structure intact)"
            if all_consistent
            else f"INCONSISTENCY: {n_passed}/{n_total} pass. Possible bf16 outlier, "
                 "quantization artifact, or measurement noise."
        ),
        "references": [
            "Sage script: sage_recursive_sweep_2026-04-30.sage",
            "Lean script: lean_taf/taf/Taf/Identities.lean",
            "Paper 2 appendix A.4: appendix_formal_verification_2026-05-01.md",
        ],
    }


def bimodal_phase_class(gamma: float) -> str:
    """§32.2 — Bimodal classifier (paper 2 §4 finding F11).

    γ_text panel n=25 shows 2 density peaks (~0.75 + ~1.0) with gap 0.85-0.95.
    Hartigan dip test pending (paper 2 Tier-A E3).
    """
    if gamma is None:
        return "unknown"
    if gamma < 0:
        return "catastrophic"
    if gamma < 0.85:
        return "Phase A (long-range)"
    if gamma < 0.95:
        return "boundary (gap zone)"
    if gamma < 1.0:
        return "Hagedorn boundary"
    return "Hagedorn zone"


def nearest_famous_constant(gamma: float, max_results: int = 3,
                            tolerance: float = 0.05) -> list:
    """§32.3 — Convenience wrapper: find named constants near γ.

    Wraps famous_constant_proximity(); always returns a list (possibly empty).
    Useful for displaying "your γ is close to <constant>" in UI.
    """
    if gamma is None:
        return []
    out = famous_constant_proximity(gamma, tolerance=tolerance)
    return out.get("hits", [])[:max_results]


# ════════════════════════════════════════════════════════════════════════════
# Recipe registry
# ════════════════════════════════════════════════════════════════════════════
RECIPES = {
    "X-1": {
        "name": "Custom Training vs API",
        "description": "Should I train a custom model or use a frontier API for my domain task?",
        "fn": run_recipe_x1,
        "params": ["N_params", "D_tokens", "gpu", "n_gpus", "mfu",
                   "api_model", "monthly_tokens_M"],
        "category": "build-vs-buy",
        "uses_sections": ["§17", "§19", "§20", "§24"],
    },
    "X-2": {
        "name": "Long Context Viability",
        "description": "Will model M serve length L doing Needle-in-a-Haystack retrieval?",
        "fn": run_recipe_x2,
        "params": ["theta", "T_train", "T_eval", "n_attention_heads", "n_kv_heads",
                   "d_head", "n_layers", "n_params", "has_SWA"],
        "category": "long-context",
        "uses_sections": ["§26", "§19"],
    },
    "X-3": {
        "name": "Budget Pre-flight",
        "description": "Given $ budget, what model is feasible to train?",
        "fn": run_recipe_x3,
        "params": ["USD_budget", "gpu", "mfu", "n_gpus"],
        "category": "training-budget",
        "uses_sections": ["§17", "§20"],
    },
    "X-5": {
        "name": "Hardware Selection",
        "description": "Which GPU should I use to serve my model at target throughput?",
        "fn": run_recipe_x5,
        "params": ["N_params", "T_eval", "n_layers", "n_kv_heads", "d_head",
                   "bytes_per_weight", "target_tokens_per_day", "concurrent_users"],
        "category": "serving",
        "uses_sections": ["§19", "§20"],
    },
    "X-19": {
        "name": "KV Compression Decision",
        "description": "Should I use soft decay, D_f cutoff, or literature methods to compress KV?",
        "fn": run_recipe_x19,
        "params": ["theta", "T_train", "T_eval", "n_attention_heads", "n_kv_heads",
                   "d_head", "n_layers", "n_params", "has_SWA"],
        "category": "kv-compression",
        "uses_sections": ["§26", "§19"],
    },
    "X-21": {
        "name": "Imprint Purity Diagnostic ✗ RETIRED",
        "description": "RETIRED (2026-08) — rested on the learned-imprint slope ν=−1/(2π), which Part II states is 'unconstrained by the current data' (bootstrap 95% CI [−0.260, −0.008]); the '0.3% match' framing was withdrawn there too. Consistent but not strongly identified. Kept callable for reproducibility only; do not act on its verdict.",
        "fn": run_recipe_x21,
        "params": ["theta", "T_train", "n_attention_heads", "n_kv_heads",
                   "d_head", "n_layers", "n_params", "T_eval", "gamma_random_obs"],
        "category": "diagnostic",
        "status": "retired",
        "uses_sections": ["§26", "§28"],
    },
    "X-22": {
        "name": "Compute-Context Invariant",
        "description": "Does γ × log(N²·D) lie in the panel band 51.2 ± 16.8? Detects training/scaling anomalies.",
        "fn": run_recipe_x22,
        "params": ["theta", "T_train", "n_params", "gamma_obs", "D_tokens", "T_eval"],
        "category": "diagnostic",
        "uses_sections": ["§26", "§29"],
    },
    "X-23": {
        "name": "IH-Phase Detector",
        "description": "Is this model pre- or post-induction-head? Cheap probe via sign(γ_text − γ_random).",
        "fn": run_recipe_x23,
        "params": ["n_params", "gamma_text", "gamma_random"],
        "category": "diagnostic",
        "uses_sections": ["§30"],
    },
}


def list_recipes() -> str:
    """Return JSON of all recipes for UI dropdown."""
    return json.dumps([
        {"id": rid, "name": r["name"], "description": r["description"],
         "category": r["category"], "params": r["params"],
         "uses_sections": r["uses_sections"]}
        for rid, r in RECIPES.items()
    ])


def run_recipe(recipe_id: str, **params) -> dict:
    """Dispatcher — execute recipe by id with given params."""
    r = RECIPES.get(recipe_id)
    if r is None:
        return {"error": f"unknown recipe '{recipe_id}'",
                "available": list(RECIPES.keys())}
    return r["fn"](**params)


# ════════════════════════════════════════════════════════════════════════════
# Known model presets
# ════════════════════════════════════════════════════════════════════════════
PRESETS = {
    # Reviewed 2026-10-24. Geometry: pinned configs in data/model_catalog.json.
    # T_train is the model-card native reference (32768), not config max (40960).
    # Parameter counts are rounded model-card values, not stored tensor counts.
    "Qwen/Qwen3-0.6B": {
        "theta": 1000000, "T_train": 32768,
        "n_attention_heads": 16, "n_kv_heads": 8,
        "d_head": 128, "n_layers": 28, "n_params": 0.6e9, "has_SWA": False,
    },
    "Qwen/Qwen3-8B": {
        "theta": 1000000, "T_train": 32768,
        "n_attention_heads": 32, "n_kv_heads": 8,
        "d_head": 128, "n_layers": 36, "n_params": 8.2e9, "has_SWA": False,
    },
    "EleutherAI/pythia-2.8b": {
        "theta": 10000, "T_train": 2048,
        "n_attention_heads": 32, "n_kv_heads": 32,
        "d_head": 80, "n_layers": 32, "n_params": 2.8e9, "has_SWA": False,
    },
    "EleutherAI/pythia-1b": {
        "theta": 10000, "T_train": 2048,
        "n_attention_heads": 8, "n_kv_heads": 8,
        "d_head": 256, "n_layers": 16, "n_params": 1e9, "has_SWA": False,
    },
    "EleutherAI/pythia-1.4b": {
        "theta": 10000, "T_train": 2048,
        "n_attention_heads": 16, "n_kv_heads": 16,
        "d_head": 128, "n_layers": 24, "n_params": 1.4e9, "has_SWA": False,
    },
    "meta-llama/Meta-Llama-3-8B": {
        "theta": 500000, "T_train": 8192,
        "n_attention_heads": 32, "n_kv_heads": 8,
        "d_head": 128, "n_layers": 32, "n_params": 8e9, "has_SWA": False,
    },
    "meta-llama/Llama-3.2-1B": {
        "theta": 500000, "T_train": 131072,
        "n_attention_heads": 32, "n_kv_heads": 8,
        "d_head": 64, "n_layers": 16, "n_params": 1.2e9, "has_SWA": False,
    },
    "meta-llama/Llama-3.3-70B-Instruct": {
        "theta": 500000, "T_train": 131072,
        "n_attention_heads": 64, "n_kv_heads": 8,
        "d_head": 128, "n_layers": 80, "n_params": 70e9, "has_SWA": False,
    },
    "mistralai/Mistral-7B-v0.1": {
        "theta": 10000, "T_train": 8192,
        "n_attention_heads": 32, "n_kv_heads": 8,
        "d_head": 128, "n_layers": 32, "n_params": 7e9, "has_SWA": True,
    },
    "Qwen/Qwen2.5-7B": {
        "theta": 1000000, "T_train": 32768,
        "n_attention_heads": 28, "n_kv_heads": 4,
        "d_head": 128, "n_layers": 28, "n_params": 7.6e9, "has_SWA": False,
    },
    "Qwen/Qwen2.5-1.5B": {
        "theta": 1000000, "T_train": 32768,
        "n_attention_heads": 12, "n_kv_heads": 2,
        "d_head": 128, "n_layers": 28, "n_params": 1.5e9, "has_SWA": False,
    },
    "google/gemma-2-9b-it": {
        "theta": 10000, "T_train": 8192,
        "n_attention_heads": 16, "n_kv_heads": 8,
        "d_head": 256, "n_layers": 42, "n_params": 9e9, "has_SWA": True,
    },
    "microsoft/phi-3-mini-4k-instruct": {
        "theta": 10000, "T_train": 4096,
        "n_attention_heads": 32, "n_kv_heads": 32,
        "d_head": 96, "n_layers": 32, "n_params": 3.8e9, "has_SWA": True,
    },
}


def list_presets() -> str:
    return json.dumps([
        {"id": k, "label": k.split("/")[-1],
         "theta": v["theta"], "T_train": v["T_train"]}
        for k, v in PRESETS.items()
    ])


def get_preset(model_id: str) -> dict:
    return PRESETS.get(model_id, {})


# ════════════════════════════════════════════════════════════════════════════
# MODEL PROFILE — runs all 5 recipes with sensible defaults
# ════════════════════════════════════════════════════════════════════════════
def profile_model(theta, T_train, n_attention_heads, n_kv_heads, d_head,
                  n_layers, n_params, has_SWA=False,
                  T_eval=None, USD_budget=5000, target_tokens_per_day=10_000_000,
                  api_model="GPT-4o", monthly_tokens_M=10.0,
                  **_unused) -> dict:
    """Run all 5 recipes against the same model and assemble a TAF Card profile.

    This produces the canonical paper §sec:gamma_decomposition view: one model,
    all viability dimensions, with κey numbers + falsification status per dimension.
    """
    if T_eval is None:
        T_eval = T_train  # default eval at training context

    has_GQA = n_kv_heads < n_attention_heads
    g_pade = gamma_pade(theta, T_eval)
    decomp = gamma_decompose(g_pade, has_GQA, has_SWA, n_params)
    g_corr = decomp["gamma_corrected"]
    dh = d_horizon(theta, g_corr)
    chi = chi_susceptibility(g_corr) if 0 < g_corr < 2 else None

    # Factual configuration labels only; no size-derived circuit labels.
    arch_class = ("GQA" if has_GQA else "MHA") + (" + configured SWA" if has_SWA else "")

    common_params = {
        "theta": theta, "T_train": T_train, "T_eval": T_eval,
        "n_attention_heads": n_attention_heads, "n_kv_heads": n_kv_heads,
        "d_head": d_head, "n_layers": n_layers, "n_params": n_params,
        "has_SWA": has_SWA,
    }

    # Run all 5 recipes
    results = {}
    try:
        results["X-2"] = run_recipe_x2(**common_params)
    except Exception as e:
        results["X-2"] = {"error": str(e)}

    try:
        results["X-19"] = run_recipe_x19(**common_params)
    except Exception as e:
        results["X-19"] = {"error": str(e)}

    try:
        results["X-1"] = run_recipe_x1(N_params=n_params, gpu="H100 SXM",
                                        n_gpus=8, mfu=0.45,
                                        api_model=api_model, monthly_tokens_M=monthly_tokens_M)
    except Exception as e:
        results["X-1"] = {"error": str(e)}

    try:
        results["X-3"] = run_recipe_x3(USD_budget=USD_budget, gpu="H100 SXM",
                                        mfu=0.45, n_gpus=1)
    except Exception as e:
        results["X-3"] = {"error": str(e)}

    try:
        results["X-5"] = run_recipe_x5(N_params=n_params, T_eval=T_eval,
                                        n_layers=n_layers, n_kv_heads=n_kv_heads,
                                        d_head=d_head, bytes_per_weight=2.0,
                                        target_tokens_per_day=target_tokens_per_day,
                                        concurrent_users=1)
    except Exception as e:
        results["X-5"] = {"error": str(e)}

    falsifications = [
        {"id": "F1", "claim": "Padé accuracy below 5%", "status": "withdrawn: unreconstructed selection"},
        {"id": "F2", "claim": "Inverse-coordinate NIAH ceiling", "status": "withdrawn: no validated capacity mapping"},
        {"id": "F17", "claim": "Universal soft-decay boundary", "status": "unvalidated: three extrapolation cases"},
    ]

    return {
        "model_summary": {
            "architecture_class": arch_class,
            "n_params": n_params,
            "T_train": T_train,
            "T_eval": T_eval,
            "rope_theta": theta,
            "has_GQA": has_GQA,
            "has_SWA": has_SWA,
        },
        "key_numbers": {
            "gamma_pade": g_pade,
            "gamma_decomposed": g_corr,
            "decomposition_breakdown": decomp,
            "d_horizon": dh,
            "L_NIAH_ceiling": None,
            "chi_susceptibility": None,
            "kv_memory_per_request_GB": kv_cache_memory(n_layers, n_kv_heads,
                                                        d_head, T_eval)["GB"],
            "gamma_random_predicted": None,
            "compute_invariant_K": None,
            "K_in_distribution": None,
        },
        "v04_diagnostics": {},
        "formula_contract": "finite-family-v2-20261118",
        "gamma_observed": None,
        "recipes": {
            rid: {
                "verdict": r.get("verdict", "ERROR"),
                "reason": r.get("reason", r.get("error", "")),
                "mitigation": r.get("mitigation", ""),
                "name": r.get("recipe_name", ""),
                # i18n passthrough — without these the UI cannot localize tiles
                "reason_code": r.get("reason_code"),
                "reason_params": r.get("reason_params"),
                "mit_code": r.get("mit_code"),
                "mit_params": r.get("mit_params"),
            }
            for rid, r in results.items()
        },
        "falsification_status": falsifications,
    }


# ════════════════════════════════════════════════════════════════════════════
# COMPARE — same recipe across multiple models
# ════════════════════════════════════════════════════════════════════════════
def compare_models(model_specs: list, recipe_id: str = "X-2",
                   shared_params: dict = None) -> dict:
    """Run one recipe across multiple models and assemble side-by-side comparison.

    Args:
        model_specs: list of dicts each with model architectural params + a "label" key
        recipe_id: which recipe to run (X-1, X-2, X-3, X-5, X-19)
        shared_params: extra params to pass to recipe (T_eval, etc.)
    """
    shared_params = shared_params or {}
    rows = []
    for spec in model_specs:
        label = spec.pop("label", spec.get("model_id", "model"))
        params = {**spec, **shared_params}
        try:
            result = run_recipe(recipe_id, **params)
            rows.append({
                "label": label,
                "verdict": result.get("verdict", "ERROR"),
                "reason": result.get("reason", ""),
                "reason_code": result.get("reason_code"),
                "reason_params": result.get("reason_params"),
                "key_numbers": _extract_key_numbers(result),
            })
        except Exception as e:
            rows.append({"label": label, "verdict": "ERROR", "reason": str(e), "key_numbers": {}})
    return {
        "recipe_id": recipe_id,
        "recipe_name": RECIPES.get(recipe_id, {}).get("name", recipe_id),
        "shared_params": shared_params,
        "rows": rows,
    }


def _extract_key_numbers(result: dict) -> dict:
    """Pull the numerically interesting fields from a recipe result for compare table."""
    nums = {}
    for step in result.get("chain", []):
        name = step.get("name", "")
        res = step.get("result")
        if res is None:
            continue
        if isinstance(res, (int, float)):
            nums[name] = res
        elif isinstance(res, dict) and "GB" in res:
            nums[name] = res["GB"]
    return nums


# Smoke test
if __name__ == "__main__":
    print("─── X-2 Llama-3-8B @ 32K ───")
    r = run_recipe("X-2", theta=500_000, T_train=8192, T_eval=32_000,
                   n_attention_heads=32, n_kv_heads=8, d_head=128,
                   n_layers=32, n_params=8e9, has_SWA=False)
    print(f"Verdict: {r['verdict']} — {r['reason']}\n")

    print("─── X-1 Llama-3-8B vs GPT-4o (10M tok/mo) ───")
    r = run_recipe("X-1", N_params=8e9, monthly_tokens_M=10.0, api_model="GPT-4o")
    print(f"Verdict: {r['verdict']} — {r['reason']}\n")

    print("─── X-3 budget $5K ───")
    r = run_recipe("X-3", USD_budget=5000.0, gpu="H100 SXM", n_gpus=1)
    print(f"Verdict: {r['verdict']} — {r['reason']}\n")

    print("─── X-5 serve Llama-3-8B at 4K ───")
    r = run_recipe("X-5", N_params=8e9, T_eval=4096, n_layers=32, n_kv_heads=8, d_head=128,
                   target_tokens_per_day=10e6, concurrent_users=1)
    print(f"Verdict: {r['verdict']} — {r['reason']}\n")

    print("─── X-19 KV compression for Llama-3-8B ───")
    r = run_recipe("X-19", theta=500_000, T_train=8192, T_eval=8192,
                   n_attention_heads=32, n_kv_heads=8, d_head=128,
                   n_layers=32, n_params=8e9)
    print(f"Verdict: {r['verdict']} — {r['reason']}\n")