/tools/dashboard.py · raw
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
#!/usr/bin/env python3
"""tools/dashboard.py: the site's Home page and its Machines table (reports/site-redesign.md §3.2, §3.3;
tools/README-dashboard.md), plus every record they are built from.

    python3 -B tools/dashboard.py                 # the whole site (= tools/site.py, sitekit.build_all): any missing
                                                  #   thumbnails (6 niced workers), every machine page, Home
                                                  #   (dashboard/index.html), Machines (machines.html), Submissions,
                                                  #   Reports, Decisions, data.json, kills.json, the root index.html
    python3 -B tools/dashboard.py --no-thumbs     # pages only (missing thumbnails show a placeholder)
    python3 -B tools/dashboard.py --force-thumbs  # redraw every thumbnail
    python3 -B tools/dashboard.py --no-cards-index  # everything except the machine pages
    python3 -B tools/dashboard.py --screens       # then screenshots of every page into dashboard/screens/
    python3 -B tools/pr_sync.py                   # before it, when a PR may have moved (gh pr view, read-only)
    python3 -B tools/test_dashboard.py            # tests
    -> /busy-beaver/dashboard/   (and /busy-beaver/ redirects there)

Home (dashboard/index.html) says where things stand (one tile per bucket: accepted / submitted / claimed / active /
waiting / parked / cryptid, plus untouched), what needs Dennis (open decisions, calls and Checkpoint A answers, PRs
with comments, Discord texts to post, kills ready to submit, the Discord question drafts) and what changed recently
(kills, PR merges, status changes and calls of the last 4 days, the tail of reports/overnight-ledger.md). Machine
names link only to the machine page (machines/<tm>/index.html), never to raw files.

Machines (dashboard/machines.html) is one table of every machine folder, filterable by bucket and class and
searchable (JS; without it the whole table shows, grouped): one group per bucket, the kills grouped by family
(tools/killreview.py's family graph), each row with the standard picture, the name (sitekit.Names), state, what is
happening now, the proof checks, related machines, the last change and the flags; then, folded, the untouched
holdouts of the list as a grid.

The list is the current one, data/holdouts/BB6_holdouts_740.txt (LIST; line numbers on the pages are its lines).
Machines we have a machines/<tm>/ folder for that are not on it are still shown, in their bucket, marked "off the
list" with the reason (solved by our merged PR, or status.json 'holdouts_740', e.g. removed by equivalence, linked
to the equivalent machine when it is on the list) and their line in the previous list (PREV_LIST, "778 line n").
Kills are split by their upstream state (status.json 'pr' / 'pr_state', kept current by tools/pr_sync.py):
Accepted upstream (PR merged), Submitted, awaiting verification (PR open), Kill claimed (check_kill PASS here, no
PR yet). Every machine gets a bucket from the status files in machines/<tm>/ (recent file activity is only a
"working" badge), a bbchallenge.org Default-view thumbnail from the blank tape (dashboard/thumbs/<tm>.png, cached),
the sheet's class (or a labelled guess from the nearest classified machine), the sheet's simulation depth, its
equivalence-class size, the other holdouts with the same transition table from another start state, and flags
(Discord lists, our targeting pool rank, sheet status). Pages are static HTML in the shared site shell
(tools/sitekit.py: nav, theme, clock script). Stdlib only; it reuses tools/card.py's styles and status logic.
"""
from __future__ import annotations

import argparse
import datetime as _dt
import itertools
import json
import multiprocessing
import os
import re
import hashlib
import sys
import time
from collections import Counter
from pathlib import Path
from urllib.parse import quote

sys.dont_write_bytecode = True
TOOLS = Path(__file__).resolve().parent
if str(TOOLS) not in sys.path:
    sys.path.insert(0, str(TOOLS))
import card as C          # noqa: E402  (styles, escaping, status chips, the card's state logic)
import sitekit as S       # noqa: E402  (the site shell, nav, names, Repo)
import holdouts as H      # noqa: E402  (list + sheet parsing)

ROOT = TOOLS.parent
MACHINES = ROOT / "machines"
DATA = ROOT / "data"
LIST = DATA / "holdouts" / "BB6_holdouts_663.txt"          # current published list
PREV_LIST = DATA / "holdouts" / "BB6_holdouts_740.txt"     # historical labels and anchors
LEGACY_LIST = DATA / "holdouts" / "2026-10-07_778.txt"
RECONCILIATION = DATA / "holdouts" / "reconciliation-663.json"
EQV = DATA / "holdouts" / "2026-10-07_eqv_1590.txt"
TARGETING = ROOT / "reports" / "targeting.md"
LEDGER = ROOT / "reports" / "overnight-ledger.md"
OUT = ROOT / "dashboard"
SERVER = "http://localhost:8765"
DISCORD_LISTS = (  # key, file, chip text, tooltip
    ("ubrrba", DATA / "discord" / "2026-08-24_mxdys_ubrrba_86.txt", "UBRRBA",
     "on mxdys's UBRRBA_TODO list (Discord 2026-08-24): easy to accelerate with UBRRBA, block size 1-12"),
    ("long", DATA / "discord" / "2026-10-01_dyuan01_longitudinal_24.txt", "longit.",
     "on dyuan01's longitudinal-analysis filter (Discord 2026-10-01)"),
)

# Thumbnails: the bbchallenge.org Default view exactly as the site draws it (tools/diagram.py, pixel-identical).
# The 400x500 source is shown at 144x180 / 128x160 (about 1/3), so the label gives ranges, not pixel ratios.
THUMB = {"view": "site_default_canvas", "steps": 10_000, "width": 400, "ox": 0.5, "canvas": [400, 500], "v": 1}
THUMB_LABEL = {
    "style": "bbchallenge-default",
    "start": "blank",
    "rows": "steps 0 → 10,000, top to bottom",
    "window": "cells −200..199, left to right",
    "legend": "white = 1, black = 0 or unvisited",
}
THUMB_SCALE = ("about 1/3 of the site's size, so the site's red/green head marks are too small to see; click a "
               "picture to open the machine page (bbchallenge.org for a holdout with no folder)")
THUMB_TIP = ("bbchallenge.org Default view · start blank · steps 0 → 10,000 top to bottom · cells −200..199 left "
             "to right · white = 1, black = 0 · about 1/3 scale")
THUMB_JOBS = 6            # at most 6 parallel, niced processes (resource rule)
LIVE_MIN = 30             # files changed in machines/<tm>/ within this many minutes = an agent is on it now (badge)
STALE_MIN = 15            # the page says so when it was built longer ago than this (JS, viewer's clock)
GUESS_MAX = 2             # a class guess needs a classified machine at most this many transitions away
WORK_SKIP = {"card.html", "index.html", "kill.html", "review.html", "compare.html"}     # renders, not work
CLASS_FIX = {"Chaotic Fractral Type 1": "Chaotic Fractal Type 1",   # the Classifications tab's header typo
             "Chaotic Fractral Others": "Chaotic Fractal Others"}
# Known sheet errors (STATUS.md): the chip is shown struck through, with the reason.
SHEET_OVERRIDE = {
    "1RB1LC_0RC0RB_1LD0LA_1LE---_1LF1RA_1LA1LC":
        "misattributed (STATUS.md): the Results tab's NONHALT / SOCSSv5.v note belongs to its sibling "
        "…_1LA1LA; this machine looks like a real open holdout",
}
KILL_LEDGER = "kills.json"   # in the output dir: the first check_kill PASS seen per kill, so kill numbers never move
REVIEW_GLOBS = ("review*.html", "compare*.html", "review*.md", "compare*.md")   # killed tiles link these

BUCKETS = (  # key, heading, header-tile name, icon, one-line meaning, short meaning (header tiles)
    ("accepted", "Kills claimed", "Kills claimed", "★",
     "our PR is merged into busycoq (status.json pr_state merged, tools/pr_sync.py); the list drops the machine",
     "PR merged into busycoq"),
    ("submitted", "PR submitted", "PR submitted", "↑",
     "check_kill PASS here; our PR is open upstream and posted on Discord, waiting for the maintainers to check it",
     "PR open · posted"),
    ("claimed", "Locally proved · unsubmitted", "Unsubmitted proofs", "!",
     "verified local blank-start proof, in no PR yet; packaging readiness is shown separately",
     "locally proved · not submitted"),
    ("active", "Open (in pipeline)", "Open (in pipeline)", "●", "mid-pipeline with no question for you (OPEN, "
     "CHECKPOINT_B, high-confidence Checkpoint A, or no status.json yet); the ● working now badge marks the ones an "
     "agent touched in the last 30 min", "mid-pipeline · ● = being worked on now"),
    ("waiting", "Waiting on you", "Waiting on you", "?", "proof work waits for your call or your Checkpoint A answers",
     "your call or Checkpoint A answers"),
    ("parked", "Parked (deferred)", "Parked (deferred)", "▲",
     "stuck, cryptid candidate or skipped, with no question for you", "stuck · cryptid · skipped"),
    ("untouched", "Untouched", "Untouched", "○", "on the list, no machines/<tm>/ folder yet",
     "no machines/<tm>/ folder yet"),
)
BUCKETS += (
    ("upstream_overlap", "Claimed by someone else", "Claimed by someone else", "!",
     "our local proofs were unsubmitted when we identified these upstream results; submit verified proofs early",
     "our proof remained unsubmitted"),
    ("external_solved", "Claimed elsewhere · no local proof", "Claimed elsewhere", "↗",
     "mapped upstream blank-start proof; no local proof is counted", "upstream proof · no local proof"),
)
BUCKETS += (
    ("competing_pr", "Competing open PRs · local proofs", "Competing open PRs", "!",
     "another author submitted this exact machine; our local proof remains unsubmitted; acceptance and credit are pending",
     "local proof · another author’s PR open"),
    ("external_pending", "External PRs awaiting review", "External PRs awaiting review", "↗",
     "external blank-start proof submitted; not merged and not independently checked here",
     "external submission · awaiting review"),
)
BUCKET_KEYS = [b[0] for b in BUCKETS]
BUCKET_ICON = {b[0]: b[3] for b in BUCKETS}
KILL_BUCKETS = ("accepted", "submitted", "claimed")    # a kill's bucket is its upstream state (submission())
LOCAL_PROOF_BUCKETS = KILL_BUCKETS + ("upstream_overlap", "competing_pr")
SOLVED_BUCKETS = LOCAL_PROOF_BUCKETS + ("external_solved",)
PR_RX = re.compile(r"github\.com/[\w.-]+/[\w.-]+/pull/(\d+)")
PIPE = ("observe", "deepen", "proof.md", "Rocq")
KILLED = ("KILLED_NONHALT", "KILLED_HALT")
TM_RX = H._TM_IN_TEXT

esc = C.esc


# ----------------------------------------------------------------------------------------------- inputs

def load_list(path: Path) -> list[str]:
    pl = H.load_list(path)
    if not pl.ok:
        raise SystemExit(f"{path}: invalid holdout list")
    return pl.tms()


def load_eqv(path: Path) -> dict[str, list[str]]:
    """representative -> its equivalence class (the representative first). Blank-line separated groups."""
    groups: dict[str, list[str]] = {}
    if not path.is_file():
        return groups
    for block in re.split(r"\n\s*\n", path.read_text(encoding="utf-8").strip()):
        tms = [x.strip() for x in block.splitlines() if TM_RX.fullmatch(x.strip())]
        if tms:
            groups[tms[0]] = tms
    return groups


def load_tm_set(path: Path) -> set[str]:
    """Machines named at the start of a line (comment lines '#' skipped): the Discord list files."""
    out = set()
    if not path.is_file():
        return out
    for line in path.read_text(encoding="utf-8").splitlines():
        if line.lstrip().startswith("#"):
            continue
        m = TM_RX.match(line.strip())
        if m:
            out.add(m.group(0))
    return out


_RANK_ROW = re.compile(r"^\|\s*(R?\d+)\s*\|\s*`(" + TM_RX.pattern + r")`\s*\|", re.M)


def load_ranks(path: Path) -> dict[str, str]:
    """tm -> targeting-pool rank ('2', 'R4') from reports/targeting.md §4 (first table row wins)."""
    out: dict[str, str] = {}
    if path.is_file():
        for m in _RANK_ROW.finditer(path.read_text(encoding="utf-8")):
            out.setdefault(m.group(2), m.group(1))
    return out


def rank_label(r: str | None) -> str:
    return "" if not r else (r if r.startswith("R") else f"#{r}")


def rank_sort(r: str | None) -> int:
    if not r:
        return 10_000
    return 100 + int(r[1:]) if r.startswith("R") else int(r)


_LEDGER_ROW = re.compile(r"^\|\s*([^|]*?)\s*\|\s*([^|]*?)\s*\|\s*([^|]*?)\s*\|\s*([^|]*?)\s*\|\s*$", re.M)


def load_ledger(path: Path, by_rank: dict[str, str]) -> dict[str, dict]:
    """tm -> the last reports/overnight-ledger.md row whose machines column names it (#N / RN; 'many' names
    nobody): {time, action, workflow}."""
    out: dict[str, dict] = {}
    if not path.is_file():
        return out
    for m in _LEDGER_ROW.finditer(path.read_text(encoding="utf-8")):
        t, action, mach, wf = m.groups()
        if t in ("time", "---") or set(t) <= {"-"}:
            continue
        for tok in re.findall(r"(?<![\w-])(#\d+|R\d+)(?![\w-])", mach):
            tm = by_rank.get(tok.lstrip("#"))
            if tm:
                out[tm] = {"time": t, "action": action, "workflow": wf if wf not in ("-", "") else ""}
    return out


def sheet_data(tms: list[str], count_over: list[str] | None = None) -> dict:
    """Class, Results-tab status/notes and Direct Simulation depth per machine, plus the classified pool for
    guesses. Classes: the Classifications tab first, else the Results tab's Classification column. The pending
    counts are over `count_over` (default: tms), i.e. the list without the off-list machines shown."""
    tabs, _links = H.load_sheet()
    cls_tab = {k: CLASS_FIX.get(v.strip(), v.strip()) for k, v in H.sheet_classes(tabs).items() if v.strip()}
    res = H.results_status(tabs)
    pending = {13: set(), 14: set(), 15: set()}       # listed and not struck: not yet simulated to 1e(k)
    for tab in tabs:
        if tab.slug != "direct-simulation" or not tab.rows:
            continue
        for j, h in enumerate(tab.rows[0]):
            mexp = re.search(r"1e(\d+)", h)
            if not mexp or int(mexp.group(1)) not in pending:
                continue
            for ri, row in enumerate(tab.rows[1:], 2):
                c = row[j].strip() if j < len(row) else ""
                if TM_RX.fullmatch(c) and (ri, H._col_letter(j)) not in tab.struck:
                    pending[int(mexp.group(1))].add(c)
    classes, src = {}, {}
    for tm, r in res.items():
        c = CLASS_FIX.get(r["classification"].strip(), r["classification"].strip())
        if c:
            classes[tm], src[tm] = c, "Results tab"
    for tm, c in cls_tab.items():
        classes[tm], src[tm] = c, "Classifications tab"
    sim = {}
    for tm in tms:
        sim[tm] = 13 if tm in pending[14] else 14 if tm in pending[15] else 15
    return {"classes": classes, "class_src": src, "results": res, "sim": sim,
            "pending_counts": {k: len(v & set(count_over if count_over is not None else tms))
                               for k, v in pending.items()}}


# ----------------------------------------------------------------------------------------------- class guesses

def slots(tm: str) -> list[str]:
    return [g[i:i + 3] for g in tm.split("_") for i in (0, 3)]


def distance(a: str, b: str) -> int:
    """Differing transitions between two 6x2 machines, up to L/R mirroring (and state renaming, via
    holdouts.equiv_key). 12 = everything differs."""
    sa = slots(a)
    best = min(sum(x != y for x, y in zip(sa, slots(b))),
               sum(x != y for x, y in zip(sa, slots(H.mirror(b)))))
    ka, kb = H.equiv_key(a), H.equiv_key(b)
    if ka and kb:
        best = min(best, sum(x != y for x, y in zip(slots(ka), slots(kb))))
    return best


def guess_class(tm: str, pool: dict[str, str], exclude: set[str], max_d: int = GUESS_MAX) -> dict | None:
    """The class of the nearest classified machine (fewest differing transitions, <= max_d), never 'Unknown'.
    Ties: the most common class among the nearest; the tooltip lists them all."""
    best, near = max_d + 1, []
    for other, c in pool.items():
        if other in exclude or not c or c == "Unknown":
            continue
        d = distance(tm, other)
        if d > max_d:
            continue
        if d < best:
            best, near = d, [(other, c)]
        elif d == best:
            near.append((other, c))
    if not near:
        return None
    votes = Counter(c for _, c in near)
    cls, n = votes.most_common(1)[0]
    return {"class": cls, "dist": best, "near": [o for o, c in near if c == cls][0], "n_near": len(near),
            "votes": dict(votes), "agree": n}


# ----------------------------------------------------------------------------------------------- same table
#
# Two holdouts "share a table" when one is the other's transition table under some renaming of the 6 states
# (all 720) and optionally L/R mirroring, with the START STATE FREE: e.g. kill #24 is #3's table mirrored and
# started in #3's state D. The equivalence file keeps the start fixed, so it never links these. Canonical form:
# relabel the states in breadth-first order of first appearance from each possible root (x mirror), keep the
# smallest string; states unreachable from the root are tried in every order. Relabeling commutes with this, so
# two machines share a table iff their canonical strings are equal.

_ST = H.STATES


def relabel(tm: str, lab: dict[str, str]) -> str:
    """The machine with state s renamed lab[s] (rows re-sorted A..F). Halt entries stay as they are."""
    rows = tm.split("_")
    new = [""] * len(rows)
    for i, g in enumerate(rows):
        def t(x: str) -> str:
            return x[:2] + lab[x[2]] if x[2] in lab else x
        new[_ST.index(lab[_ST[i]])] = t(g[:3]) + t(g[3:])
    return "_".join(new)


def _bfs_forms(tm: str, root: str) -> list[tuple[str, dict[str, str]]]:
    rows = dict(zip(_ST, tm.split("_")))
    lab, order, i = {root: "A"}, [root], 0
    while i < len(order):
        s = order[i]
        i += 1
        for t in (rows[s][:3], rows[s][3:]):
            if t[2] in rows and t[2] not in lab:
                lab[t[2]] = _ST[len(lab)]
                order.append(t[2])
    out = []
    for rest in itertools.permutations([s for s in _ST if s not in lab]):
        full = dict(lab)
        for s in rest:
            full[s] = _ST[len(full)]
        out.append((relabel(tm, full), full))
    return out


def table_key(tm: str) -> tuple[str, list[tuple[bool, dict[str, str]]]]:
    """(canonical table string, every (mirrored?, renaming) that reaches it)."""
    best, how = None, []
    for m in (False, True):
        x = H.mirror(tm) if m else tm
        for root in _ST:
            for k, lab in _bfs_forms(x, root):
                if best is None or k < best:
                    best, how = k, [(m, lab)]
                elif k == best:
                    how.append((m, lab))
    return best, how


def table_start(x_how: list, ref_how: list) -> tuple[str, bool]:
    """Machine x as a start of ref's table: (the state of ref that x's start A is, mirrored?). With symmetries
    there can be several; the unmirrored, alphabetically first one is reported."""
    m_ref, lab_ref = ref_how[0]
    inv = {c: s for s, c in lab_ref.items()}
    return sorted({(inv[lab["A"]], m != m_ref) for m, lab in x_how}, key=lambda t: (t[1], t[0]))[0]


def table_groups(tms: list[str]) -> dict[str, list[dict]]:
    """tm -> the OTHER machines of the list with its table: [{tm, start, mirror}], where start is the other
    machine's start in THIS machine's state names. Machines alone with their table are left out."""
    keys = {tm: table_key(tm) for tm in tms}
    by: dict[str, list[str]] = {}
    for tm in tms:
        by.setdefault(keys[tm][0], []).append(tm)
    out = {}
    for group in by.values():
        if len(group) < 2:
            continue
        for tm in group:
            out[tm] = []
            for o in group:
                if o != tm:
                    s, m = table_start(keys[o][1], keys[tm][1])
                    out[tm].append({"tm": o, "start": s, "mirror": m})
    return out


# ----------------------------------------------------------------------------------------------- machines/<tm>/

def _last_work(mdir: Path) -> float:
    """Newest mtime of a file in the machine folder, ignoring rendered pages and caches."""
    newest = 0.0
    stack = [mdir]
    while stack:
        d = stack.pop()
        try:
            with os.scandir(d) as it:
                for e in it:
                    if e.is_dir(follow_symlinks=False):
                        if e.name not in ("__pycache__", "review", "compare", "screens"):   # rendered pages, not work
                            stack.append(Path(e.path))
                    elif e.is_file(follow_symlinks=False) and e.name not in WORK_SKIP and not e.name.endswith(".pyc"):
                        newest = max(newest, e.stat().st_mtime)
        except OSError:
            pass
    return newest


def _ask(st: dict, reason: str) -> str:
    """The call proof work waits on (tools/card.py card_state's rule): status.json priority_call, else the
    'priority call' sentence of the reason."""
    ask = st.get("priority_call") if isinstance(st.get("priority_call"), str) else ""
    # a status.json carrying 'parked' or 'funded' records Dennis's answer to the call its reason still quotes
    if not ask.strip() and reason and not (st.get("parked") or st.get("funded")):
        ask = C._sentence_with(reason, C._PRIORITY_RX)
        ask = re.sub(r"priority call for dennis\s*:?\s*", "", ask, flags=re.I)
        ask = re.sub(r"\bneeds dennis(?:'s|’s)", "needs your", ask, flags=re.I)
        ask = re.sub(r"\bneeds dennis\b", "needs you", ask, flags=re.I)
        ask = re.sub(r"\bdennis(?:'s|’s)\b", "your", ask, flags=re.I)
    ask = ask.strip()
    return ask[:1].upper() + ask[1:]


def pipeline_step(status: str, stage: str, mdir: Path) -> int:
    """0 observe, 1 deepen, 2 proof.md, 3 Rocq, 4 killed."""
    if status in KILLED:
        return 4
    if status == "CHECKPOINT_B" or stage in ("formalize", "formal_proof", "verify") \
            or any(mdir.glob("*.v")) or (mdir / "rocq").is_dir() and any((mdir / "rocq").glob("*.v")):
        return 3
    if stage == "informal_proof" or (mdir / "proof.md").is_file():
        return 2
    if stage.startswith("deepen") or stage in ("rules", "observe+research", "research") \
            or (mdir / "deepen.json").is_file():
        return 1
    return 0


def _ts(s) -> float | None:
    """An ISO time (check_kill's checked_at, a status.json killed_at) as a timestamp."""
    if not isinstance(s, str) or not s.strip():
        return None
    try:
        t = _dt.datetime.fromisoformat(s.strip().replace("Z", "+00:00"))
    except ValueError:
        return None
    return (t if t.tzinfo else t.astimezone()).timestamp()


def _when(ts: float) -> str:
    return _dt.datetime.fromtimestamp(ts).strftime("%b %-d %H:%M")


def _kill_info(mdir: Path, tm: str, st: dict | None = None) -> dict:
    """Kill facts from check_kill.txt's JSON line(s). The facts are the latest run's; first_ts is the EARLIEST
    PASS on record (every JSON line of submission/ and the folder's check_kill.txt, and status.json killed_at),
    so a re-run for a review never renumbers the kills (build_records also keeps a ledger)."""
    sub = mdir / "submission"
    info: dict = {"submission": sub.is_dir()}
    runs = []
    for ck in (sub / "check_kill.txt", mdir / "check_kill.txt"):
        if not ck.is_file():
            continue
        for line in ck.read_text(encoding="utf-8", errors="replace").splitlines():
            if line.startswith("JSON: "):
                try:
                    j = json.loads(line[6:])
                except ValueError:
                    continue
                if isinstance(j, dict):
                    runs.append((_ts(j.get("checked_at")) or 0.0, str(ck.relative_to(mdir)), j))
    if runs:
        ts, cfile, j = max(runs, key=lambda r: r[0])
        info.update(result=j.get("result"), checked_at=j.get("checked_at"), compile_s=j.get("compile_seconds"),
                    coqchk=j.get("coqchk"), assumptions=len(j.get("assumptions") or []), check_file=cfile)
        if ts:
            info["when"], info["when_ts"] = _when(ts), ts
    firsts = [r[0] for r in runs if r[0] and r[2].get("result") == "PASS"]
    if _ts((st or {}).get("killed_at")):
        firsts.append(_ts(st["killed_at"]))
    if firsts:
        info["first_ts"] = min(firsts)
    for v in (sub / f"{tm}.v", mdir / f"{tm}.v"):
        if v.is_file():
            data = v.read_bytes()
            info.update(v=str(v.relative_to(mdir)), v_lines=data.count(b"\n"), v_bytes=len(data))
            break
    for p in (sub / "proof.md", mdir / "proof.md"):
        if p.is_file():
            info["proof"] = str(p.relative_to(mdir))
            break
    if (sub / "README.md").is_file():
        info["readme"] = "submission/README.md"
    info["reviews"] = sorted({p.name for g in REVIEW_GLOBS for p in mdir.glob(g) if p.is_file()},
                             key=lambda n: (not n.endswith(".html"), n.rsplit(".", 1)[0]))
    return info


def mechanism_line(readme: Path) -> str:
    """The first bullet under '## Mechanism' in a submission README (continuation lines joined), or ''."""
    try:
        lines = readme.read_text(encoding="utf-8", errors="replace").splitlines()
    except OSError:
        return ""
    on, out = False, []
    for ln in lines:
        if re.match(r"^#{1,6}\s", ln):
            if out:
                break
            on = bool(re.match(r"^#{1,6}\s*mechanism\b", ln, re.I))
            continue
        if not on:
            continue
        if re.match(r"^\s*[-*]\s+", ln):
            if out:
                break
            out.append(re.sub(r"^\s*[-*]\s+", "", ln))
        elif out and ln.strip():
            out.append(ln.strip())
        elif out:
            break
    return " ".join(out).strip()


def _str(v) -> str:
    return v.strip() if isinstance(v, str) else ""


def submission(st: dict) -> dict:
    """A kill's upstream state from status.json: 'accepted' (pr_state merged), 'submitted' (a PR that is open, or
    whose state was never synced), 'claimed' (no PR, or a PR closed unmerged: flagged 'closed'). Plus the PR
    facts the tiles show: pr (URL), no, pr_state, file (upstream path), posted (text) / posted_date, opened,
    merged_at / merged_by (tools/pr_sync.py), comments (comments + reviews, when synced)."""
    url, ps = _str(st.get("pr")), _str(st.get("pr_state")).lower()
    if not url:
        return {"state": "claimed"}
    m = PR_RX.search(url)
    out = {"pr": url, "no": int(m.group(1)) if m else None, "pr_state": ps or None,
           "file": _str(st.get("pr_file")), "posted": _str(st.get("posted")), "opened": _str(st.get("pr_opened"))}
    d = re.search(r"\d{4}-\d{2}-\d{2}", out["posted"])
    out["posted_date"] = d.group(0) if d else ""
    out["state"] = "accepted" if ps == "merged" else "claimed" if ps == "closed" else "submitted"
    if ps == "closed":
        out["closed"] = True
    if ps == "merged":
        mt = _str(st.get("pr_merged_at")) or (re.match(r"\d{4}-\d{2}-\d{2}T[\d:]+Z?", _str(st.get("merged"))) or
                                              [""])[0]
        out["merged_at"], out["merged_by"] = mt, _str(st.get("pr_merged_by"))
    if isinstance(st.get("pr_comments"), int):
        out["comments"] = st["pr_comments"]
    return out


def off_list_reason(st: dict, sub: dict | None, n_list: int) -> dict:
    """Why a machine we have a folder for is not on the current list: {short, text}. Our merged PR first, else
    status.json 'holdouts_<n>' (e.g. 'absent: removed by equivalence (...) to <tm>, which stays on the list')."""
    if sub and sub.get("state") == "accepted":
        no = f"#{sub['no']}" if sub.get("no") else ""
        return {"short": f"solved by our merged PR {no}".strip(),
                "text": f"removed from the {n_list} list because our PR {no} was merged upstream".replace("  ", " ")}
    historical = ("holdouts_740", "holdouts_778") if n_list in (698, 663) else ()
    for key in (f"holdouts_{n_list}", "off_list", *historical):
        txt = _str(st.get(key))
        if txt:
            short = re.sub(r"^absent\s*[:(]?\s*", "", txt, flags=re.I)
            short = re.split(r"\s*[(;,]", short, maxsplit=1)[0].strip(" .:)") or txt
            return {"short": short, "text": txt}
    return {"short": "reason not recorded", "text": f"not on the {n_list} list; status.json gives no reason "
            f"(add a 'holdouts_{n_list}' field)"}


def _open_decision(mdir: Path) -> bool:
    """True if machines/<tm>/decision.json exists and has no filed answer (unreadable counts as open)."""
    p = mdir / "decision.json"
    if not p.is_file():
        return False
    try:
        return not json.loads(p.read_text(encoding="utf-8")).get("answer")
    except (OSError, ValueError, AttributeError):
        return True


def machine_state(mdir: Path, now: float) -> dict:
    """Everything the dashboard shows about a machine we have touched."""
    tm = mdir.name
    st = C.load_status(mdir)
    obs, err = (C.load_obs(mdir / "observe.json") if (mdir / "observe.json").is_file() else ({}, None))
    obs = obs or {}
    qs = C.norm_questions(obs)
    state = C.card_state(obs, st, qs, mdir)
    status, stage, reason = state["status"], state["stage"], state["reason"]
    ask = _ask(st, reason) if status not in KILLED else ""
    last = _last_work(mdir)
    live = bool(last) and now - last < LIVE_MIN * 60
    # The bucket comes from the status files alone (card_state, so it agrees with the machine pages);
    # recent file activity is only the "working" badge.
    sub = submission(st) if status in KILLED else None
    if sub:
        bucket = sub["state"]                     # accepted / submitted / claimed
    elif state["group"] == "wait":
        bucket = "waiting"
    elif state["group"] == "parked" or status in ("STUCK", "CRYPTID_CANDIDATE", "SKIPPED"):
        bucket = "parked"
    else:
        bucket = "active"
    # a stage Dennis funded from the decision queue is in the pipeline until it files a new, unanswered call
    if bucket == "waiting" and isinstance(st.get("funded"), dict) and not _open_decision(mdir):
        bucket = "active"
    conf = st.get("confidence") if st.get("confidence") in C.CONFIDENCE else obs.get("confidence")
    open_qs = [[k + 1, q["text"]] for k, q in enumerate(qs) if not q["answer"]]
    diags = C.diag_list(obs)
    dc = obs.get("discord_check")
    rec = {
        "status": status, "stage": stage, "reason": reason, "updated": state["updated"],
        "group": state["group"], "bucket": bucket, "live": live, "last_work": last,
        "step": pipeline_step(status, stage, mdir), "ask": ask,
        "questions": open_qs if state["group"] == "wait" and not ask else [],
        "confidence": conf if conf in C.CONFIDENCE else None,
        "summary": obs.get("summary") if isinstance(obs.get("summary"), str) else "",
        "class_ours": obs.get("class_guess") if isinstance(obs.get("class_guess"), str) else "",
        "open_q": list(state["open"]), "discord": dc.strip() if isinstance(dc, str) and dc.strip() else "",
        "unlabelled": sum(1 for i, x in enumerate(diags) if not isinstance(x, dict) or C.label_issues(x, i)[0]),
        "stage_txt": state.get("stage_txt") or "", "short": state.get("short") or "",
        "proof_md": (mdir / "proof.md").is_file(),
        "notes": (mdir / "notes.md").is_file(), "parent": st.get("parent") if isinstance(st.get("parent"), str) else "",
        "label": st.get("label") if isinstance(st.get("label"), str) else "",
        "obs_error": err, "has_status": bool(st), "has_observe": bool(obs),
    }
    if sub:
        rec["sub"] = sub
        rec["kill"] = _kill_info(mdir, tm, st)
        mech = mechanism_line(mdir / "submission" / "README.md")
        if mech:                                  # the submitted mechanism, not the (older) observer summary
            rec["summary"], rec["summary_src"] = mech, "submission/README.md, Mechanism"
    return rec


# ----------------------------------------------------------------------------------------------- thumbnails

def thumb_path(out: Path, tm: str) -> Path:
    return out / "thumbs" / f"{tm}.png"


def _thumb_init():
    try:
        os.nice(10)
    except OSError:
        pass


def _thumb_job(job: tuple[str, str]) -> tuple[str, str | None]:
    tm, dest = job
    try:
        import diagram as dg
        cv = dg.site_default_canvas(tm, steps=THUMB["steps"], width=THUMB["width"], ox=THUMB["ox"],
                                    canvas=tuple(THUMB["canvas"]))
        dest_p = Path(dest)
        tmp = dest_p.with_name(f".{dest_p.name}.{os.getpid()}.tmp")
        tmp.write_bytes(cv.to_png())
        os.replace(tmp, dest_p)
        return tm, None
    except Exception as e:                       # one bad machine never stops the page
        return tm, f"{type(e).__name__}: {e}"


def ensure_thumbs(tms: list[str], out: Path, force: bool = False, jobs: int = THUMB_JOBS) -> dict:
    """Draw the missing thumbnails (all of them if forced or if the drawing parameters changed)."""
    tdir = out / "thumbs"
    tdir.mkdir(parents=True, exist_ok=True)
    params = tdir / "params.json"
    try:
        old = json.loads(params.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        old = None
    if old != THUMB:
        force = True
    todo = [tm for tm in tms if force or not thumb_path(out, tm).is_file()]
    errors = {}
    t0 = time.time()
    if todo:
        jobs = max(1, min(jobs, THUMB_JOBS, len(todo)))
        work = [(tm, str(thumb_path(out, tm))) for tm in todo]
        if jobs == 1:                            # in-process (tests); the caller's own priority is left alone
            for tm, e in map(_thumb_job, work):
                if e:
                    errors[tm] = e
        else:
            with multiprocessing.get_context("fork").Pool(jobs, initializer=_thumb_init) as pool:
                for tm, e in pool.imap_unordered(_thumb_job, work, chunksize=4):
                    if e:
                        errors[tm] = e
        C.write_atomic(params, json.dumps(THUMB, indent=1) + "\n")
    return {"drawn": len(todo) - len(errors), "errors": errors, "seconds": round(time.time() - t0, 1)}


# ----------------------------------------------------------------------------------------------- records

def machine_dirs(machines: Path) -> dict[str, Path]:
    return {d.name: d for d in sorted(machines.iterdir()) if d.is_dir() and TM_RX.fullmatch(d.name)} \
        if machines.is_dir() else {}


def load_reconciliation(list_path: Path, machines: Path) -> dict:
    """Static upstream evidence is used only with its exact canonical current-list input.

    Alternate lists and fixture trees retain their own status logic. A broken installed
    reconciliation fails the build rather than silently restoring stale submission credit.
    """
    if Path(list_path).resolve() != LIST.resolve() or Path(machines).resolve() != MACHINES.resolve():
        return {}
    if not RECONCILIATION.is_file():
        return {}
    data = json.loads(RECONCILIATION.read_text(encoding="utf-8"))
    current = data["current_list"]
    if data.get("schema_version") != 1 or hashlib.sha256(Path(list_path).read_bytes()).hexdigest() != current["sha256"]:
        raise ValueError("current holdout list does not match reconciliation evidence")
    tms = load_list(Path(list_path))
    rows = data["machines"]
    if len(tms) != current["count"] or set(tms) != {t for t, r in rows.items() if r.get("retained_current", r.get("retained698"))}:
        raise ValueError("reconciliation membership/count mismatch")
    return data


def apply_reconciliation(rec: dict, row: dict, machines: Path) -> None:
    """Enrich presentation without rewriting live status or granting publication credit.

    Current local status remains authoritative. A pending audited promotion is the only
    exception, and requires the current literal proof bytes to match the recorded gate.
    """
    rec["reconciliation"] = row
    rec["raw_status"], rec["raw_stage"] = rec.get("status"), rec.get("stage")
    rec["old740_line"], rec["current698_line"] = row["old740_line"], row["current698_line"]
    rec["line_740"], rec["line_698"] = row["old740_line"], row["current698_line"]
    rec["current_line"] = row.get("current_line", row.get("current698_line"))
    rec["current_list_size"] = row.get("current_list_size", 698)
    rec["current663_line"] = row.get("current663_line")
    rec["upstream"] = row.get("upstream")
    proof = dict(row["local_proof"]) if row.get("local_proof") else None
    if proof:
        source = ROOT / proof["source_path"]
        try:
            current_sha = hashlib.sha256(source.read_bytes()).hexdigest()
        except OSError:
            current_sha = None
        gate = proof.get("gate") or {}
        matched = (current_sha == proof.get("source_sha256") == gate.get("sha256")
                   and gate.get("tm") == rec["tm"] and gate.get("result") == "PASS"
                   and gate.get("exit") == 0 and gate.get("coqchk") == "pass")
        proof["source_matches"] = matched
        proof["ready"] = bool(proof.get("ready") and matched)
        proof["packaging_ready"] = bool(proof.get("packaging_ready") and proof["ready"])
        if not matched:
            proof["readiness_warning"] = "Current proof source no longer matches the recorded audited gate."
        rec["local_proof"] = proof
        if proof["ready"] and proof.get("status_promotion_pending") and rec.get("status") == row.get("current_status"):
            rec.update(status="KILLED_HALT" if proof["result"] == "halt" else "KILLED_NONHALT",
                       stage="done", bucket="claimed", group="killed", step=3,
                       reason="Audited blank-start proof; raw status promotion and packaging remain pending.")
            rec["sub"] = submission(C.load_status(machines / rec["tm"]))
            rec["bucket"] = rec["sub"]["state"]
            rec["kill"] = _kill_info(machines / rec["tm"], rec["tm"])
    upstream = row.get("upstream")
    kind = row.get("suggested_bucket")
    if upstream and kind in ("upstream_overlap", "external_solved", "accepted"):
        # New live PR facts can still progress a local proof after this static snapshot.
        live_sub = rec.get("sub") or {}
        if kind == "upstream_overlap" and live_sub.get("state") in ("submitted", "accepted"):
            kind = live_sub["state"]
        if kind == "external_solved" and rec.get("status") in KILLED:
            kind = "upstream_overlap"
        rec["bucket"] = kind
        sub = dict(live_sub)
        sub.update(state=kind, upstream=upstream)
        if kind == "accepted" and upstream.get("pr_url"):
            sub.update(pr=upstream["pr_url"], no=upstream["original_pr"], pr_state="merged",
                       merged_at=upstream.get("merged_at_utc"),
                       file=" · ".join(x for x in (upstream.get("file"), upstream.get("module")) if x))
        rec["sub"] = sub
        if kind == "external_solved":
            rec.update(status="EXTERNALLY_SOLVED", stage="done")
            rec["reason"] = "Mapped upstream blank-start proof; no local proof counted."
        elif kind == "upstream_overlap":
            rec["reason"] = "Claimed by someone else while our local proof remained unsubmitted. See source and timing details."
        if not rec.get("line"):
            short = ("our merged PR" if kind == "accepted" else "claimed by someone else"
                     if kind == "upstream_overlap" else "solved upstream externally")
            rec["off"] = {"short": short, "text": short + ": " + upstream["source_url"]}
    external = row.get("external_submission")
    if external:
        rec["external_submission"] = external
        if external.get("state") == "open" and rec["bucket"] not in ("accepted", "submitted", "upstream_overlap", "external_solved"):
            local = rec.get("status") in KILLED or (rec.get("local_proof") or {}).get("ready")
            rec["bucket"] = "competing_pr" if local else "external_pending"
            rec["reason"] = f'External PR #{external["number"]} is open; acceptance and attribution remain pending.'
            rec["sub"] = dict(rec.get("sub") or {}, state=rec["bucket"])
            rec.update(ask="", questions=[], open_q=[], live=False, discord="")
    if rec["bucket"] in SOLVED_BUCKETS:
        rec.update(ask="", questions=[], open_q=[], live=False, discord="")


def packaging_ready(rec: dict) -> bool:
    evidence = rec.get("local_proof")
    return bool(evidence.get("packaging_ready")) if evidence is not None else True


def shown_tms(list_path: Path = LIST, machines: Path = MACHINES, prev_path: Path | None = PREV_LIST) -> list[str]:
    """Every machine the page shows: the list in order, then the machines/ folders not on it (previous-list
    order, then by name)."""
    tms = load_list(list_path)
    prev = _prev_lines(prev_path, list_path)
    on = set(tms)
    evidence = load_reconciliation(list_path, machines).get("machines", {})
    off = sorted((t for t in set(machine_dirs(machines)) | set(evidence) if t not in on),
                 key=lambda t: (prev.get(t, 10**6), t))
    return tms + off


def _prev_lines(prev_path: Path | None, list_path: Path) -> dict[str, int]:
    if not prev_path or not Path(prev_path).is_file() or Path(prev_path).resolve() == Path(list_path).resolve():
        return {}
    return {tm: i for i, tm in enumerate(load_list(Path(prev_path)), 1)}


def _lsort(r: dict) -> int:
    """List order with the off-list machines last (by their previous-list line)."""
    return r["line"] if r.get("line") else 10_000 + (r.get("line_prev") or 9_999)


def build_records(list_path: Path = LIST, eqv_path: Path = EQV, machines: Path = MACHINES, out: Path = OUT,
                  now: float | None = None, prev_path: Path | None = PREV_LIST,
                  guess_for: set[str] | None = None) -> tuple[list[dict], dict]:
    """Every machine's record + the page facts. guess_for: compute class guesses only for these machines (a
    single machine page skips the ~3 s guess pass over the whole list); None = all."""
    now = time.time() if now is None else now
    tms = load_list(list_path)
    onlist = set(tms)
    prev = _prev_lines(prev_path, list_path)
    reconciliation = load_reconciliation(list_path, machines)
    reconciled = reconciliation.get("machines", {})
    legacy = _prev_lines(LEGACY_LIST, list_path) if reconciliation else {}
    shown = shown_tms(list_path, machines, prev_path)
    off_tms = shown[len(tms):]
    eqv = load_eqv(eqv_path)
    members = {m: rep for rep, g in eqv.items() for m in g}
    ranks = load_ranks(TARGETING)
    by_rank = {r: tm for tm, r in ranks.items()}
    ledger = load_ledger(LEDGER, by_rank)
    sheet = sheet_data(shown, count_over=tms)
    lists = {k: load_tm_set(p) for k, p, _, _ in DISCORD_LISTS}
    dirs = machine_dirs(machines)
    recs = []
    for i, tm in enumerate(shown, 1):
        line = i if tm in onlist else None
        group = eqv.get(tm, [tm])
        cls = sheet["classes"].get(tm, "")
        res = sheet["results"].get(tm, {})
        rec = {"tm": tm, "line": line, "line_prev": prev.get(tm), "eqv": len(group), "class": cls,
               "class_src": sheet["class_src"].get(tm, ""),
               "guess": None, "sim": sheet["sim"][tm], "rank": ranks.get(tm, ""),
               "sheet_status": res.get("status", "").strip(), "sheet_notes": res.get("notes", "").strip(),
               "sheet_row": res.get("row"), "flags": [k for k, *_ in DISCORD_LISTS if tm in lists[k]],
               "thumb": thumb_path(out, tm).is_file(), "ledger": ledger.get(tm)}
        rec["has_folder"] = tm in dirs
        rec["aid"] = f"m{line}" if line else f"p{prev[tm]}" if tm in prev else f"x{i}"
        if reconciliation:
            old_line = reconciled.get(tm, {}).get("old740_line")
            # Keep all published old-740 mN links bound to the same exact machine.
            rec["aid"] = f"m{old_line}" if old_line else f"p{legacy[tm]}" if tm in legacy else f"n{len(tms)}-{line}"
            if not rec["line_prev"] and tm in legacy:
                rec["line_prev"], rec["prev_n"] = legacy[tm], len(legacy)
        if not line:
            rec.setdefault("prev_n", len(prev))
        if (not cls or cls == "Unknown") and (guess_for is None or tm in guess_for):
            excl = set(group) | {members.get(tm, tm)}
            rec["guess"] = guess_class(tm, sheet["classes"], excl)
        if tm in SHEET_OVERRIDE:
            rec["sheet_override"] = SHEET_OVERRIDE[tm]
        if tm in dirs:
            rec.update(machine_state(dirs[tm], now))
            if rec.get("parent"):
                rec["parent_rank"] = ranks.get(rec["parent"], "")
            if line is None:
                rec["off"] = off_list_reason(C.load_status(dirs[tm]), rec.get("sub"), len(tms))
        else:
            rec["bucket"] = "untouched"
        if tm in reconciled:
            apply_reconciliation(rec, reconciled[tm], machines)
        recs.append(rec)
    by_tm = {r["tm"]: r for r in recs}
    # an off-list reason that names a machine still on the list (removed by equivalence to it): link both ways
    ekeys: dict[str, str] | None = None
    for r in recs:
        if not r.get("off"):
            continue
        for t in dict.fromkeys(m.group(0) for m in TM_RX.finditer(r["off"]["text"])):
            x = t if t in onlist else None
            if x is None:
                if ekeys is None:
                    ekeys = {}
                    for y in tms:
                        ekeys.setdefault(H.equiv_key(y) or y, y)
                x = ekeys.get(H.equiv_key(t) or t)
            if x and x != r["tm"]:
                o = by_tm[x]
                r["off"]["target"] = {"tm": x, "aid": o["aid"], "line": o["line"], "same": x == t}
                o.setdefault("eq_of", []).append({"tm": r["tm"], "aid": r["aid"], "short": r["off"]["short"],
                                                   "bucket": r["bucket"]})
                break
    ledger_p = out / KILL_LEDGER
    kill_ledger = _load_kill_ledger(ledger_p)
    kills = [r for r in recs if r["bucket"] in LOCAL_PROOF_BUCKETS]
    for r in kills:                                # kill numbers: the first PASS ever seen, never the latest
        k = r["kill"]
        cands = [x for x in (_ts(kill_ledger.get(r["tm"], {}).get("first_pass")), k.get("first_ts")) if x]
        first = min(cands) if cands else k.get("when_ts")
        if first:
            k["first_ts"], k["first"] = first, _when(first)
            kill_ledger[r["tm"]] = {"first_pass": _dt.datetime.fromtimestamp(first).astimezone().isoformat(
                timespec="seconds"), "name": member_name(r)}
    for i, r in enumerate(sorted(kills, key=lambda r: (r["kill"].get("first_ts") or 9e18, _lsort(r))), 1):
        r["kill_no"] = i
    # same table, other start: every member names the others; the reference is the most advanced other member
    groups = table_groups(shown)
    for r in recs:
        others = groups.get(r["tm"])
        if not others:
            continue
        r["table"] = [dict(o, name=member_name(by_tm[o["tm"]]), bucket=by_tm[o["tm"]]["bucket"],
                           aid=by_tm[o["tm"]]["aid"]) for o in others]
        r["table"].sort(key=lambda o: _member_key(by_tm[o["tm"]]))
        ref = by_tm[r["table"][0]["tm"]]
        if ref["bucket"] != "untouched":
            back = next(o for o in groups[ref["tm"]] if o["tm"] == r["tm"])   # r as a start of ref's table
            r["table_ref"] = {"tm": ref["tm"], "name": member_name(ref), "bucket": ref["bucket"],
                              "aid": ref["aid"], "start": back["start"], "mirror": back["mirror"]}
    kill_families(kills)
    for r in recs:                                 # names, now that every machine has its kill number / table
        for e in r.get("eq_of") or []:
            e["name"] = member_name(by_tm[e["tm"]])
        if r.get("off", {}).get("target"):
            r["off"]["target"]["name"] = member_name(by_tm[r["off"]["target"]["tm"]])
    # a call that names another machine (R4's "invest in a joint #32/R4 invariant, or park both?") shows there too
    for r in recs:
        if not r.get("ask"):
            continue
        for tok in sorted(set(re.findall(r"(?<![\w#-])(#\d+|R\d+)(?![\w-])", r["ask"]))):
            o = by_tm.get(by_rank.get(tok.lstrip("#"), ""))
            if o and o is not r and o["bucket"] not in SOLVED_BUCKETS + ("untouched",):
                o.setdefault("ask_via", []).append({"tm": r["tm"], "name": member_name(r), "ask": r["ask"],
                                                    "bucket": r["bucket"], "aid": r["aid"]})
    for r in recs:                                  # untouched order: kill-table starts, pool, touched-table starts
        if r["bucket"] == "untouched":
            tr = r.get("table_ref")
            r["tier"] = 0 if tr and tr["bucket"] in SOLVED_BUCKETS else 1 if r["rank"] else 2 if tr else 3
    prs = {}
    for r in kills:                                 # one entry per PR, for the section keys
        s = r["sub"]
        if s.get("pr"):
            p = prs.setdefault(s["pr"], dict(s, machines=[]))
            p["machines"].append(r["tm"])
            for k in ("posted_date", "opened", "merged_at", "merged_by"):
                p[k] = p.get(k) or s.get(k)
    meta = {"list": list_path, "n": len(tms), "n_shown": len(shown),
            "prev": Path(prev_path) if prev else None, "n_prev": len(prev),
            "prev_gone": len(set(prev) - onlist) if prev else 0,
            "eqv_total": sum(len(eqv.get(t, [t])) for t in tms),
            "off_list": off_tms, "pending": sheet["pending_counts"], "now": now,
            "ranks": len(ranks), "kill_ledger": kill_ledger, "kill_ledger_path": ledger_p, "prs": prs,
            "reconciliation": {k: v for k, v in reconciliation.items() if k != "machines"},
            "tables": {"groups": len({tuple(sorted([t] + [o["tm"] for o in g])) for t, g in groups.items()}),
                       "machines": len(groups)}}
    return recs, meta


def kill_families(kills: list[dict]) -> None:
    """Kills joined by a status.json parent link or a shared table (another start) are one family; the lead is
    its lowest kill number. Sets r['fam'] (the lead's tm), r['fam_name'] and r['fam_members'] (names, kill order)."""
    up = {r["tm"]: r["tm"] for r in kills}

    def find(x: str) -> str:
        while up[x] != x:
            up[x] = up[up[x]]
            x = up[x]
        return x
    for r in kills:
        for o in [r.get("parent")] + [t["tm"] for t in r.get("table") or []]:
            if o in up:
                up[find(o)] = find(r["tm"])
    fams: dict[str, list[dict]] = {}
    for r in kills:
        fams.setdefault(find(r["tm"]), []).append(r)
    for g in fams.values():
        g.sort(key=lambda r: (r.get("kill_no") or 999, _lsort(r)))
        names = [member_name(x) for x in g]
        for r in g:
            r["fam"], r["fam_name"], r["fam_members"] = g[0]["tm"], names[0], names


def _load_kill_ledger(p: Path) -> dict:
    try:
        d = json.loads(p.read_text(encoding="utf-8"))
    except (OSError, ValueError):
        return {}
    return {k: v for k, v in d.items() if isinstance(v, dict)} if isinstance(d, dict) else {}


def member_name(r: dict) -> str:
    """How a machine is named on other tiles: '#3', 'R4', '#3b' (status.json label), 'twin of #12', 'line 604'."""
    if r["rank"]:
        return rank_label(r["rank"])
    if r.get("label"):
        return r["label"]
    if r.get("parent") and r.get("parent_rank"):
        return f"twin of {rank_label(r['parent_rank'])}"
    return line_label(r)


def line_label(r: dict) -> str:
    """'line 604' on the current list; '778 line 12' (the previous list's line) for a machine no longer on it."""
    if r.get("old740_line"):
        return f"740 line {r['old740_line']}"
    if r.get("current_line"):
        return f"{r['current_list_size']} line {r['current_line']}"
    if r.get("line"):
        return f"line {r['line']}"
    if r.get("line_prev"):
        return f"{r.get('prev_n') or 'previous list'} line {r['line_prev']}"
    return "off the list"


def _member_key(r: dict) -> tuple:
    """Most advanced first: kills (kill order), touched (pool rank), pool targets, then list order."""
    if r["bucket"] in LOCAL_PROOF_BUCKETS:
        return (0, r.get("kill_no") or 99, _lsort(r))
    if r["bucket"] != "untouched":
        return (1, rank_sort(r["rank"]), _lsort(r))
    return (2 if r["rank"] else 3, rank_sort(r["rank"]), _lsort(r))


# ----------------------------------------------------------------------------------------------- HTML pieces

def _rel_machine(tm: str, path: str = "") -> str:
    return "../machines/" + quote(tm) + "/" + C.url_path(path)


def _explorer(tm: str) -> str:
    return "../tools/explorer/#tm=" + quote(tm, safe="_-")


def _first_sentences(s: str, limit: int = 260) -> str:
    s = " ".join((s or "").split())
    if len(s) <= limit:
        return s
    parts = re.split(r"(?<=[.!?;])\s+", s)
    out = ""
    for p in parts:
        if len(out) + len(p) + 1 > limit:
            break
        out = (out + " " + p).strip()
    return out or s[:limit].rsplit(" ", 1)[0] + " …"


def _tm_html(tm: str, cls: str = "tmn") -> str:
    """The machine string, breakable only between state groups (never inside '---')."""
    gs = tm.split("_")
    return f'<div class="{cls}">' + "<wbr>".join(f'<span>{esc(g)}{"_" if i < len(gs) - 1 else ""}</span>'
                                                 for i, g in enumerate(gs)) + "</div>"


def _ago(ts: float, now: float) -> str:
    """'Oct 10 10:47 (16 min ago)' as of `now` (the build); the page's JS redoes it on the viewer's clock."""
    m = int((now - ts) // 60)
    when = _when(ts)
    if m < 1:
        return f"{when} (just now)"
    if m < 120:
        return f"{when} ({m} min ago)"
    if m < 48 * 60:
        return f"{when} ({m // 60} h ago)"
    return when


def ago_html(ts: float, now: float) -> str:
    return f'<span class="ago" data-ts="{int(ts)}">{esc(_ago(ts, now))}</span>'


def thumb_target(rec: dict) -> tuple[str, str]:
    """Where a click on a thumbnail goes: our machine page (machines/<tm>/index.html) for every machine with a
    folder; else (untouched machines) bbchallenge.org. Returns (href relative to dashboard/, tooltip suffix)."""
    tm = rec["tm"]
    if rec.get("has_folder", rec.get("bucket") not in (None, "untouched")):          # untouched = no folder in the tree built from
        return f"../machines/{quote(tm)}/index.html", " · click: open our page for this machine"
    external = rec.get("external_submission") or {}
    if external.get("url"):
        return external["url"], " · external PR awaiting review"
    upstream = rec.get("upstream") or {}
    if upstream.get("source_url"):
        return upstream["source_url"], " · click: upstream proof (no local folder)"
    return C.tm_url(tm), " · click: open on bbchallenge.org (no folder yet)"


def thumb_html(rec: dict, w: int, h: int) -> str:
    tm = rec["tm"]
    if rec.get("thumb"):
        inner = (f'<img src="/busy-beaver/tools/thumbs/</span><span class="si">{quote(tm)}.png" width="{w}" height="{h}" loading="lazy" decoding="async" '
                 f'alt="space-time diagram from the blank tape, steps 0 to 10,000">')
    else:
        inner = '<span class="nothumb">no thumbnail</span>'
    href, where = thumb_target(rec)
    return f'<a class="th" href="/busy-beaver/tools/</span><span class="si">{esc(href)}" title="{esc(THUMB_TIP + where)}">{inner}</a>'


def _bold(h: str) -> str:
    """**x** -> <b>x</b> in already-escaped text (submission READMEs use it for a bullet's lead)."""
    return re.sub(r"\*\*(.+?)\*\*", r"<b>\1</b>", h)


def _plain(s: str) -> str:
    return re.sub(r"\*\*|`", "", s or "")


def class_html(rec: dict, mini: bool = False) -> str:
    cls = rec["class"] or "unclassified"
    tip = f"sheet class ({rec['class_src'] or 'none'}): {cls}"
    if rec.get("class_ours") and C.norm_class(rec["class_ours"]) != C.norm_class(cls):
        tip += f" · ours: {rec['class_ours']}"
    out = f'<span class="cl" title="{esc(tip)}">{esc(cls)}</span>'
    if not mini and rec.get("confidence") in C.CONFIDENCE:   # the observer's confidence in the mechanism
        out += (f' <span class="conf" title="the observer\'s confidence in the mechanism (observe.json): '
                f'{esc(rec["confidence"])}">{C.CONFIDENCE[rec["confidence"]]}</span>')
    g = rec.get("guess")
    if g:
        votes = ", ".join(f"{c} {n}" for c, n in sorted(g["votes"].items(), key=lambda x: -x[1]))
        gtip = (f"GUESS, not the sheet's: the nearest classified machine{'s' if g['n_near'] > 1 else ''} "
                f"({g['n_near']}) differ{'s' if g['n_near'] == 1 else ''} in {g['dist']} transition"
                f"{'s' if g['dist'] != 1 else ''} (up to mirror/renaming); classes: {votes}; e.g. {g['near']}")
        out += (f'<span class="gs" title="{esc(gtip)}"><b>guess</b> {esc(g["class"])} '
                f'<span class="muted">({g["dist"]} tr.)</span></span>')
    return f'<div class="tcl">{out}</div>'


def _start_txt(start: str, mirror: bool) -> str:
    return f"start {start}" + (", mirrored" if mirror else "")


def table_tip(rec: dict) -> str:
    """Tooltip: every other machine with this table, as a start of THIS machine's table."""
    rows = [f"{o['name']} ({o['bucket']}): this table from {_start_txt(o['start'], o['mirror'])}"
            for o in rec.get("table") or []]
    return "Same table, other start (states renamed, maybe mirrored):\n" + "\n".join(rows)


def table_html(rec: dict) -> str:
    """Big tiles: 'same table: B → line 604 ○ · C → #25 ✓ · D mirrored → #24 ✓' (starts in this machine's names)."""
    others = rec.get("table") or []
    if not others:
        return ""
    items = []
    for o in others:
        st = f'{o["start"]}{" mirrored" if o["mirror"] else ""}'
        items.append(f'<span class="tsm"><b>{esc(st)}</b> → <a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{o["aid"]}">{esc(o["name"])}</a>'
                     f'<span class="bi {o["bucket"]}" title="{esc(o["bucket"])}">{BUCKET_ICON[o["bucket"]]}'
                     f'</span></span>')
    return (f'<div class="ttab" title="{esc(table_tip(rec))}"><span class="lk">same table, other starts</span> '
            + " · ".join(items) + "</div>")


def table_chip(rec: dict) -> str:
    """Untouched tiles: 'same table as kill #3 (start B)' when a machine we worked on has this table."""
    tr = rec.get("table_ref")
    if not tr:
        return ""
    k = tr["bucket"] in SOLVED_BUCKETS
    who = ("kill " if k else "") + tr["name"]
    return (f'<div class="tsame{" k" if k else ""}" title="{esc(table_tip(rec))}">same table as '
            f'<a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{tr["aid"]}">{esc(who)}</a> ({esc(_start_txt(tr["start"], tr["mirror"]))})</div>')


def eq_chip(rec: dict) -> str:
    """A list machine that an off-list one was removed in favour of (by equivalence): our work there applies here.
    'equivalent to', not 'same machine as': the list machine matches the machine the reason names, not the off-list
    one (#19 and 740 line 556 differ even up to renaming and mirroring), so a .v for one does not pass check_kill for
    the other; the equivalence links them."""
    out = []
    for e in rec.get("eq_of") or []:
        out.append(f'<div class="tsame q" title="{esc(e["name"])} left the list ({esc(e["short"])}) in favour of '
                   f'this machine: an equivalent machine, not the same one; a proof of either settles both through '
                   f'that equivalence">equivalent to <a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{e["aid"]}">'
                   f'{esc(e["name"])}</a> (off the list; {esc(e["bucket"])})</div>')
    return "".join(out)


def pr_chip(rec: dict) -> str:
    """'#14 merged' / '#15 open' (a link to the PR) on a kill's tile; nothing for a kill in no PR."""
    s = rec.get("sub") or {}
    if not s.get("pr"):
        return ""
    no = f'#{s["no"]}' if s.get("no") else "PR"
    st = s.get("pr_state") or "state unknown"
    word = {"merged": "merged", "open": "open", "closed": "closed unmerged"}.get(st, st)
    tip = [f"PR {no} {word}" + (f" {s['merged_at']}" if s.get("merged_at") else "")
           + (f" by {s['merged_by']}" if s.get("merged_by") else "")]
    if s.get("file"):
        tip.append(f"file {s['file']}")
    if s.get("posted"):
        tip.append(f"posted: {s['posted']}")
    if "comments" in s:
        tip.append(f"{s['comments']} comments/reviews (tools/pr_sync.py)")
    elif not s.get("pr_state"):
        tip.append("state not synced: run python3 -B tools/pr_sync.py")
    cls = st if st in ("merged", "open", "closed") else "unk"
    return (f'<a class="prc {cls}" href="/busy-beaver/tools/</span><span class="si">{esc(s["pr"])}" title="{esc(" · ".join(tip))}">'
            f'PR {esc(no)} {esc(word)}</a>')


def pr_line(rec: dict) -> str:
    """Accepted: the upstream file and the merge; submitted: the file, when posted, the PR's comment count."""
    s = rec.get("sub") or {}
    if not s.get("pr"):
        return ""
    no = f'#{s["no"]}' if s.get("no") else "the PR"
    bits = []
    if s["state"] == "accepted":
        when = _iso_short(s.get("merged_at"))
        by = f' by {esc(s["merged_by"])}' if s.get("merged_by") else ""
        bits.append(f'merged{" " + esc(when) if when else ""}{by}')
        if s.get("file"):
            up = rec.get("upstream") or {}
            label = f'<code>{esc(s["file"])}</code>'
            if up.get("source_url"):
                label = f'<a href="/busy-beaver/tools/</span><span class="si">{esc(up["source_url"])}">{label}</a>'
            bits.append("upstream file " + label)
    else:
        if s.get("file"):
            bits.append(f'file <code>{esc(s["file"])}</code>')
        if s.get("posted_date"):
            bits.append(f'<span title="{esc(s["posted"])}">posted {esc(s["posted_date"])}</span>')
        elif s.get("posted"):
            bits.append(f'<span title="{esc(s["posted"])}">posted</span>')
        if "comments" in s:
            n = s["comments"]
            bits.append(f'<span class="{"pcn" if n else "muted"}" title="comments + reviews on {esc(no)} at the last '
                        f'tools/pr_sync.py run">{n} comment{"s" if n != 1 else ""}/reviews</span>')
    lab = {"accepted": "upstream", "submitted": "PR"}.get(s["state"], "PR")
    return f'<div class="kpr"><span class="lk">{lab}</span> ' + " · ".join(bits) + "</div>" if bits else ""


def _iso_short(t) -> str:
    """'2026-10-10T20:47:35Z' -> '2026-10-10 20:47 UTC'."""
    m = re.match(r"(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2})", t or "")
    return f"{m.group(1)} {m.group(2)} UTC" if m else (t or "")


def off_chip(rec: dict) -> str:
    """'off the 740 list · removed by equivalence' (the full reason in the tooltip; a link to the list machine)."""
    o = rec.get("off")
    if not o:
        return ""
    tg = o.get("target")
    to = (f' → <a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{tg["aid"]}" title="{"this machine" if tg.get("same") else "an equivalent machine"} on the '
          f'list">{esc(tg.get("name") or line_label(tg))}</a>') if tg else ""
    short = "claimed by someone else" if rec.get("bucket") == "upstream_overlap" else o["short"]
    return (f'<span class="offl" title="{esc(o["text"])}">off the list · {esc(short)}{to}</span>')


def meta_html(rec: dict, rank: bool = False, killed: bool = False) -> str:
    """eqv size, sim depth, flags (and the pool rank, for tiles that do not show it in their head line)."""
    bits = []
    if rank and rec["rank"]:
        bits.append(f'<span class="fl rk" title="our targeting pool rank (reports/targeting.md §4)">'
                    f'{esc(rank_label(rec["rank"]))}</span>')
    bits.append(f'<span class="mt" title="equivalence class: {rec["eqv"]} machine{"s" if rec["eqv"] != 1 else ""}">'
                f'eqv ×{rec["eqv"]}</span>')
    if rec.get("table") and rank and not rec.get("table_ref"):        # mini tiles with no chip: just the size
        bits.append(f'<span class="mt" title="{esc(table_tip(rec))}">table ×{len(rec["table"]) + 1}</span>')
    sim_tip = {13: "sheet: simulated to 1e13, not yet to 1e14", 14: "sheet: simulated to 1e14, not yet to 1e15",
               15: "sheet: simulated to 1e15"}
    sim_cls = "" if killed else f" sim{rec['sim']}"            # a killed machine's sim depth is no warning
    bits.append(f'<span class="mt{sim_cls}" title="{sim_tip[rec["sim"]]}">sim 1e{rec["sim"]}</span>')
    for k, _p, label, tip in DISCORD_LISTS:
        if k in rec["flags"]:
            bits.append(f'<span class="fl" title="{esc(tip)}">{esc(label)}</span>')
    if rec["sheet_status"]:
        tip = f"sheet Results tab row {rec['sheet_row']}: {rec['sheet_status']}"
        if rec["sheet_notes"]:
            tip += f" · {rec['sheet_notes'][:400]}"
        if rec.get("sheet_override"):
            tip = f"{rec['sheet_override']} · {tip}"
            bits.append(f'<span class="fl ss x" title="{esc(tip)}"><s>sheet: {esc(rec["sheet_status"])}</s> '
                        f'misattributed</span>')
        else:
            bits.append(f'<span class="fl ss" title="{esc(tip)}">sheet: {esc(rec["sheet_status"])}</span>')
    return '<div class="tmeta">' + "".join(bits) + "</div>"


def links_html(rec: dict, extra: list[tuple[str, str, str]] | None = None, short: bool = False) -> str:
    items = list(extra or [])
    items += [(C.tm_url(rec["tm"]), "bbchallenge" if short else "bbchallenge ↗", "bbchallenge.org" if short else ""),
              (_explorer(rec["tm"]), "explore" if short else "explorer", "our explorer" if short else "")]
    return '<div class="tln">' + "".join(f'<a href="/busy-beaver/tools/</span><span class="si">{esc(u)}"{f" title={chr(34)}{esc(t)}{chr(34)}" if t else ""}>'
                                         f'{esc(n)}</a>' for u, n, t in items) + "</div>"


def pipe_html(step: int, stage: str) -> str:
    lis = []
    for i, name in enumerate(PIPE):
        cls = "done" if i < step else "now" if i == step else ""
        lis.append(f'<li class="{cls}">{esc(name)}</li>')
    tip = f"pipeline: observe → deepen → proof.md → Rocq → kill; now: {PIPE[min(step, 3)]}" + \
        (f" (status.json stage: {stage})" if stage else " (no status.json stage)")
    return f'<ol class="pipe" title="{esc(tip)}">{"".join(lis)}</ol>'


_TAG_EXACT = re.compile(r"^(?:#\d+[a-z]?|R\d+|[A-Z]\d*-\d+[a-z]?)$")   # tags a search matches exactly (#3, R4, W4-3b)


def _data_attrs(rec: dict, order: int, b: str | None = None, tag: str = "") -> str:
    """What the filter bar reads (search = machine string, label tag, class; the guessed class separately).
    b: the bucket shown (the Machines page splits cryptid candidates off parked); tag: the sitekit.Names tag."""
    rk = tag if _TAG_EXACT.match(tag or "") else rank_label(rec["rank"])
    extra = f' data-rk="{esc(rk)}"' if rk else ""
    if tag:
        extra += f' data-tag="{esc(tag)}"'
    if rec.get("guess"):
        extra += f' data-g="{esc(rec["guess"]["class"])}"'
    if rec.get("tier") is not None:
        extra += f' data-t="{rec["tier"]}"'
    extra += f' data-old740="{rec.get("old740_line") or ""}" data-current698="{rec.get("current698_line") or ""}"'
    extra += f' data-currentline="{rec.get("current_line") or ""}" data-currentlist="{rec.get("current_list_size") or ""}"'
    aid = rec.get("aid") or f'm{rec.get("line")}'
    return (f' id="{aid}" data-tm="{esc(rec["tm"])}" data-b="{b or rec["bucket"]}" data-c="{esc(rec["class"])}"{extra}'
            f' data-o="{order}" data-l="{rec.get("line") or ""}" data-ls="{_lsort(rec)}" data-e="{rec["eqv"]}"'
            f' data-sim="{rec["sim"]}" data-r="{rank_sort(rec["rank"])}"')


def live_html(rec: dict) -> str:
    """The 'working' badge: files changed in the last LIVE_MIN min at build time; the JS hides it once that is
    no longer true on the viewer's clock (it can only expire: new work needs a rebuild)."""
    if not rec.get("live") or rec["bucket"] in KILL_BUCKETS:
        return ""
    return (f'<span class="live" data-ts="{int(rec["last_work"])}" title="files in machines/&lt;tm&gt;/ changed '
            f'in the {LIVE_MIN} min before the build (card renders excluded)">● working at build</span>')


def kill_facts_html(rec: dict) -> str:
    """A kill's facts line: lines and KB of the .v, compile time, coqchk, axioms, the first PASS (and the latest
    re-run), and "from #3" for a derived kill with a rank of its own."""
    k = rec.get("kill", {})
    facts = []
    if k.get("v_lines"):
        facts.append(f'<b>{k["v_lines"]:,}</b> lines · {k["v_bytes"] / 1024:.0f} KB .v')
    if k.get("compile_s") is not None:
        facts.append(f'compile {k["compile_s"]:.1f} s')
    if k.get("coqchk"):
        facts.append(f'coqchk {esc(k["coqchk"])}')
    if k.get("assumptions") is not None:
        facts.append(f'{k["assumptions"]} axioms')
    if k.get("result") and k["result"] != "PASS":
        facts.append(f'<span class="bad">latest check_kill {esc(k["result"])}</span>')
    if k.get("first"):
        rerun = k.get("when_ts") and k["when_ts"] - k["first_ts"] > 60
        facts.append(f'PASS {esc(k["first"])}' + (f' <span class="muted" title="latest check_kill run">'
                                                 f'(re-run {esc(k["when"])})</span>' if rerun else ""))
    if rec.get("parent") and rec["rank"]:                # without a rank the head already says "twin of"
        pr = rank_label(rec.get("parent_rank")) or "parent"
        facts.append(f'<span title="{esc(rec["parent"])}">from {esc(pr)}</span>')
    return (f'<div class="kf" title="from {esc(k.get("check_file", "check_kill.txt"))}">'
            f'{" · ".join(facts)}</div>')


def reason_html(rec: dict) -> str:
    """The first sentences of the status reason ('progress' for an active machine, else 'status'); full text in
    the tooltip."""
    b = rec["bucket"]
    line = _first_sentences(rec["reason"], 300 if b == "active" else 200) or \
        ("no status.json yet: observing" if not rec.get("has_status") else "")
    if not line:
        return ""
    two = " two" if b == "waiting" else ""
    return (f'<div class="tpr{two}" title="{esc(rec["reason"])}"><span class="lk">'
            f'{"progress" if b == "active" else "status"}</span> {C.rich(line)}</div>')


def last_change_html(rec: dict, now: float) -> str:
    """'last change / idle since <when>' (the newest file in the folder; the ledger row in the tooltip)."""
    if not rec.get("last_work"):
        return ""
    lg = rec.get("ledger")
    lt = (f' · ledger {lg["time"]}: {lg["action"]}' + (f' ({lg["workflow"]})' if lg["workflow"] else "")) \
        if lg else ""
    lw = int(rec["last_work"])
    return (f'<div class="tlw" title="newest file in machines/&lt;tm&gt;/ (card renders excluded)'
            f'{esc(lt)}"><span class="lwk" data-ts="{lw}">'
            f'{"last change" if rec.get("live") else "idle since"}</span> {ago_html(lw, now)}'
            f'{" · status.json " + esc(rec["updated"]) if rec.get("updated") else ""}</div>')


def ask_html(rec: dict, also: bool = False) -> str:
    """The call proof work waits on (or the Checkpoint A questions), with a link to the machine page."""
    lab = "also for you" if also else "your call"
    page = _rel_machine(rec["tm"], "index.html")
    if rec["ask"]:
        return (f'<div class="ask"><span class="lk">{lab}</span> {C.rich(rec["ask"])} '
                f'<a href="/busy-beaver/tools/</span><span class="si">{esc(page)}">open its page →</a></div>')
    conf = {"med": "medium", "low": "low"}.get(rec.get("confidence") or "", rec.get("confidence") or "?")
    qs = "".join(f'<li><b>Q{n}</b> {C.rich(q)}</li>' for n, q in rec["questions"])
    return (f'<div class="ask"><span class="lk">{"also: " if also else ""}Checkpoint A</span> {conf} confidence in '
            f'the mechanism; answer under <a href="/busy-beaver/tools/</span><span class="si">{esc(page)}#mechanism">Mechanism on its page →</a> (the figures '
            f'are there)<ul class="aq">{qs}</ul></div>')


def tile_mini(rec: dict, order: int, tag: str = "") -> str:
    """An untouched holdout in the Machines page's grid: picture, class, chips, the machine string, links."""
    return (f'<article class="t mini"{_data_attrs(rec, order, tag=tag)}>{thumb_html(rec, 128, 160)}'
            f'{class_html(rec, True)}{table_chip(rec)}{eq_chip(rec)}{meta_html(rec, rank=True)}{_tm_html(rec["tm"], "tmn sm")}'
            f'{links_html(rec, short=True)}</article>')


# ----------------------------------------------------------------------------------------------- the site's buckets

# The 7 buckets of the site (sitekit.BUCKETS7: the dashboard buckets with the parked cryptid candidates split off)
# plus untouched: key, tile name, Machines heading, icon, short meaning (tile), one-line meaning (tooltip, heading).
TILES = (
    ("accepted", "Kills claimed", "Kills claimed", "★", "our proof accepted upstream", BUCKETS[0][4]),
    ("submitted", "PR submitted", "PR submitted", "↑", "PR open · awaiting verification",
     BUCKETS[1][4]),
    ("claimed", "Unsubmitted proofs", "Locally proved · unsubmitted", "!",
     "check_kill PASS · not submitted", BUCKETS[2][4]),
    ("active", "Open (in pipeline)", "Open (in pipeline)", "●", "mid-pipeline · ● = being worked on now",
     BUCKETS[3][4]),
    ("waiting", "Waiting on you", "Waiting on you", "?", "your call or Checkpoint A answers", BUCKETS[4][4]),
    ("parked", "Parked", "Parked (deferred)", "▲", "stuck · skipped", "stuck or skipped, with no question for you"),
    ("cryptid", "Cryptid candidate", "Cryptid candidates (parked)", "⚠", "cryptid candidate, parked",
     "the rules involve pseudo-random arithmetic (CLAUDE.md's cryptid protocol: formalize the rules, flag, stop); "
     "parked, with no question for you"),
    ("untouched", "Untouched", "Untouched", "○", "no machines/<tm>/ folder yet", BUCKETS[6][4]),
)
TILES += tuple((b[0], b[2], b[1], b[3], b[5], b[4]) for b in BUCKETS if b[0] in ("upstream_overlap", "external_solved", "competing_pr", "external_pending"))
# Publication work and missed claims stay above the untouched inventory.
_display_order = ("accepted", "submitted", "claimed", "active", "waiting", "parked", "cryptid",
                  "external_pending", "external_solved", "competing_pr", "upstream_overlap", "untouched")
TILES = tuple(next(t for t in TILES if t[0] == key) for key in _display_order)
TILE = {t[0]: t for t in TILES}
KEYS8 = [t[0] for t in TILES]
BUCKET_ICON["cryptid"] = "⚠"
RECENT_DAYS = 4           # Home: events of the last 4 days ...
RECENT_MAX = 12           # ... at most 12 of them
LEDGER_ROWS = 6           # Home: the last rows of reports/overnight-ledger.md
LEDGER_CHARS = 220


def bucket7(rec: dict) -> str:
    return S.bucket7(rec)


def _by7(recs: list[dict]) -> dict[str, list[dict]]:
    by = {k: [] for k in KEYS8}
    for r in recs:
        by[bucket7(r)].append(r)
    return by


def _mhref(tm: str, frag: str = "") -> str:
    """A machine page from a page in dashboard/."""
    return S.machine_href(tm, "dashboard") + frag


def _tag_link(names: S.Names, tm: str, href: str | None) -> str:
    """Just the tag (#3, W4-3, line 604) as a link, the full string in the tooltip: for tight places."""
    tag, tip = names.label(tm)
    if not href:
        return f'<span class="tgl" title="{esc(tip)}">{esc(tag)}</span>'
    return f'<a class="tgl" href="/busy-beaver/tools/</span><span class="si">{esc(href)}" title="{esc(tip)}">{esc(tag)}</a>'


def _rel_root(p: Path) -> str:
    p = Path(p)
    return str(p.relative_to(ROOT)) if p.is_relative_to(ROOT) else str(p)


def _pr_a(s: dict) -> str:
    no = f'#{s["no"]}' if s.get("no") else ""
    return f'<a href="/busy-beaver/tools/</span><span class="si">{esc(s["pr"])}">PR {esc(no)}</a>'


def _prs(repo) -> dict:
    """The PRs: url -> build_records' entry (state, no, pr_state, opened, merged_at/by, machines)."""
    return repo.meta.get("prs") or {}


def kill_key(key: str, rs: list[dict], meta: dict) -> str:
    """The line under a kill bucket's heading: the PR behind it, or what the claimed kills wait for."""
    prs = [p for p in (meta.get("prs") or {}).values()]
    n_list = meta["n"]
    if key == "accepted":
        parts = []
        for p in prs:
            if p["state"] != "accepted":
                continue
            files = sorted({r["sub"]["file"] for r in rs if r["sub"].get("pr") == p["pr"] and r["sub"].get("file")})
            when = _iso_short(p.get("merged_at"))
            parts.append(f'{_pr_a(p)} merged{" " + esc(when) if when else ""}'
                         f'{" by " + esc(p["merged_by"]) if p.get("merged_by") else ""}'
                         + (f' · upstream file{"s" if len(files) > 1 else ""} '
                            + ", ".join(f"<code>{esc(f)}</code>" for f in files) if files else ""))
        off = sum(1 for r in rs if r.get("off"))
        tail = (f' {"It is" if off == 1 else "They are"} off the {n_list} list because of it.' if off else "")
        return f'<p class="key">{"; ".join(parts)}.{tail}</p>' if parts else ""
    if key == "submitted":
        parts = []
        for p in prs:
            if p["state"] != "submitted":
                continue
            k = [r for r in rs if r["sub"].get("pr") == p["pr"]]
            bits = [f'{_pr_a(p)} {esc(p.get("pr_state") or "state not synced")}'
                    + (f' since {esc(p["opened"])}' if p.get("opened") else ""),
                    f'{len(k)} machine{"s" if len(k) != 1 else ""} ({esc(", ".join(member_name(r) for r in k))})']
            if p.get("posted_date"):
                bits.append(f'posted on Discord {esc(p["posted_date"])}')
            nc = [r["sub"]["comments"] for r in k if "comments" in r["sub"]]
            if nc:
                c = max(nc)
                bits.append(f'<b class="pcn">{c} comments/reviews: read the PR</b>' if c else
                            '0 comments or reviews yet')
            parts.append(" · ".join(bits))
        return (f'<p class="key">{"; ".join(parts)}. Waiting for the maintainers to check and merge; PR state as of '
                f'the last <code>python3 -B tools/pr_sync.py</code>.</p>') if parts else ""
    if key == "claimed":
        ready = sum(packaging_ready(r) for r in rs)
        return (f'<p class="key">{ready} ready for PR; {len(rs) - ready} need packaging. '
                'Submit verified packages early. A local proof enters the claimed total when our PR is accepted.</p>')
    return ""


def _default_order(recs: list[dict]) -> list[dict]:
    def k(r):
        if r["bucket"] in LOCAL_PROOF_BUCKETS:
            return (0, r.get("kill_no") or 999, _lsort(r))
        if r["bucket"] == "untouched":
            return (1, r.get("tier", 3), rank_sort(r["rank"]), _lsort(r))
        return (0, rank_sort(r["rank"]), _lsort(r))
    return sorted(recs, key=k)


def list_line(meta: dict, off_href: str = "machines.html#off") -> str:
    """'740 holdouts (current list) · +2 off the list · previous list 778 (38 gone) · 1,526 with equivalents ·
    sim pending 130 / 35' (the list facts both pages show)."""
    offs = meta.get("off_list") or []
    n, pend = meta["n"], meta["pending"]
    bits = [f'<b>{n} holdouts (current list)</b> <code>{esc(meta["list"].name)}</code>']
    if offs:
        bits.append(f'<a href="/busy-beaver/tools/</span><span class="si">{esc(off_href)}" title="historical machines and mapped upstream results not on the current '
                    f'list, shown in their bucket with the reason">+{len(offs)} off the list</a>')
    if meta.get("prev"):
        bits.append(f'previous list {meta["n_prev"]} (<code>{esc(meta["prev"].name)}</code>; {meta["prev_gone"]} '
                    f'gone since)')
    bits.append(f'{meta["eqv_total"]:,} with equivalents')
    bits.append(f'<span title="sheet Direct Simulation tab: {pend[14]} of the {n} not yet simulated to 1e14; '
                f'{pend[15] - pend[14]} more simulated to 1e14 but not to 1e15">sim pending {pend[14]} / '
                f'{pend[15] - pend[14]}</span>')
    return " · ".join(bits)


# ----------------------------------------------------------------------------------------------- Home

COPY_JS = r"""
(function(){
 function copyText(t,b){
  function ok(){var o=b.getAttribute('data-t')||b.textContent;b.setAttribute('data-t',o);b.textContent='copied';
   setTimeout(function(){b.textContent=o},1200)}
  function fb(){var a=document.createElement('textarea');a.value=t;a.style.position='fixed';a.style.opacity='0';
   document.body.appendChild(a);a.select();try{document.execCommand('copy');ok()}catch(e){}document.body.removeChild(a)}
  if(navigator.clipboard&&window.isSecureContext){navigator.clipboard.writeText(t).then(ok,fb)}else{fb()}
 }
 document.querySelectorAll('button.copy[data-copy]').forEach(function(b){b.hidden=false;
  b.addEventListener('click',function(){var e=document.getElementById(b.getAttribute('data-copy'));if(e)copyText(e.textContent,b)})});
})();
"""

# Home's tiles count the "working now" machines of their bucket from their timestamps (no rows on this page).
def _event_ts(s: str) -> tuple[float | None, bool]:
    """An ISO time or a bare date -> (timestamp, has a time of day?). A bare date counts from its local midnight."""
    s = _str(s)
    m = re.match(r"\d{4}-\d{2}-\d{2}", s)
    if not m:
        return None, False
    if re.match(r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}", s):
        t = _ts(s[:19] + ("Z" if s.rstrip().endswith("Z") else ""))
        if t:
            return t, True
    try:
        return _dt.datetime.fromisoformat(m.group(0)).timestamp(), False
    except ValueError:
        return None, False


def _decision_events(mdir: Path) -> list[tuple[str, str, dict]]:
    """(date, kind, decision) for every call of a machine: decision.json (filed / answered) and decisions/*.json
    (answered, archived)."""
    out = []
    files = [mdir / "decision.json"] + sorted((mdir / "decisions").glob("*.json"))
    for p in files:
        if not p.is_file():
            continue
        try:
            d = json.loads(p.read_text(encoding="utf-8"))
        except (OSError, ValueError):
            continue
        if not isinstance(d, dict):
            continue
        ans = d.get("answer") if isinstance(d.get("answer"), dict) else None
        if ans and _str(ans.get("date")):
            out.append((_str(ans["date"]), "answered", d))
        if p.name == "decision.json" and _str(d.get("updated")):
            out.append((_str(d["updated"]), "filed", d))
    return out


def recent_events(repo, days: int = RECENT_DAYS, limit: int = RECENT_MAX) -> list[dict]:
    """What changed in the last `days` days, newest first, at most `limit`: kills verified (the first check_kill
    PASS), PRs merged and opened, status changes (status.json 'updated'; its file time when that is the same day),
    calls filed and answered (decision.json, decisions/*.json). [{ts, timed, kind, label, tms, html}]."""
    now = repo.now
    cut = now - days * 86400
    ev: list[dict] = []

    def add(ts, timed, kind, label, tms, html_):
        if ts and cut <= ts <= now + 3600:
            ev.append({"ts": ts, "timed": timed, "kind": kind, "label": label, "tms": tms, "html": html_})
    names = repo.names
    for r in repo.recs:
        if r["bucket"] == "untouched":
            continue
        tm = r["tm"]
        k = r.get("kill") or {}
        if k.get("first_ts"):
            what = "halts" if r["status"] == "KILLED_HALT" else "never halts"
            add(k["first_ts"], True, "kill", "kill verified",
                [tm], f'kill {r.get("kill_no") or "?"}: check_kill PASS, it {what}')
        elif r.get("updated"):
            ts, timed = _event_ts(r["updated"])
            stp = repo.machines / tm / "status.json"
            try:
                mt = stp.stat().st_mtime
                if ts and _dt.date.fromtimestamp(mt) == _dt.date.fromtimestamp(ts):
                    ts, timed = mt, True
            except OSError:
                pass
            line = _first_sentences(r.get("reason") or "", 160)
            add(ts, timed, "status", "status", [tm],
                f'{C.status_chip(r["status"] or None)} {C.rich(line)}' if line else C.status_chip(r["status"] or None))
        for date, kind, d in _decision_events(repo.machines / tm):
            ts, timed = _event_ts(date)
            q = _str(d.get("question"))
            if kind == "answered":
                a = d["answer"]
                txt = f'call answered: <b>{esc(_str(a.get("option")) or "a note")}</b>' + \
                      (f' · {C.rich(_first_sentences(q, 140))}' if q else "")
            else:
                txt = "call filed" + (f': {C.rich(_first_sentences(q, 160))}' if q else "")
            add(ts, timed, "call", f"call {kind}", [tm], txt)
    for p in _prs(repo).values():
        no = f'#{p["no"]}' if p.get("no") else "PR"
        tms = list(p.get("machines") or [])
        if p.get("merged_at"):
            ts, timed = _event_ts(p["merged_at"])
            add(ts, timed, "merged", "PR merged", tms,
                f'{_pr_a(p)} merged into busycoq' + (f' by {esc(p["merged_by"])}' if p.get("merged_by") else ""))
        if p.get("opened"):
            ts, timed = _event_ts(p["opened"])
            add(ts, timed, "opened", "PR opened", tms, f'{_pr_a(p)} opened')
    ev.sort(key=lambda e: -e["ts"])
    return ev[:limit]


def _ledger_tail(repo, n: int = LEDGER_ROWS) -> list[dict]:
    """The last n rows of reports/overnight-ledger.md: {time, action, machines (html, tokens linked)}."""
    path = repo.root / "reports" / "overnight-ledger.md"
    if not path.is_file():
        path = LEDGER
    try:
        text = path.read_text(encoding="utf-8")
    except OSError:
        return []
    names = repo.names
    tok: dict[str, str] = {}
    for tm in repo.dirs:
        tag = names.tag(tm)
        if _TAG_EXACT.match(tag):
            tok.setdefault(tag, tm)
        lab = _str(names.status.get(tm, {}).get("label"))
        if lab:
            tok.setdefault(lab, tm)
    for tm, r in load_ranks(TARGETING).items():
        tok.setdefault(rank_label(r), tm)
    rows = []
    for m in _LEDGER_ROW.finditer(text):
        t, action, mach, wf = m.groups()
        if t in ("time", "---") or set(t) <= {"-", ":"}:
            continue
        rows.append((t, action, mach, wf))
    out = []
    rx = re.compile(r"(?<![\w#-])(#\d+[a-z]?|R\d+|[A-Z]\d*-\d+[a-z]?)(?![\w-])")
    def link(mm):
        tm = tok.get(mm.group(1))
        if tm and tm in repo.dirs:
            return f'<a href="/busy-beaver/tools/</span><span class="si">{esc(_mhref(tm))}" title="{esc(tm)}">{esc(mm.group(1))}</a>'
        return esc(mm.group(1))
    for t, action, mach, wf in rows[-n:][::-1]:
        parts, i = [], 0
        for mm in rx.finditer(mach):                  # the machine tokens linked, the rest escaped
            parts.append(esc(mach[i:mm.start()]))
            parts.append(link(mm))
            i = mm.end()
        parts.append(esc(mach[i:]))
        act = " ".join(action.split())
        cut_ = len(act) > LEDGER_CHARS
        out.append({"time": t.replace("_", " "), "action": act[:LEDGER_CHARS].rstrip() + (" …" if cut_ else ""),
                    "full": act if cut_ else "", "machines": "".join(parts) if mach.strip() not in ("-", "") else "",
                    "workflow": wf if wf not in ("-", "") else ""})
    return out


def latest_report(repo) -> Path | None:
    """The newest reports/overnight-20*.md (not a plan, not the ledger); sitekit.Repo.reports[0] when it exists."""
    try:
        reps = repo.reports
    except Exception:                             # no Reports registry (yet): look for the file here
        reps = None
    if reps:
        first = reps[0]
        p = first.get("path") if isinstance(first, dict) else first
        if p:
            p = Path(p) if Path(p).is_absolute() else repo.root / p
            if p.is_file():
                return p
    cands = [p for p in (repo.root / "reports").glob("overnight-20*.md")
             if not re.search(r"-(plan|ledger)", p.name)]
    return max(cands, key=lambda p: (p.stat().st_mtime, p.name)) if cands else None


def _md_title(p: Path) -> str:
    try:
        for line in p.read_text(encoding="utf-8", errors="replace").splitlines():
            if line.startswith("# "):
                return line[2:].strip()
    except OSError:
        pass
    return p.name


def _nb(cls: str, title: str, sub: str, body: str, go: tuple[str, str] | None = None, bid: str = "") -> str:
    """One block of 'Needs you'."""
    g = f'<a class="go" href="/busy-beaver/tools/</span><span class="si">{esc(go[0])}">{esc(go[1])}</a>' if go else ""
    s = f'<span class="gm">{sub}</span>' if sub else ""
    i = f' id="{bid}"' if bid else ""
    return f'<div class="nb {cls}"{i}><h3>{esc(title)}{s}{g}</h3>{body}</div>'


def needs_html(repo, by7: dict[str, list[dict]], kinds: set[str] | None = None) -> tuple[str, int]:
    """The detailed 'Needs you' blocks: open decisions (dec), calls proof work waits on (wait), PRs with comments and
    Discord texts to post (pr), kills ready to submit (ready), other calls (also), unanswered Checkpoint A questions
    (q), the Discord question drafts (dq). kinds: only these. (html, blocks shown)."""
    names, recs, meta = repo.names, repo.recs, repo.meta
    by_tm = repo.by_tm
    blocks = []
    urgent = 0                                  # open decisions, waiting machines, PR comments, Discord to post
    # 1. open decisions (the queue), with Claude's recommendation
    od = repo.open_decisions
    if od:
        import decisions as DEC
        items = []
        for tm, q in od:
            rec_txt = ""
            try:
                ent = DEC.analyze(repo.machines / tm, out_dir=repo.out)
                dec = ent.get("dec")
                if dec and dec.get("recommended"):
                    lab = next((o["label"] for o in dec["options"] if o["id"] == dec["recommended"]), "")
                    rec_txt = (f'<div class="nr"><span class="lk">recommended</span> <b>{esc(dec["recommended"])}</b>'
                               f'{" · " + C.rich(lab) if lab else ""}</div>')
                q = q or (dec or {}).get("question")
            except Exception:                     # the queue page says what is wrong; Home only points there
                pass
            qh = C.rich(q) if q else '<span class="bad">decision.json unreadable</span>'
            items.append(f'<li>{names.name_html(tm, f"decisions.html#tm-{quote(tm)}")}<div class="nq">{qh}</div>'
                         f'{rec_txt}</li>')
        urgent += 1
        blocks.append(_nb("dec", f"Open decisions ({len(od)})",
                          "Claude's recommendation is pre-selected on the Decisions page",
                          f'<ul class="nl">{"".join(items)}</ul>', ("decisions.html", "Decisions →")))
    # 2. machines whose proof work waits on a call or on Checkpoint A answers
    wait = by7["waiting"]
    if wait:
        items = "".join(f'<li>{names.name_html(r["tm"], _mhref(r["tm"]))}{ask_html(r)}</li>' for r in wait)
        urgent += 1
        blocks.append(_nb("wait", f"Waiting on you ({len(wait)})", "proof work on these waits for your answer",
                          f'<ul class="nl">{items}</ul>', ("machines.html#b-waiting", "on Machines →")))
    # 3. PRs with comments or reviews to answer; 4. open PRs whose Discord text is not posted
    prs = sorted(_prs(repo).values(), key=lambda p: -(p.get("no") or 0))
    answer, post = [], []
    for p in prs:
        if p["state"] != "submitted":
            continue
        ms = [by_tm[t] for t in p.get("machines") or [] if t in by_tm]
        tags = ", ".join(_tag_link(names, r["tm"], _mhref(r["tm"])) for r in ms)
        no = f'#{p["no"]}' if p.get("no") else ""
        nc = max([(r.get("sub") or {}).get("comments") or 0 for r in ms] or [0])
        if nc:
            answer.append(f'<li>{_pr_a(p)} <b class="pcn">{nc} comment{"s" if nc != 1 else ""}/reviews</b> · {tags} · '
                          f'<a href="/busy-beaver/tools/</span><span class="si">{esc(p["pr"])}">read the PR ↗</a></li>')
        if not any((r.get("sub") or {}).get("posted") for r in ms):
            post.append(f'<li>{_pr_a(p)} is open, its Discord text is not posted · {tags} · '
                        f'<a href="/busy-beaver/tools/submissions.html#pr-</span><span class="si">{p.get("no") or ""}">copy it on Submissions →</a></li>')
    urgent += bool(answer) + bool(post)
    if answer:
        blocks.append(_nb("pr", f"PRs to answer ({len(answer)})", "comments or reviews at the last "
                          "<code>python3 -B tools/pr_sync.py</code>", f'<ul class="nl">{"".join(answer)}</ul>'))
    if post:
        blocks.append(_nb("pr", f"Discord to post ({len(post)})", "no machine of the PR has status.json "
                          "<code>posted</code>", f'<ul class="nl">{"".join(post)}</ul>',
                          ("submissions.html", "Submissions →")))
    # 5. claimed kills, ready to submit, by family
    claimed = [r for r in by7["claimed"] if packaging_ready(r)]
    if claimed:
        fams: dict[str, list[dict]] = {}
        for r in sorted(claimed, key=lambda r: r.get("kill_no") or 999):
            fams.setdefault(r.get("fam") or r["tm"], []).append(r)
        items = []
        for lead, g in fams.items():
            lead_tag = g[0].get("fam_name") or names.tag(g[0]["tm"])
            members = ", ".join(_tag_link(names, r["tm"], _mhref(r["tm"])) for r in g)
            cls = g[0]["class"] or "class ?"
            items.append(f'<li><span class="fn">Family of {esc(lead_tag)}</span> <span class="muted">'
                         f'{esc(cls)}</span> · {members}</li>')
        blocks.append(_nb("ready", f"Ready for PR ({len(claimed)} proof{'s' if len(claimed) != 1 else ''})",
                          f"{len(fams)} famil{'ies' if len(fams) != 1 else 'y'}",
                          kill_key("claimed", claimed, meta) + f'<ul class="nl fams">{"".join(items)}</ul>',
                          ("submissions.html#ready", "packages on Submissions →")))
    # other calls on file (work goes on): a funded call, and the machines another call names
    also = [r for k in ("active", "parked", "cryptid") for r in by7[k] if r["ask"] or r["questions"]]
    if also:
        items = []
        for r in also:
            via = [x for x in recs if any(v["tm"] == r["tm"] for v in x.get("ask_via") or [])]
            cov = (f'<div class="nr">the call also covers {", ".join(_tag_link(names, x["tm"], _mhref(x["tm"])) for x in via)}'
                   f'</div>' if via else "")
            items.append(f'<li>{names.name_html(r["tm"], _mhref(r["tm"]))}{ask_html(r, also=True)}{cov}</li>')
        blocks.append(_nb("also", f"Other calls on file ({len(also)})", "work goes on; your answer redirects it",
                          f'<ul class="nl">{"".join(items)}</ul>'))
    # 6. unanswered Checkpoint A questions
    qr = [r for r in recs if r.get("open_q")]
    if qr:
        nq = sum(len(r["open_q"]) for r in qr)
        nwait = sum(len(r["open_q"]) for r in qr if bucket7(r) == "waiting")
        nkill = sum(len(r["open_q"]) for r in qr if r["bucket"] in KILL_BUCKETS)
        parts = [f"{nwait} block work (waiting on you)" if nwait else "none blocks work"]
        if nkill:
            parts.append(f"{nkill} on kills, where they are optional")
        groups = []
        for key in KEYS8:
            g = [r for r in qr if bucket7(r) == key]
            if g:
                groups.append(f'<li><span class="lk">{esc(TILE[key][1])}</span> ' + ", ".join(
                    f'{_tag_link(names, r["tm"], _mhref(r["tm"], "#mechanism"))}<span class="muted">×{len(r["open_q"])}</span>'
                    for r in g) + "</li>")
        body = (f'<details class="nd"><summary>{nq} question{"s" if nq != 1 else ""} on {len(qr)} machine'
                f'{"s" if len(qr) != 1 else ""} · {esc("; ".join(parts))}</summary><ul class="nl qs">'
                f'{"".join(groups)}</ul><p class="muted">Each link opens the machine\'s Mechanism, where the '
                f'questions sit next to the figures.</p></details>')
        blocks.append(_nb("q", "Checkpoint A questions", "non-blocking unless the machine waits on you", body))
    # 7. Discord question drafts (observe.json discord_check), each distinct message once
    drafts: dict[str, dict] = {}
    for r in recs:
        if r.get("discord"):
            msg = C.discord_message(r["discord"], repo.machines / r["tm"])
            drafts.setdefault(msg["text"], {"msg": msg, "tms": []})["tms"].append(r["tm"])
    if drafts:
        items = []
        for i, item in enumerate(drafts.values()):
            msg, uid = item["msg"], f"dq{i}"
            who = ", ".join(_tag_link(names, t, _mhref(t, "#mechanism")) for t in item["tms"])
            name = f"Message {msg['n']}" if msg["n"] else "Message"
            title = f' <span class="muted">· {esc(msg["title"])}</span>' if msg["title"] else ""
            items.append(f'<div class="dqi"><div class="it"><b>{esc(name)}</b>{title}<span>for {who}</span>'
                         f'<button type="button" class="copy" data-copy="{uid}" hidden>copy</button></div>'
                         f'<pre id="{uid}">{esc(msg["text"])}</pre></div>')
        blocks.append(_nb("dq", "Discord question drafts", "",
                          f'<details class="nd"><summary>{len(drafts)} draft{"s" if len(drafts) != 1 else ""}, not '
                          f'posted (observe.json <code>discord_check</code>)</summary>{"".join(items)}</details>'))
    if kinds is not None:
        blocks = [b for b in blocks if re.match(r'<div class="nb (\w+)"', b).group(1) in kinds]
    elif not urgent:
        blocks.insert(0, '<p class="none">Nothing needs you right now: no open decision, no machine waits on you, no '
                         'PR comment to answer and no Discord text to post.</p>')
    return "".join(blocks), len(blocks)


HOME_RECENT = 8            # Home: the last 8 events (kills, PRs and calls first)
LEARN_HREF = "../learn/index.html"
ICONS = {
    "machines": '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" '
                'stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" '
                'height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" '
                'height="7" rx="1.5"/></svg>',
    "learn": '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" '
             'stroke-linejoin="round"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/>'
             '<path d="M4 20.5A2.5 2.5 0 0 0 6.5 23H20v-5"/><path d="M9 8h7M9 12h5"/></svg>',
}


def kill_counts(repo) -> dict:
    """The hero's numbers: kills by upstream state (all, and those on the current list), the other buckets."""
    by7 = _by7(repo.recs)
    on = {k: sum(1 for r in by7[k] if r.get("line")) for k in LOCAL_PROOF_BUCKETS}
    return {"by7": by7, "n": {k: len(by7[k]) for k in by7}, "on": on, "list_n": repo.meta["n"],
            "kills": sum(len(by7[k]) for k in LOCAL_PROOF_BUCKETS)}


def home_needs(repo, by7: dict) -> list[dict]:
    """Only what Dennis can act on, one link each: open decisions, machines waiting on his call, PRs with comments,
    Discord texts to post, claimed kills ready to submit."""
    names, out = repo.names, []
    dec_tms = set()
    for tm, q in repo.open_decisions:
        if repo.by_tm.get(tm, {}).get("bucket") in SOLVED_BUCKETS:
            continue
        dec_tms.add(tm)
        out.append({"ico": ("i-dec", "?"), "tag": names.tag(tm), "tip": tm, "title": "Make a call",
                    "text": S.clip(q or "decision.json is unreadable", 150),
                    "link": (f"decisions.html#tm-{quote(tm)}", "Decide"), "primary": True})
    for r in by7["waiting"]:
        if r["tm"] in dec_tms:
            continue
        ask = r.get("ask") or ""
        if not ask and r.get("questions"):
            ask = f'{len(r["questions"])} Checkpoint A question{"s" if len(r["questions"]) != 1 else ""} block proof work'
        out.append({"ico": ("i-wait", "!"), "tag": names.tag(r["tm"]), "tip": r["tm"], "title": "Waiting on your answer",
                    "text": S.clip(ask, 150), "link": (_mhref(r["tm"], "#needs"), "Open"), "primary": False})
    prs = sorted(_prs(repo).values(), key=lambda p: -(p.get("no") or 0))
    post = []
    for p in prs:
        if p["state"] != "submitted":
            continue
        ms = [repo.by_tm[t] for t in p.get("machines") or [] if t in repo.by_tm]
        nc = max([(r.get("sub") or {}).get("comments") or 0 for r in ms] or [0])
        if nc:
            out.append({"ico": ("i-pr", "↩"), "tag": f'PR #{p.get("no")}', "tip": "", "title": "Reply on GitHub",
                        "text": f'{nc} comment{"s" if nc != 1 else ""} or review{"s" if nc != 1 else ""} since the last '
                                f'sync', "link": (p["pr"], "Read"), "primary": False})
        if not any((r.get("sub") or {}).get("posted") for r in ms):
            post.append(p)
    if post:
        nos = ", ".join(f'#{p.get("no")}' for p in post)
        out.append({"ico": ("i-post", "↗"), "tag": "", "tip": "",
                    "title": f"Post {len(post)} Discord text{'s' if len(post) != 1 else ''}",
                    "text": f"PR {nos} {'is' if len(post) == 1 else 'are'} open upstream; the announcement is ready to "
                            f"copy.", "link": (f"submissions.html#pr-{post[0].get('no') or ''}", "Copy"),
                    "primary": False})
    claimed = [r for r in by7["claimed"] if packaging_ready(r)]
    if claimed:
        fams = {r.get("fam") or r["tm"] for r in claimed}
        out.append({"ico": ("i-ready", "✓"), "tag": "", "tip": "",
                    "title": f"{len(claimed)} proof{'s' if len(claimed) != 1 else ''} ready for PR",
                    "text": f"Verified here and packaged in {len(fams)} famil{'ies' if len(fams) != 1 else 'y'}; "
                            f"submit verified packages early.", "link": ("submissions.html#ready", "Prepare PRs"), "primary": True})
    pending = [r for r in by7["claimed"] if not packaging_ready(r)]
    if pending:
        out.append({"ico": ("i-ready", "✓"), "tag": "", "tip": "",
                    "title": f"{len(pending)} local proof needs packaging",
                    "text": "Audited proof available; complete the submission package before publication.",
                    "link": ("submissions.html#packaging", "Packaging"), "primary": False})
    out.sort(key=lambda item: item["ico"][0] != "i-ready")
    return out


def home_recent(repo, n: int = HOME_RECENT) -> list[dict]:
    """The last n events (kills, PRs, status changes, calls), one line each; events of the same kind and status
    within 15 minutes of each other are one line. Kills, PRs and calls always make the list (the newest 4)."""
    names, now = repo.names, repo.now
    ev = recent_events(repo, days=10, limit=80)
    rows: list[dict] = []
    for e in ev:
        tms = e["tms"]
        r = repo.by_tm.get(tms[0], {}) if tms else {}
        if e["kind"] == "kill":
            tone = "warn"
            text = (f'→ <b class="t-warn">Locally proved</b> · local proof {r.get("kill_no") or "?"}, '
                    f'{"halts" if r.get("status") == "KILLED_HALT" else "never halts"}')
            key = ("kill", e["ts"])
        elif e["kind"] in ("merged", "opened"):
            m = re.search(r"PR #(\d+)", e["html"])
            no = f"#{m.group(1)}" if m else ""
            tone = "ok" if e["kind"] == "merged" else "accent"
            text = f'→ <b class="t-{tone}">{"Kill claimed" if e["kind"] == "merged" else "PR submitted"}</b> · PR {no}'
            key = (e["kind"], no)
        elif e["kind"] == "status":
            tone, lab = S.STATUS_PILL.get(r.get("status") or "", ("muted", r.get("status") or "status"))
            first = S.sentences(S.plain(r.get("reason") or ""))
            text = f'→ <b class="t-{tone}">{esc(lab)}</b>' + (f' · {esc(S.clip(first[0], 140))}' if first else "")
            key = ("status", r.get("status"), (first or [""])[0][:40])
        else:
            rest_ = re.sub(r"^call (?:answered|filed):?\s*", "", S.plain(e["html"]))
            tone = "accent"
            text = (f'→ <b class="t-accent">{esc(e["label"].capitalize())}</b>'
                    + (f' · {esc(S.clip(rest_, 140))}' if rest_ else ""))
            key = ("call", e["label"])
        if rows and rows[-1]["key"] == key and abs(rows[-1]["ts"] - e["ts"]) < 900:
            for t in tms:
                if t not in rows[-1]["tms"]:
                    rows[-1]["tms"].append(t)
            continue
        rows.append({"key": key, "ts": e["ts"], "timed": e["timed"], "tone": tone, "text": text, "tms": list(tms)})
    big = [x for x in rows if x["key"][0] != "status"][:4]
    rest = [x for x in rows if x["key"][0] == "status"][:max(0, n - len(big))]
    out = []
    for x in sorted(big + rest, key=lambda x: -x["ts"]):
        tags = [f'<a class="hm-who" href="/busy-beaver/tools/</span><span class="si">{esc(_mhref(t))}" title="{esc(t)}">{esc(names.tag(t))}</a>' for t in x["tms"][:3]]
        more = f' <span class="ui-muted">+{len(x["tms"]) - 3}</span>' if len(x["tms"]) > 3 else ""
        when = S.ago_short(x["ts"], now) if x["timed"] else _dt.datetime.fromtimestamp(x["ts"]).strftime("%b %-d")
        full = _dt.datetime.fromtimestamp(x["ts"]).strftime("%b %-d %H:%M")
        out.append({"when": when, "full": full, "tone": x["tone"], "html": ", ".join(tags) + more + " " + x["text"],
                    "title": S.plain(x["text"])})
    return out


def _more_html(repo, by7: dict) -> str:
    """Home's fold: the other calls on file, Checkpoint A questions, Discord question drafts, the ledger's last rows,
    the latest report and the list facts (all the detail the old Home showed)."""
    blocks, _n = needs_html(repo, by7, kinds={"also", "q", "dq"})
    rows = _ledger_tail(repo)
    lg = "".join(f'<li><span class="lgt">{esc(r["time"])}</span><span class="lga"'
                 f'{" title=" + chr(34) + esc(r["full"]) + chr(34) if r["full"] else ""}>{esc(r["action"])}</span>'
                 f'{"<span class=lgm>" + r["machines"] + "</span>" if r["machines"] else ""}</li>' for r in rows)
    ledger = (f'<h3 class="hh3">Overnight ledger <span class="gm">the last {len(rows)} rows, newest first · '
              f'<a href="/busy-beaver/reports/overnight-ledger.md.html">the whole ledger</a></span></h3><ul class="lgl">{lg}</ul>'
              if rows else "")
    rep = latest_report(repo)
    rp = ""
    if rep:
        rel = os.path.relpath(rep, repo.out)
        rp = (f'<p class="rpl"><span class="lk">latest report</span> <a href="/busy-beaver/tools/</span><span class="si">{esc(C.url_path(rel))}">'
              f'{esc(_md_title(rep))}</a> <span class="muted">· {esc(_when(rep.stat().st_mtime))} · all reports on '
              f'<a href="/busy-beaver/tools/reports.html">Reports</a></span></p>')
    lst = f'<p class="rpl"><span class="lk">the list</span> {list_line(repo.meta)}</p>'
    return S.fold("More detail", blocks + ledger + rp + lst, "other calls, Checkpoint A questions, Discord drafts, "
                  "the ledger", fid="more")


def render_home(repo) -> str:
    """dashboard/index.html: the summary (#counts), what needs Dennis (#needs), what changed (#recent), the two
    entry cards (Machines, Learn), and the rest of the detail folded (#more)."""
    kc = kill_counts(repo)
    n, on, by7 = kc["n"], kc["on"], kc["by7"]
    list_n = kc["list_n"] or 0
    on_total = sum(on.values())
    pct = 100 * on_total / list_n if list_n else 0
    ready = [r for r in by7["claimed"] if packaging_ready(r)]
    pending = [r for r in by7["claimed"] if not packaging_ready(r)]
    stages = ((len(pending), "Locally proved", "Needs packaging", "submissions.html#packaging" if pending else "submissions.html", "proved"),
              (len(ready), "Ready for PR", "Submit early", "submissions.html#ready", "ready"),
              (n["submitted"], "PR submitted", "Awaiting acceptance", "machines.html#b-submitted", "submitted"),
              (n["accepted"], "Kill claimed", "Our PR accepted", "machines.html#b-accepted", "accepted"))
    flow = '<ol class="claim-flow" aria-label="Proof to claim workflow">' + "".join(
        f'<li class="claim-stage {tone}"><a href="/busy-beaver/tools/</span><span class="si">{href}"><b>{count}</b><span>{label}</span>'
        f'<small>{detail}</small></a></li>' for count, label, detail, href, tone in stages) + '</ol>'
    active = sum(bool(r.get("line")) for k in ("active", "waiting") for r in by7[k])
    parked = sum(bool(r.get("line")) for k in ("parked", "cryptid") for r in by7[k])
    hero = (f'<section class="ui-card hm-hero" id="counts" aria-label="Claimed kills"><div>'
            f'<div class="hm-big"><b>{n["accepted"]}</b><span>kills claimed</span></div>'
            '<p class="claim-definition">Our proofs accepted upstream.</p>'
            f'<a class="ui-link" href="/busy-beaver/tools/machines.html#b-accepted">See claimed kills →</a></div>'
            '<div><h2 class="ui-h2">From proof to claim</h2>' + flow + '</div>'
            f'<div class="claim-inventory"><b>{list_n}</b> current holdouts · '
            f'<a href="/busy-beaver/tools/machines.html#b-active"><b>{active}</b> in progress</a> · '
            f'<a href="/busy-beaver/tools/machines.html#b-parked"><b>{parked}</b> parked</a> · '
            f'<a href="/busy-beaver/tools/machines.html#b-untouched"><b>{n["untouched"]}</b> not started</a></div></section>')
    reminder = ""
    if ready:
        verified = [r["kill"]["first_ts"] for r in ready if (r.get("kill") or {}).get("first_ts")]
        age = (f' Oldest local verification: {esc(_when(min(verified)))} '
               f'({esc(S.ago_short(min(verified), repo.now))} ago).' if verified else "")
        reminder += (f'<section class="claim-ready" id="submit-early"><div><h2>{len(ready)} proofs ready for PR</h2>'
                     f'<p>These packages are ready to submit.{age}</p></div>'
                     '<a class="ui-btn primary" href="/busy-beaver/tools/submissions.html#ready">Open submission queue →</a></section>')
    items = home_needs(repo, by7)
    lis = []
    for it in items:
        tag = (f'<span class="ui-tag"{" title=" + chr(34) + esc(it["tip"]) + chr(34) if it["tip"] else ""}>'
               f'{esc(it["tag"])}</span>' if it["tag"] else "")
        lis.append(f'<li><span class="hm-ico {it["ico"][0]}" aria-hidden="true">{it["ico"][1]}</span><div>'
                   f'<div class="hm-nt">{esc(it["title"])}{tag}</div><div class="hm-nd" title="{esc(it["text"])}">'
                   f'{esc(it["text"])}</div></div><a class="ui-btn{" primary" if it["primary"] else ""}" '
                   f'href="/busy-beaver/tools/</span><span class="si">{esc(it["link"][0])}">{esc(it["link"][1])} →</a></li>')
    needs_body = (f'<ul class="hm-needs">{"".join(lis)}</ul>' if lis else
                  '<p class="hm-none"><span class="hm-ico i-ready">✓</span>Nothing needs you right now.</p>')
    badge = f'<span class="hm-badge">{len(items)}</span>' if items else ""
    needs = (f'<section class="ui-card hm-panel" id="needs"><div class="ui-sec-head"><h2 class="ui-h2">Needs you{badge}'
             f'</h2></div>{needs_body}</section>')
    rec = home_recent(repo)
    rlis = "".join(f'<li><span class="hm-when" title="{esc(x["full"])}">{esc(x["when"])}</span><span class="hm-kd '
                   f'{x["tone"]}"></span><span class="hm-line" title="{esc(x["title"])}">{x["html"]}</span></li>'
                   for x in rec)
    recent = (f'<section class="ui-card hm-panel" id="recent"><div class="ui-sec-head"><h2 class="ui-h2">Recent</h2>'
              + ('<a class="ui-link" href="/busy-beaver/reports/overnight-ledger.md.html">Full log →</a>'
                 if (repo.root / "reports" / "overnight-ledger.md").is_file() else "") + '</div>'
              f'<ol class="hm-recent">{rlis or "<li>Nothing recent.</li>"}</ol></section>')
    nlearn = len(list((repo.root / "learn").glob("[0-9][0-9]-*.html")))
    folders = sum(1 for r in repo.recs if r.get("has_folder", r["bucket"] != "untouched"))
    entries = (f'<div class="hm-entries">'
               f'<a class="ui-card hm-entry" href="/busy-beaver/tools/machines.html"><span class="hm-eico">{ICONS["machines"]}</span>'
               f'<span><h3>Machines</h3><p>All {len(repo.recs)} machines · {folders} local folders</p></span>'
               f'<span class="hm-arrow">→</span></a>'
               f'<a class="ui-card hm-entry" href="/busy-beaver/tools/</span><span class="si">{LEARN_HREF}"><span class="hm-eico">{ICONS["learn"]}</span>'
               f'<span><h3>Learn</h3><p>How holdouts get proved{f", in {nlearn} short chapters" if nlearn else ""}</p>'
               f'</span><span class="hm-arrow">→</span></a></div>')
    built = _dt.datetime.fromtimestamp(repo.now).strftime("%a %b %-d, %H:%M")
    reconciliation_note = ""
    evidence = repo.meta.get("reconciliation") or {}
    if evidence:
        snapshot = evidence.get("summary") or {}
        overlap_n = snapshot.get("suggested_buckets", {}).get("upstream_overlap", 0)
        own_removed = snapshot.get("removed_with_local_proofs", 0) - overlap_n
        head = evidence.get("upstream_head") or ""
        reconciliation_note = (
            '<section class="ui-card hm-panel" id="reconciliation" style="margin:24px 0">'
            f'<div class="ui-sec-head"><h2 class="ui-h2">{list_n}-list reconciliation</h2></div>'
            f'<p>{snapshot.get("removed_since740", snapshot.get("removed_in698", 0))} machines removed since the 740 list: '
            f'{own_removed} through our merged PRs, '
            f'<a href="/busy-beaver/tools/submissions.html#upstream-overlap">{overlap_n} claimed by someone else while ours remained unsubmitted</a>, '
            f'and <a href="/busy-beaver/tools/machines.html#b-external_solved">{snapshot.get("removed_without_local_proofs", 0)} others</a>.</p>'
            f'<p>{on_total} of the {list_n} listed machines have local proofs; '
            f'{list_n - on_total} have no full local proof recorded. The published list remains {list_n}.</p>'
            f'<p class="ui-muted">Reconciled {esc(evidence.get("created_at_utc", "")[:10])}. Upstream snapshot '
            f'<a href="https://github.com/ccz181078/busycoq/commit/{esc(head)}">{esc(head[:8])}</a>; '
            'rebuilding this page does not fetch new upstream results. '
            f'<a href="/busy-beaver/unavailable.html"si">{esc(evidence.get("report_path", "astra/holdouts-698-20261015/REPORT.md"))}">List report</a> · '
            '<a href="/busy-beaver/unavailable.html">Overlap timeline and timing limits</a></p></section>')
    pending_external = evidence.get("external_submissions") or {}
    if pending_external and (by7["competing_pr"] or by7["external_pending"]):
        reconciliation_note += ('<p class="ui-muted">External PRs checked '
            + esc(pending_external["checked_at"]) + ': '
            + f'<a href="/busy-beaver/tools/submissions.html#competing-prs">{len(by7["competing_pr"])} overlap our unsubmitted proofs</a>; '
            + f'<a href="/busy-beaver/tools/machines.html#b-external_pending">{len(by7["external_pending"])} cover other listed machines</a>. '
            + 'These submissions are awaiting review.</p>')
    body = (S.page_title("BB(6) holdout hunt", f"Updated {esc(built)}") + hero + reminder
            + f'<div class="hm-grid">{needs}{recent}</div>' + reconciliation_note + entries + _more_html(repo, by7))
    return S.page("BB(6) hunt", body, active="home", prefix="../", css=C.CARD_CSS + DASH_CSS + HOME_CSS,
                  js=COPY_JS, built_ts=repo.now, open_n=len(repo.open_decisions), machines=repo.machines)


# ----------------------------------------------------------------------------------------------- Machines

FAMILY_SRC = ("Families: status.json parent links, same table with another start, targeting.md follow-on rows, "
              "ledger \"= twin\" notes, machine strings named in .v headers / proof.md / notes.md.")


def _upd_html(rec: dict, now: float) -> str:
    """The Last update cell: '12m ago' / '5h ago' within two days, else the date; the full time in the tooltip."""
    ts = rec.get("last_work")
    if not ts or rec["bucket"] == "untouched":
        return '<span class="ui-muted">–</span>'
    full = _dt.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")
    short = (S.ago_short(ts, now) + " ago") if now - ts < 48 * 3600 else _dt.datetime.fromtimestamp(ts).strftime("%b %-d")
    return f'<span class="mx-upd" data-ts="{int(ts)}" title="the newest file in its folder: {esc(full)}">{esc(short)}</span>'


def _row_sub(repo, rec: dict, b: str) -> str:
    """The muted second line under a machine's name: kill number, checks, PR, family (kills); stage, call,
    questions (others); same table, eqv, sim, flags and links (untouched); off-list reason."""
    tm, bits = rec["tm"], []
    if rec.get("external_submission"):
        ext = rec["external_submission"]
        bits.append(f'<a href="/busy-beaver/tools/</span><span class="si">{esc(ext["url"])}">{esc(ext["author"])} · PR #{ext["number"]} · {esc(ext["state"])}</a>')
        bits.append(f'<span>submitted result: {"halts" if ext["result"] == "halt" else "nonhalting"} · not merged</span>')
        if rec["bucket"] == "competing_pr":
            note = "packaged" if packaging_ready(rec) else "needs packaging"
            bits.append(f'<span>our proof is local and unsubmitted · {note}</span>')
    if rec["bucket"] in ("upstream_overlap", "external_solved"):
        up = rec.get("upstream") or {}
        proof = up.get("proof") or {}
        if rec.get("kill_no"):
            bits.append(f'<span>local proof {rec["kill_no"]}</span>')
        if up.get("source_url"):
            label = ".".join(x for x in (up.get("file"), up.get("module")) if x)
            bits.append(f'<a href="/busy-beaver/tools/</span><span class="si">{esc(up["source_url"])}">{esc(label)} · {esc(up.get("result") or "proof")}</a>')
        bits.append('<span>our proof was not submitted</span>' if rec["bucket"] == "upstream_overlap" else
                    '<span>no local proof counted</span>')
    elif rec["bucket"] in KILL_BUCKETS:
        if rec.get("kill_no"):
            bits.append(f'<span class="kno" title="local proof number: order of the first check_kill PASS">local proof {rec["kill_no"]}'
                        f'</span>')
        s = repo.kill_summary(tm) or {}
        if "auto_n" in s:
            import killreview as K
            ok = s["auto_ok"] == s["auto_n"]
            why = S.plain(K.auto_why(s, repo.ctx.status.get(tm, {})))
            bits.append(f'<a class="mx-ck{"" if ok else " no"}" href="/busy-beaver/tools/</span><span class="si">{esc(_mhref(tm, "#proof"))}" title="the automatic '
                        f'kill review{" · " + esc(why) if why else ""}">{s["auto_ok"]}/{s["auto_n"]} checks</a>')
        elif s.get("error"):
            bits.append(f'<span class="bad" title="{esc(s["error"])}">kill review not built</span>')
        su = rec.get("sub") or submission(repo.ctx.status.get(tm) or C.load_status(repo.machines / tm))
        if su.get("pr"):
            word = {"merged": "merged", "open": "open", "closed": "closed unmerged"}.get(su.get("pr_state") or "",
                                                                                     "state not synced")
            bits.append(f'<a class="mx-pr{" bad" if su.get("closed") else ""}" href="/busy-beaver/tools/</span><span class="si">{esc(su["pr"])}" '
                        f'title="the busycoq PR">PR #{su.get("no") or "?"} {esc(word)}</a>')
        else:
            bits.append('<span title="check_kill PASS here; in no PR yet">not submitted</span>')
        if rec.get("fam") and rec["fam"] != tm and rec.get("fam_name"):
            bits.append(f'<span class="ui-muted">family of {esc(rec["fam_name"])}</span>')
        ks = repo.kill_summaries.get(tm) or {}
        hp = ks.get("how") if "how" in ks else C.load_how_proved(repo.machines / tm)
        if hp:
            bits.append(C.how_proved_tag(hp, _mhref(tm, "#how")))
    elif b == "untouched":
        bits.append(f'<a href="/busy-beaver/tools/</span><span class="si">{esc(_explorer(tm))}">explorer</a>')
        if rec.get("table_ref"):
            bits.append(table_chip(rec))
        bits.append(meta_html(rec, rank=True))
    else:
        if rec.get("summary"):                    # the observer's one sentence on the mechanism, clipped
            bits.append(f'<span class="mx-sum" title="{esc(S.plain(rec["summary"]))}">{esc(S.clip(rec["summary"], 90))}'
                        f'</span>')
        if rec.get("stage_txt"):
            bits.append(f'<span>{esc(rec["stage_txt"])}</span>')
        lv = live_html(rec)
        if lv:
            bits.append(lv)
        if rec.get("ask"):
            lab = "your call" if b == "waiting" else "call on file"
            bits.append(f'<span class="mx-ask" title="{esc(rec["ask"])}"><b>{lab}:</b> {esc(S.clip(rec["ask"], 110))}</span>')
        for v in rec.get("ask_via") or []:
            bits.append(f'<span class="mx-ask" title="{esc(v["ask"])}">{esc(v["name"])}\'s call covers this machine</span>')
        if rec.get("table_ref"):
            bits.append(table_chip(rec))
        elif rec.get("table"):
            bits.append(f'<span class="tsame" title="{esc(table_tip(rec))}">same table as '
                        + ", ".join(f'<a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{o["aid"]}">{esc(o["name"])}</a>' for o in rec["table"][:4])
                        + (" …" if len(rec["table"]) > 4 else "") + "</span>")
        if rec.get("obs_error"):
            bits.append(f'<span class="fl x" title="{esc(rec["obs_error"])}">observe.json unreadable</span>')
        if rec.get("unlabelled"):
            bits.append(f'<span class="fl x" title="diagrams without a complete label (observe.json)">'
                        f'{rec["unlabelled"]} unlabelled</span>')
        nq = len(rec.get("open_q") or [])
        if nq:
            blocks = " (proof work waits for the answers)" if rec.get("questions") and b == "waiting" else ""
            bits.append(f'<a class="fl q" href="/busy-beaver/tools/</span><span class="si">{esc(_mhref(tm, "#checkpoint"))}" title="unanswered Checkpoint A '
                        f'questions (observe.json){blocks}">{nq} open Q</a>')
        if rec.get("discord"):
            bits.append('<span class="fl dc" title="a Discord question draft (observe.json discord_check), not posted; '
                        'it is in Home\'s More detail">Discord draft</span>')
    if rec.get("old740_line"):
        indices = f'740 line {rec["old740_line"]}'
        if rec.get("current_line"):
            indices += f' · {rec["current_list_size"]} line {rec["current_line"]}'
        bits.append(f'<span class="mx-indices">{esc(indices)}</span>')
    oc = off_chip(rec)
    if oc:
        bits.append(oc)
    if rec.get("eq_of"):
        bits.append(eq_chip(rec))
    return f'<div class="mx-sub">{" ".join(x for x in bits if x)}</div>'


def _class_cell(rec: dict) -> str:
    cls = rec.get("class") or ""
    g = rec.get("guess")
    tip = f"sheet class ({rec.get('class_src') or 'none'}): {cls or 'unclassified'}"
    if rec.get("class_ours") and C.norm_class(rec["class_ours"]) != C.norm_class(cls or ""):
        tip += f" · ours: {rec['class_ours']}"
    out = f'<span class="cl" title="{esc(tip)}">{esc(cls)}</span>' if cls else ""
    if g:
        out += (f'<span class="gs" title="GUESS, not the sheet\'s: the class of the nearest classified machine '
                f'({g["dist"]} transitions away)"><b>guess</b> {esc(g["class"])}</span>')
    return out or '<span class="ui-muted">unclassified</span>'


def mx_row(repo, rec: dict, order: int) -> str:
    """One row: name + tag (and the muted line), status pill, class, last update."""
    names, tm, b = repo.names, rec["tm"], bucket7(rec)
    href = thumb_target(rec)[0]
    tone, label = S.BUCKET_PILL[b]
    if b == "parked" and rec.get("status") == "SKIPPED":
        tone, label = "muted", "Skipped"
    tip = rec.get("reason") or TILE[b][5]
    badge = S.workflow_pill(rec) if b in SOLVED_BUCKETS else S.pill(tone, label, title=_first_sentences(tip, 300))
    return (f'<tr class="mr {b}"{_data_attrs(rec, order, b=b, tag=names.tag(tm))}>'
            f'<td class="c-name"><div class="mx-nm">{thumb_html(rec, 36, 45)}<div class="mx-nt">{names.name_html(tm, href)}'
            f'{_row_sub(repo, rec, b)}</div></div></td>'
            f'<td class="c-st">{badge}</td>'
            f'<td class="c-cls">{_class_cell(rec)}</td><td class="c-upd">{_upd_html(rec, repo.now)}</td></tr>')


MX_COLS = (("c-name", "Machine"), ("c-st", "Status"), ("c-cls", "Class"), ("c-upd", "Last update"))


def _about_html(recs: list[dict], meta: dict, now: float) -> str:
    """The folded notes under the table: how to read it, the list facts, the sources, the off-list machines (#off)."""
    n, n_shown = meta["n"], len(recs)
    offs = [r for r in recs if r.get("off")]
    off = ""
    if offs:
        items = "; ".join(f'<a href="/busy-beaver/tools/dashboard.py.html#</span><span class="si">{r["aid"]}">{esc(member_name(r))}</a> ({esc(line_label(r))}, '
                          f'{esc(r["bucket"])}): {esc(r["off"]["short"])}' for r in offs)
        off = (f'<li id="off">off the list: {len(offs)} machine{"s" if len(offs) != 1 else ""} '
               f'that {"are" if len(offs) != 1 else "is"} not on <code>{esc(meta["list"].name)}</code>, shown in '
               f'{"their" if len(offs) != 1 else "its"} bucket with the recorded upstream or historical reason: {items}</li>')
    prev_src = (f'; previous list <code>{esc(_rel_root(meta["prev"]))}</code> (the "{meta["n_prev"]} line n" of '
                f'off-list machines)' if meta.get("prev") else "")
    tb = meta.get("tables") or {"groups": 0, "machines": 0}
    keys = (f'<p>Each row: the machine string with its tag (pool rank, label, or its line on the list), a muted line '
            f'(proofs: local proof number, the automatic checks, the PR, the family, how it was proved; others: the stage, a '
            f'call or Checkpoint A questions; not started: same table as a machine we worked on, sim depth, '
            f'equivalence class size, flags), the status, the sheet class (<span class="gs"><b>guess</b></span> = the '
            f'class of the nearest classified machine, ≤ {GUESS_MAX} transitions), and when a file in its folder last '
            f'changed. <b>same table</b> = the same transition table up to renaming states and mirroring, started in '
            f'another state ({tb["machines"]} machines in {tb["groups"]} groups); <b>sim 1eN</b> = depth simulated '
            f'without halting (sheet Direct Simulation tab: {meta["pending"][14]} of the {n} not yet to 1e14); '
            f'<b>eqv ×n</b> = machines in its equivalence class. Search: a machine string or part of one, a '
            f'bbchallenge.org link, a tag (#2, R4, W4-3: exact), line 604, or a class; <kbd>/</kbd> focuses it. A '
            f'machine\'s page (its name) has the picture, the mechanism, the proof and the files.</p>')
    counts = Counter((r.get("status") or "?") for r in recs if r["bucket"] != "untouched")
    chips = []
    for k in list(C.STATUS) + sorted(k for k in counts if k not in C.STATUS):
        if counts.get(k):
            cls, icon, label = C.STATUS[k] if k in C.STATUS else ("neutral", "•", "no status" if k == "?" else k)
            chips.append(f'<span class="chip {cls}"><b class="ic">{icon}</b>{esc(label)} {counts[k]}</span>')
    keys += f'<p class="schips"><span class="lk">display status (raw status retained in data)</span> {"".join(chips)}</p>' if chips else ""
    keys += f'<div class="tlab"><b>Pictures</b>{C.label_html(THUMB_LABEL)}</div>'
    return (f'<details class="ui-about" id="about"><summary>How to read this table: notes and sources</summary>{keys}'
            f'<p>{list_line(meta, "#off")}</p>'
            f'<ul class="src"><li>list: <code>{esc(_rel_root(meta["list"]))}</code> (current; the line numbers)'
            f'{prev_src}; equivalence classes: <code>data/holdouts/2026-10-07_eqv_1590.txt</code> (made for the '
            f'778 list)</li>'
            f'<li>class, sheet status, sim depth: Robin Rovenszky\'s sheet, exported 2026-10-09 (data/sheet/; '
            f'the Direct Simulation tab is dated Sep 2, the Results tab is stale, data/README.md); known sheet '
            f'errors are struck through (STATUS.md)</li>'
            f'<li>buckets: static source-checked upstream reconciliation in <code>{esc(_rel_root(RECONCILIATION))}</code>, '
            f'plus machines/&lt;tm&gt;/status.json + observe.json via tools/card.py\'s card_state, the '
            f'same rule as the machine pages; "working" = a file there changed in the {LIVE_MIN} min before '
            f'the build (a badge, never a bucket); ledger: reports/overnight-ledger.md</li>'
            f'<li>publication stage: status.json <code>pr</code> / <code>pr_state</code> / '
            f'<code>posted</code>, refreshed by <code>python3 -B tools/pr_sync.py</code> (gh pr view, read-only); '
            f'families: {esc(FAMILY_SRC)}</li>'
            f'<li>local proof numbers: order of each proof\'s first check_kill PASS (kept in dashboard/{KILL_LEDGER}, so a '
            f're-run does not renumber); mechanism lines: submission/README.md</li>'
            f'<li>same table: all 720 state renamings × mirror, start state free (canonical breadth-first '
            f'relabeling), over the {n_shown} machines shown</li>'
            f'<li>flags: data/discord/ (mxdys UBRRBA_TODO 2026-08-24, dyuan01 longitudinal 2026-10-01); '
            f'pool rank: reports/targeting.md §4</li>{off}'
            f'<li>built {esc(S.built_text(now))} by <code>python3 -B tools/dashboard.py</code> (the whole site: '
            f'<code>python3 -B tools/site.py</code>; tools/README-dashboard.md)</li></ul></details>')


def render_machines(repo) -> str:
    """dashboard/machines.html: one table of every holdout on the list and every machine folder, one row each
    (name + tag, status pill, class, last update), grouped by bucket (#b-<bucket>); a search box and status chips
    (JS); the not-started holdouts folded until a chip or a search asks for them."""
    recs, meta = repo.recs, repo.meta
    by7 = _by7(recs)
    order = {r["tm"]: i for i, r in enumerate(_default_order(recs))}
    folders = [r for r in recs if r.get("has_folder", r["bucket"] != "untouched")]
    nq = sum(len(r.get("open_q") or []) for r in folders)
    nqw = sum(len(r.get("open_q") or []) for r in folders if bucket7(r) == "waiting")
    sub = (f'<b>{len(recs)}</b> current and historical machines · '
           + (f'<b>{len(folders)}</b> local folders' if folders else 'no machine folders yet (machines/&lt;tm&gt;/)')
           + (f' · {nq} unanswered Checkpoint A question{"s" if nq != 1 else ""}'
              + (f' ({nqw} on machines waiting on you)' if nqw and nqw != nq else "") if nq else
              (" · no unanswered questions" if folders else "")))
    chips = (f'<button type="button" class="mx-chip" data-fb="" aria-pressed="true">All<span class="n">{len(recs)}</span>'
             f'</button>' + "".join(f'<button type="button" class="mx-chip c-{k}" data-fb="{k}" aria-pressed="false">'
                                    f'<span class="mx-dot"></span>{esc(S.BUCKET_PILL[k][1])}<span class="n">{len(by7[k])}'
                                    f'</span></button>' for k in KEYS8 if by7[k]))
    bar = (f'<div class="mx-bar" id="bar" hidden><div class="mx-search"><input type="search" id="q" '
           f'placeholder="Search a machine, #3, W4-3, line 604 or a class" aria-label="search" autocomplete="off" '
           f'spellcheck="false" title="a machine string or part of one, a bbchallenge.org link, a tag (#2, R4, W4-3: '
           f'exact), line 604, or a class; / focuses, Esc clears"><span class="mx-shown" id="shown"></span></div>'
           f'<div class="mx-chips" role="group" aria-label="status">{chips}</div></div>')
    thead = "".join(f'<th class="{c}" scope="col">{esc(t)}</th>' for c, t in MX_COLS)
    parts = []
    for key in KEYS8:
        rs = sorted(by7[key], key=lambda r: order[r["tm"]])
        _k, _t, heading, _icon, _short, meaning = TILE[key]
        keyline = kill_key(key, rs, meta) if key in KILL_BUCKETS else ""
        extra = ""
        if key == "untouched" and rs:
            extra = (f'<button type="button" class="mx-unmore" id="unmore" hidden>Show all {len(rs)}</button>')
        hid = ' id="untouched"' if key == "untouched" else ""
        empty = "" if rs else '<span class="ui-muted"> · none right now</span>'
        nl = sum(1 for r in rs if r.get("live") and r["bucket"] not in SOLVED_BUCKETS)
        if key not in SOLVED_BUCKETS and key != "untouched":
            extra += (f'<span class="lvc" data-lvb="{key}"{"" if nl else " hidden"}>● {nl} working at build</span>')
        parts.append(f'<tbody class="mx-g" data-b="{key}" id="b-{key}"><tr class="mx-h"{hid}><th colspan="4">'
                     f'<span class="mx-hn"><span class="mx-dot d-{key}"></span>{esc(heading)} <span class="n">{len(rs)}'
                     f'</span></span><span class="gm">{esc(meaning)}</span>{empty}<span class="gn"></span>{extra}'
                     f'{keyline}</th></tr></tbody>')
        if rs:
            parts.append(f'<tbody class="grp" data-b="{key}">'
                         + "".join(mx_row(repo, r, order[r["tm"]]) for r in rs) + "</tbody>")
    table = (f'<div class="ui-card mx-card"><table class="mx" id="mtab"><thead><tr>{thead}</tr></thead>{"".join(parts)}'
             f'</table><p class="mx-empty" id="nomatch" hidden>No machine matches.</p></div>')
    body = S.page_title("Machines", sub) + bar + table + _about_html(recs, meta, repo.now)
    import killreview as K
    return S.page("Machines · BB(6) hunt", body, active="machines", prefix="../",
                  css=C.CARD_CSS + K.CSS_EXTRA + DASH_CSS + MACH_CSS, js=MACH_JS, built_ts=repo.now,
                  open_n=len(repo.open_decisions), machines=repo.machines)


# ----------------------------------------------------------------------------------------------- styles + scripts

DASH_CSS = r"""
.ph{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 16px;margin:2px 0 4px}
.ph h1{font-size:21px;margin:0}
.ph .sub{font-size:13px;color:var(--muted)}.ph .sub b{color:var(--ink2)}
.vh{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}
.bstats{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:10px;margin:10px 0 4px}
a.bs{display:flex;flex-direction:column;gap:1px;background:var(--surface);border:1px solid var(--line);
 border-top:3px solid var(--axis);border-radius:10px;padding:7px 12px 8px;color:var(--ink);min-width:0}
a.bs:hover{text-decoration:none;border-color:var(--accent)}
.bs .bn{font-size:26px;font-weight:650;line-height:1.15;font-variant-numeric:tabular-nums}
.bs .bl{font-size:14px;font-weight:650}.bs .ic{margin-right:5px;color:var(--muted)}
.bs .bm{font-size:12px;color:var(--muted)}
.bs .lvc,.bs .hlv{font-size:12px;font-weight:600;color:var(--ink2);white-space:nowrap}
.bs .bof{font-size:11.5px;color:var(--muted);white-space:nowrap}
/* the three kill buckets: one green family; strong + tinted = accepted, dashed = submitted, soft = claimed */
.bs.accepted{border-top-color:var(--good-strong);background:linear-gradient(var(--good-weak),var(--good-weak)),var(--surface)}
.bs.accepted .ic{color:var(--good-strong)}
.bs.submitted{border-top-style:dashed;border-top-color:var(--good)}.bs.submitted .ic{color:var(--good)}
.bs.claimed{border-top-color:var(--good-soft)}.bs.claimed .ic{color:var(--good)}
.bs.active{border-top-color:var(--ink2)}.bs.active .ic{color:var(--ink2)}
.bs.waiting{border-top-color:var(--accent)}.bs.waiting .ic{color:var(--accent)}
.bs.parked{border-top-color:var(--caution)}.bs.parked .ic{color:var(--caution)}
.bs.cryptid{border-top-style:dashed;border-top-color:var(--caution)}.bs.cryptid .ic{color:var(--caution)}
.tnote{font-size:12.5px;color:var(--muted);margin:2px 0 0}.tnote b{color:var(--ink2);font-weight:600}
.tlab{display:flex;flex-wrap:wrap;align-items:baseline;gap:2px 10px;font-size:12.5px;color:var(--muted);margin:4px 0 2px}
.tlab .dlabel{margin-top:0;flex:1 1 600px}
.tlab b{color:var(--ink2);font-weight:650}
.tkey{font-size:12.5px;color:var(--muted);margin:2px 0 2px;line-height:1.6}
.tkey .ki{display:inline-block;max-width:100%;margin-right:16px;vertical-align:top}
.tkey b{color:var(--ink2);font-weight:650}
/* filter bar (JS only) */
.bar{position:sticky;top:0;z-index:5;background:var(--page);display:flex;flex-wrap:wrap;gap:6px 10px;align-items:center;
 padding:8px 0;border-bottom:1px solid var(--line);margin:8px 0 0}
.bar input[type=search]{font:13px ui-monospace,"Cascadia Code",Consolas,monospace;width:min(340px,100%);padding:4px 9px;
 border:1px solid var(--axis);border-radius:6px;background:var(--surface);color:var(--ink)}
.bar input[type=search]:focus{outline:2px solid var(--accent);outline-offset:-1px}
.fcs{display:flex;flex-wrap:wrap;gap:4px}
button.fc{font:12.5px system-ui,-apple-system,"Segoe UI",sans-serif;border:1px solid var(--line);background:var(--surface);
 color:var(--ink);border-radius:999px;padding:2px 10px;cursor:pointer;white-space:nowrap}
button.fc:hover{border-color:var(--accent)}
button.fc[aria-pressed=true]{border-color:var(--accent);background:var(--accent-weak);color:var(--accent);font-weight:650}
button.fc .n{color:var(--muted);margin-left:4px;font-variant-numeric:tabular-nums}
details.cf{position:static}
details.cf>summary{list-style:none;cursor:pointer;font-size:12.5px;border:1px solid var(--line);border-radius:999px;
 padding:2px 10px;background:var(--surface);white-space:nowrap}
details.cf>summary::-webkit-details-marker{display:none}
details.cf[open]>summary,details.cf.on>summary{border-color:var(--accent);color:var(--accent)}
.bar .fcs.bk{flex:1 1 100%}
details.cf .fcs{position:absolute;top:calc(100% - 4px);left:0;z-index:6;width:min(760px,100%);max-height:60vh;overflow:auto;
 background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:10px;box-shadow:0 6px 24px rgba(0,0,0,.18)}
.bar select{font:12.5px system-ui,sans-serif;border:1px solid var(--line);border-radius:6px;padding:2px 6px;
 background:var(--surface);color:var(--ink)}
.bar .srt{font-size:12.5px}
.bar .shown{font-size:12.5px;color:var(--muted);margin-left:auto;font-variant-numeric:tabular-nums}
button.clr{font:12.5px system-ui,sans-serif;border:0;background:none;color:var(--accent);cursor:pointer;padding:2px 4px}
.key{font-size:12.5px;color:var(--muted);margin:2px 0 4px;line-height:1.55;font-weight:400}
.key b{color:var(--ink2);font-weight:600}
.key .tsame{display:inline}
a.th{flex:none;display:flex;align-items:center;justify-content:center;background:var(--mat);border-radius:6px;overflow:hidden;
 width:128px;height:160px}
a.th img{display:block;width:100%;height:100%}
a.th:hover{outline:2px solid var(--accent)}
.nothumb{color:#9a9a9a;font-size:11.5px;padding:8px;text-align:center}
.kno{font-size:12px;font-weight:700;color:var(--muted);border:1px solid var(--line);border-radius:4px;padding:0 5px;
 white-space:nowrap}
a.prc{font-size:12px;font-weight:700;border-radius:4px;padding:0 6px;white-space:nowrap;border:1px solid transparent}
a.prc:hover{text-decoration:none;outline:2px solid var(--accent);outline-offset:1px}
a.prc.merged{background:var(--good-strong);border-color:var(--good-strong);color:var(--surface)}
a.prc.open{border:1px dashed var(--good);color:var(--good);background:var(--good-weak)}
a.prc.closed{border-color:var(--bad);color:var(--bad)}
a.prc.unk{border:1px dashed var(--muted);color:var(--muted)}
.kpr{font-size:12.5px;color:var(--ink2)}.kpr code{font-size:11.5px;padding:0 3px}
.pcn{color:var(--accent);font-weight:650}
.offl{font-size:11.5px;color:var(--ink2);border:1px solid var(--axis);border-radius:4px;padding:0 5px;background:var(--sunk)}
.live{font-size:12px;font-weight:650;color:var(--ink)}
.tmn{font:600 12.5px/1.35 ui-monospace,"Cascadia Code",Consolas,monospace;color:var(--ink)}
.tmn span{white-space:nowrap}
.tmn.sm{font-size:10px;font-weight:500;color:var(--ink2);line-height:1.3}
.tcl{display:flex;flex-wrap:wrap;gap:2px 8px;align-items:baseline;min-width:0}
.cl{font-size:13px;font-weight:600;color:var(--ink2)}
.gs{font-size:12px;color:var(--ink2)}.gs b{font-weight:700;color:var(--caution);text-transform:uppercase;font-size:10.5px;
 letter-spacing:.05em;margin-right:2px}
.viag .gs{background:var(--accent-weak);border-radius:3px}
.kf{font-size:12.5px;color:var(--ink2);font-variant-numeric:tabular-nums}.kf b{color:var(--ink)}
.lk{font-size:10.5px;font-weight:700;letter-spacing:.06em;text-transform:uppercase;color:var(--muted);margin-right:3px}
.tpr{font-size:12.5px;color:var(--ink2);display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden}
.tpr.two{-webkit-line-clamp:2}
.tlw{font-size:11.5px;color:var(--muted)}
.ttab{font-size:12px;color:var(--ink2)}
.ttab .tsm{white-space:nowrap}.ttab .tsm b{font-weight:650;color:var(--ink)}
.bi{margin-left:3px;font-size:11px;color:var(--muted)}
.bi.accepted{color:var(--good-strong)}.bi.submitted,.bi.claimed{color:var(--good)}.bi.waiting{color:var(--accent)}.bi.parked,.bi.cryptid{color:var(--caution)}.bi.active{color:var(--ink2)}
.tsame{font-size:11.5px;line-height:1.3;color:var(--ink2);border:1px solid var(--accent);border-radius:4px;padding:1px 5px;
 margin:1px 0}
.tsame.k{border-color:var(--good);color:var(--ink);font-weight:600}.tsame.k a{color:var(--good)}
.tsame.q{border-style:dashed}
.ask{font-size:13px;background:var(--accent-weak);border-radius:6px;padding:5px 8px;color:var(--ink);margin-top:3px}
.ask .lk{color:var(--accent)}
.ask.via{background:none;border:1px dashed var(--accent)}
.ask ul.aq{margin:3px 0 0;padding:0;list-style:none;font-size:12.5px;color:var(--ink2)}
.ask ul.aq li{margin:2px 0;padding-left:26px;text-indent:-26px}
.ask ul.aq b{display:inline-block;width:26px;text-indent:0;color:var(--accent);font-weight:700}
ol.pipe{display:flex;list-style:none;margin:1px 0;padding:0;font-size:11.5px;line-height:1.6;flex-wrap:wrap}
ol.pipe li{padding:0 7px;border:1px solid var(--line);color:var(--muted);white-space:nowrap}
ol.pipe li+li{border-left:0}
ol.pipe li:first-child{border-radius:4px 0 0 4px}ol.pipe li:last-child{border-radius:0 4px 4px 0}
ol.pipe li.done{color:var(--ink2);background:var(--sunk)}
ol.pipe li.done::before{content:"✓ ";color:var(--good)}
ol.pipe li.now{color:var(--accent);border-color:var(--accent);background:var(--accent-weak);font-weight:700}
ol.pipe li.now+li{border-left:0}
.tmeta{display:flex;flex-wrap:wrap;gap:3px 6px;align-items:center;font-size:11.5px;color:var(--ink2)}
.mt{font-variant-numeric:tabular-nums;white-space:nowrap}
.mt.sim13{color:var(--caution);font-weight:650}
.fl{border:1px solid var(--line);border-radius:4px;padding:0 4px;white-space:nowrap}
.fl.rk{border-color:var(--accent);color:var(--accent);font-weight:700}
.fl.ss{border-color:var(--caution);color:var(--caution)}
.fl.ss.x{border-color:var(--line);color:var(--muted);white-space:normal}
.fl.q{border-color:var(--accent)}.fl.dc{border-color:var(--caution)}.fl.x{border-color:var(--bad)}
.tln{display:flex;flex-wrap:wrap;gap:2px 12px;font-size:12.5px}
.t{background:var(--surface);border:1px solid var(--line);border-radius:10px;min-width:0}
.t:target{outline:2px solid var(--accent);outline-offset:1px}
.minis{display:grid;grid-template-columns:repeat(auto-fill,minmax(146px,1fr));gap:8px}
.t.mini{display:flex;flex-direction:column;gap:2px;padding:6px 7px 7px;content-visibility:auto;
 contain-intrinsic-size:auto 284px;scroll-margin-top:calc(var(--barh,96px) + 12px)}
.t.mini a.th{margin:0 auto 2px}
.t.mini .cl{font-size:12px;line-height:1.3;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;
 overflow:hidden;min-height:2.6em}
.t.mini .tcl{flex-direction:column;gap:0}
.t.mini .gs{font-size:11px;line-height:1.3}
.t.mini .tmeta{font-size:11px}
.t.mini .tln{font-size:11.5px;gap:0 10px}
.empty{color:var(--muted);font-size:13px;font-weight:400;margin:2px 0 6px}
a.tgl{font-weight:650;white-space:nowrap}span.tgl{font-weight:650}
.nm.sm code.tmn{font-size:.85em}
footer .src{margin:4px 0 0;padding-left:18px}
@media (max-width:1500px){.bstats{grid-template-columns:repeat(4,minmax(0,1fr))}}
@media (max-width:760px){.bstats{grid-template-columns:repeat(2,minmax(0,1fr))}
 .minis{grid-template-columns:repeat(auto-fill,minmax(138px,1fr))}
 .bar{position:relative}.bar .shown{margin-left:0}}
"""

HOME_CSS = r"""
.claim-definition{color:var(--text-2);margin:12px 0 8px}
.claim-flow{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));list-style:none;padding:0;margin:16px 0 0;gap:8px}
.claim-stage{min-width:0;border:1px solid var(--border);border-top:3px solid var(--warn);border-radius:8px;background:var(--surface-2)}
.claim-stage a{display:flex;flex-direction:column;padding:12px 10px;color:var(--text);height:100%;font-size:13px}
.claim-stage a:hover{text-decoration:none;background:var(--accent-weak)}
.claim-stage b{font-size:28px;line-height:1.2;font-variant-numeric:tabular-nums}
.claim-stage span{font-weight:650;margin:4px 0}.claim-stage small{font-size:11px;color:var(--text-2)}
.claim-stage.ready{background:var(--warn-weak);border-color:var(--warn)}
.claim-stage.submitted{border-top-color:var(--accent)}.claim-stage.accepted{border-top-color:var(--ok)}
.claim-inventory{grid-column:1/-1;font-size:14px;color:var(--text-2);border-top:1px solid var(--border);padding-top:16px}
.claim-inventory a{color:var(--text-2)}
.claim-ready{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:20px 24px;margin:24px 0;border:1px solid var(--warn);border-radius:12px;background:var(--warn-weak)}
.claim-ready h2{font-size:18px;text-transform:none;letter-spacing:0;color:var(--text);margin:0 0 4px}
.claim-ready p{font-size:14px;color:var(--text-2)}
@media(max-width:700px){.claim-flow{grid-template-columns:repeat(2,minmax(0,1fr))}.claim-ready{align-items:stretch;flex-direction:column}.claim-ready{padding:16px}}

.hm-hero{padding:var(--sp-4);display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1.25fr);gap:var(--sp-4);align-items:center;
 scroll-margin-top:72px}
.hm-big{display:flex;align-items:baseline;gap:var(--sp-2)}
.hm-big b{font-size:64px;line-height:1;font-weight:700;letter-spacing:-.03em;font-variant-numeric:tabular-nums}
.hm-big span{font-size:18px;color:var(--text-2);font-weight:500}
.hm-split{display:flex;flex-wrap:wrap;gap:var(--sp-1);margin-top:var(--sp-2)}
.hm-split a{display:inline-flex;align-items:center;gap:8px;height:32px;padding:0 12px;border-radius:var(--r-pill);
 border:1px solid var(--border);color:var(--text-2);font-size:14px;background:var(--surface)}
.hm-split a:hover{text-decoration:none;border-color:var(--border-2);color:var(--text)}
.hm-split a b{color:var(--text);font-variant-numeric:tabular-nums}
.hm-dot{width:9px;height:9px;border-radius:50%;flex:none}
.hm-dot.d-accepted{background:var(--ok)}.hm-dot.d-submitted{background:var(--ok-mid)}
.hm-dot.d-claimed{background:var(--ok-soft);box-shadow:inset 0 0 0 1px var(--ok-mid)}
.hm-prog-top{display:flex;flex-wrap:wrap;justify-content:space-between;align-items:baseline;gap:4px var(--sp-2);margin-bottom:10px}
.hm-prog-top b{font-size:15px}
.hm-prog-top span{white-space:nowrap;font-size:14px;color:var(--text-3);font-variant-numeric:tabular-nums}
.hm-bar{display:flex;height:12px;border-radius:var(--r-pill);background:var(--surface-2);overflow:hidden;box-shadow:inset 0 0 0 1px var(--border)}
.hm-bar i{display:block;height:100%}
.hm-bar .d-accepted{background:var(--ok)}.hm-bar .d-submitted{background:var(--ok-mid)}.hm-bar .d-claimed{background:var(--ok-soft)}
.hm-rest{margin-top:var(--sp-2);display:flex;flex-wrap:wrap;gap:4px var(--sp-3);font-size:14px}
.hm-rest a{color:var(--text-3)}.hm-rest a:hover{text-decoration:none;color:var(--text)}
.hm-rest b{color:var(--text);font-weight:600;font-variant-numeric:tabular-nums}
.hm-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:var(--sp-3);margin-top:var(--sp-3);align-items:start}
.hm-panel{padding:var(--sp-3);scroll-margin-top:72px;min-width:0}
.hm-badge{display:inline-flex;align-items:center;justify-content:center;min-width:24px;height:24px;padding:0 7px;margin-left:8px;
 border-radius:var(--r-pill);background:var(--accent);color:var(--on-accent);font:700 13px/1 var(--font);vertical-align:2px}
ul.hm-needs{list-style:none;margin:0;padding:0;display:flex;flex-direction:column}
ul.hm-needs li{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:4px 12px;align-items:start;padding:14px 0;
 border-top:1px solid var(--border)}
ul.hm-needs li:first-child{border-top:0;padding-top:4px}
.hm-ico{width:32px;height:32px;border-radius:var(--r-sm);display:grid;place-items:center;font:700 15px/1 var(--font);flex:none}
.hm-ico.i-dec{background:var(--accent-weak);color:var(--accent)}
.hm-ico.i-wait{background:var(--warn-weak);color:var(--warn)}
.hm-ico.i-post{background:var(--surface-2);color:var(--text-2)}
.hm-ico.i-ready{background:var(--warn-weak);color:var(--warn)}
.hm-ico.i-pr{background:var(--bad-weak);color:var(--bad)}
.hm-nt{font-weight:600;font-size:15px;line-height:1.35;display:flex;flex-wrap:wrap;align-items:center;gap:4px 8px}
.hm-nd{font-size:14px;color:var(--text-2);margin-top:2px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.hm-none{display:flex;gap:12px;align-items:center;color:var(--text-2);font-size:15px;padding:var(--sp-1) 0}
ol.hm-recent{list-style:none;margin:0;padding:0}
ol.hm-recent li{display:grid;grid-template-columns:52px 10px minmax(0,1fr);gap:0 12px;align-items:center;min-height:40px;
 border-top:1px solid var(--border);font-size:14.5px}
ol.hm-recent li:first-child{border-top:0}
.hm-when{color:var(--text-3);font-size:13px;font-variant-numeric:tabular-nums;white-space:nowrap}
.hm-kd{width:8px;height:8px;border-radius:50%;background:var(--border-2)}
.hm-kd.ok{background:var(--ok)}.hm-kd.warn{background:var(--warn)}.hm-kd.accent{background:var(--accent)}.hm-kd.muted{background:var(--text-3)}
.hm-line{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:var(--text-2)}
.hm-line a.hm-who{color:var(--text);font-weight:600}
.hm-line b{font-weight:600}.hm-line b.t-ok{color:var(--ok)}.hm-line b.t-warn{color:var(--warn)}.hm-line b.t-accent{color:var(--accent)}
.hm-line b.t-muted{color:var(--text-2)}
.hm-entries{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sp-3);margin-top:var(--sp-3)}
a.hm-entry{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:var(--sp-2);align-items:center;padding:var(--sp-3);color:var(--text)}
a.hm-entry:hover{text-decoration:none;border-color:var(--border-2);box-shadow:0 4px 16px rgba(17,24,39,.08)}
a.hm-entry h3{margin:0;font-size:18px;font-weight:650}
a.hm-entry p{margin:2px 0 0;color:var(--text-2);font-size:14.5px}
.hm-eico{width:48px;height:48px;border-radius:var(--r);display:grid;place-items:center;background:var(--surface-2);color:var(--text-2)}
.hm-eico svg{width:24px;height:24px}
.hm-arrow{color:var(--text-3);font-size:20px}
a.hm-entry:hover .hm-arrow{color:var(--accent)}
#more{margin-top:var(--sp-3)}
/* the folded detail (the old Home's blocks) */
.nb{background:var(--surface);border:1px solid var(--border);border-left:4px solid var(--border-2);border-radius:var(--r-sm);
 padding:10px 14px 12px;margin:0 0 10px;min-width:0}
.nb.also{border-left-color:var(--text-2)}.nb.q{border-left-color:var(--accent)}.nb.dq{border-left-color:var(--warn)}
.nb>h3{font-size:14.5px;font-weight:650;margin:0 0 6px;display:flex;flex-wrap:wrap;gap:2px 10px;align-items:baseline}
.nb>h3 .gm{font-size:12.5px;font-weight:400;color:var(--text-3)}
.nb>h3 .go{margin-left:auto;font-size:13px;font-weight:600;white-space:nowrap}
ul.nl{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:9px}
ul.nl>li{min-width:0;font-size:13.5px;overflow-wrap:anywhere}
ul.nl.fams,ul.nl.qs{gap:4px}
.nq{margin-top:2px;color:var(--text)}
.nr{font-size:12.5px;color:var(--text-2);margin-top:2px}
details.nd>summary{cursor:pointer;color:var(--text-2);font-size:13.5px}
details.nd[open]>summary{margin-bottom:8px}
.dqi{margin:0 0 10px}.dqi .it{display:flex;flex-wrap:wrap;gap:4px 10px;align-items:center;font-size:13px;margin-bottom:3px}
.dqi pre{margin:0;white-space:pre-wrap;word-break:break-word;background:var(--surface-2);border:1px solid var(--border);
 border-radius:6px;padding:7px 9px;font-size:12.5px;max-height:220px;overflow:auto}
.hh3{font-size:13px;font-weight:650;color:var(--text-2);margin:16px 0 6px;letter-spacing:0;text-transform:none}
.hh3 .gm{font-weight:400;color:var(--text-3);font-size:12.5px}
ul.lgl{list-style:none;margin:0;padding:0;font-size:12.5px;color:var(--text-2)}
ul.lgl li{padding:5px 0;border-bottom:1px solid var(--border);display:grid;grid-template-columns:110px minmax(0,1fr);gap:0 12px}
.lgt{color:var(--text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
.lga{min-width:0;overflow-wrap:anywhere}
.lgm{grid-column:2;color:var(--text-3);font-size:12px}
.rpl{margin-top:12px;font-size:13.5px;overflow-wrap:anywhere}
@media (max-width:900px){.hm-hero{grid-template-columns:minmax(0,1fr);gap:var(--sp-3)}.hm-grid{grid-template-columns:minmax(0,1fr)}}
@media (max-width:600px){.hm-hero{padding:var(--sp-3)}
 .hm-line{white-space:normal;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical}ol.hm-recent li{padding:8px 0;align-items:start}
 ol.hm-recent li .hm-kd{margin-top:8px}ol.hm-recent li .hm-when{line-height:24px}.hm-big b{font-size:52px}
 .hm-entries{grid-template-columns:minmax(0,1fr);gap:var(--sp-2)}
 ul.hm-needs li{grid-template-columns:auto minmax(0,1fr)}ul.hm-needs li .ui-btn{grid-column:2;justify-self:start;margin-top:6px}
 a.hm-entry{padding:var(--sp-2)}.hm-panel{padding:var(--sp-2)}ol.hm-recent li{grid-template-columns:44px 8px minmax(0,1fr);gap:0 10px}
 ul.lgl li{grid-template-columns:minmax(0,1fr)}.lgm{grid-column:1}.nb>h3 .go{margin-left:0}}
"""

MACH_CSS = r"""
:root{--maxw:1240px}
.mx-bar{position:sticky;top:56px;z-index:20;background:var(--bg);padding:var(--sp-1) 0 12px;margin:0 0 var(--sp-1);
 display:flex;flex-direction:column;gap:10px}
.mx-search{display:flex;align-items:center;gap:var(--sp-2);flex-wrap:wrap}
.mx-search input{flex:1 1 320px;min-width:0;max-width:520px;height:40px;padding:0 14px;border:1px solid var(--border-2);
 border-radius:var(--r-sm);background:var(--surface);color:var(--text);font:15px var(--font)}
.mx-search input:focus{outline:2px solid var(--accent);outline-offset:-1px;border-color:var(--accent)}
.mx-shown{font-size:13.5px;color:var(--text-3);font-variant-numeric:tabular-nums}
.mx-chips{display:flex;flex-wrap:wrap;gap:6px}
button.mx-chip{display:inline-flex;align-items:center;gap:7px;height:32px;padding:0 12px;border-radius:var(--r-pill);
 border:1px solid var(--border);background:var(--surface);color:var(--text-2);font:500 13.5px var(--font);cursor:pointer;
 white-space:nowrap}
button.mx-chip:hover{border-color:var(--border-2);color:var(--text)}
button.mx-chip[aria-pressed=true]{border-color:var(--accent);background:var(--accent-weak);color:var(--accent);font-weight:600}
button.mx-chip .n{color:var(--text-3);font-variant-numeric:tabular-nums;font-weight:500}
.mx-dot{width:8px;height:8px;border-radius:50%;background:var(--border-2);flex:none;display:inline-block}
.c-accepted .mx-dot,.mx-dot.d-accepted{background:var(--ok)}.c-submitted .mx-dot,.mx-dot.d-submitted{background:var(--accent)}
.c-claimed .mx-dot,.mx-dot.d-claimed{background:var(--warn)}
.c-active .mx-dot,.mx-dot.d-active,.c-waiting .mx-dot,.mx-dot.d-waiting{background:var(--accent)}
.c-parked .mx-dot,.mx-dot.d-parked,.c-cryptid .mx-dot,.mx-dot.d-cryptid{background:var(--warn)}
.c-upstream_overlap .mx-dot,.mx-dot.d-upstream_overlap,.hm-dot.d-upstream_overlap{background:var(--bad)}
.mx-chip.c-upstream_overlap{color:var(--bad);border-color:var(--bad);background:var(--bad-weak)}
tbody[data-b="upstream_overlap"],tbody[data-b="competing_pr"]{background:var(--bad-weak)}
.mx-chip.c-competing_pr,tbody[data-b="competing_pr"] .mx-hn{color:var(--bad)}
.mx-dot.d-competing_pr{background:var(--bad)}
.mx-dot.d-external_pending{background:var(--warn)}
tbody[data-b="upstream_overlap"] .mx-hn{color:var(--bad)}
tr.upstream_overlap td:first-child{border-left:3px solid var(--bad)}
tr.upstream_overlap .mx-sub{color:var(--text-2)}
.c-external_solved .mx-dot,.mx-dot.d-external_solved{background:var(--text-3)}
.mx-card{overflow:hidden}
table.mx{width:100%;border-collapse:collapse;table-layout:fixed;font-size:14.5px}
table.mx thead th{text-align:left;font-size:13px;font-weight:600;color:var(--text-3);padding:12px var(--sp-2);background:var(--surface-2);
 border-bottom:1px solid var(--border)}
table.mx th.c-name{width:50%}table.mx th.c-st{width:17%}table.mx th.c-cls{width:21%}table.mx th.c-upd{width:12%}
table.mx td{padding:12px var(--sp-2);border-top:1px solid var(--border);vertical-align:top;min-width:0;overflow-wrap:anywhere}
tr.mr{scroll-margin-top:190px}
tr.mr:hover td{background:var(--surface-2)}
tr.mr:target td,tr.mr.hl td{background:var(--accent-weak)}
td.c-name .nm{display:block}
.mx-nm{display:flex;gap:12px;align-items:flex-start;min-width:0}.mx-nt{min-width:0;flex:1}
table.mx a.th{flex:none;width:36px;height:45px;border-radius:4px;background:var(--mat);display:block;overflow:hidden}
table.mx a.th img{display:block;width:100%;height:100%;image-rendering:pixelated}
table.mx .nothumb{display:none}
tbody.mx-g .lvc{font-size:13px;font-weight:600;color:var(--text-2);margin-left:8px}
td.c-name .nm code.tmn{font-size:13.5px}
.mx-sub{display:flex;flex-wrap:wrap;align-items:center;gap:3px 10px;margin-top:5px;font-size:13px;color:var(--text-3);line-height:1.45}
.mx-sub>*{min-width:0}
.mx-sub .kr-sub{font-size:12.5px;margin:0}
.mx-sub .tmeta{font-size:12px}
.mx-sub .tsame,.mx-sub .eqv{font-size:12px;margin:0}
a.mx-ck{color:var(--ok);font-weight:600}a.mx-ck.no{color:var(--warn)}
.mx-sub .howp-tag{margin:0;border:0;padding:0;background:none;color:var(--text-2);max-width:100%}
a.mx-pr{color:var(--text-2)}a.mx-pr.bad{color:var(--bad);font-weight:600}
.mx-sum{color:var(--text-2)}
.mx-ask{color:var(--text);background:var(--accent-weak);border-radius:6px;padding:1px 8px}
.mx-ask b{color:var(--accent);font-weight:600}
td.c-st .ui-pill{max-width:100%;height:auto;min-height:24px;white-space:normal;line-height:1.3;padding-top:4px;padding-bottom:4px}
td.c-st .ui-pill::before{flex-shrink:0}
td.c-cls{font-size:14px;color:var(--text-2)}
td.c-cls .cl{font-size:14px;font-weight:500;color:var(--text-2);display:block}
td.c-cls .gs{display:block;font-size:13px}
td.c-upd{font-size:13.5px;color:var(--text-3);font-variant-numeric:tabular-nums;white-space:nowrap}
tbody.mx-g th{text-align:left;padding:20px var(--sp-2) 8px;background:var(--surface);border-top:1px solid var(--border);font-weight:400}
tbody.mx-g:first-of-type th{border-top:0}
tbody.mx-g{scroll-margin-top:190px}
tr.mx-h{scroll-margin-top:190px}
.mx-hn{display:inline-flex;align-items:center;gap:8px;font-size:16px;font-weight:650;color:var(--text);margin-right:10px}
.mx-hn .n{color:var(--text-3);font-weight:500;font-variant-numeric:tabular-nums}
tbody.mx-g .gm{font-size:13px;color:var(--text-3)}
tbody.mx-g .gn{font-size:13px;color:var(--accent);margin-left:8px}
tbody.mx-g .key{margin:6px 0 0;font-size:13px;color:var(--text-3);line-height:1.55;font-weight:400}
tbody.mx-g .key b{color:var(--text-2)}
button.mx-unmore{margin-left:10px;height:28px;padding:0 12px;border-radius:var(--r-pill);border:1px solid var(--border-2);
 background:var(--surface);color:var(--accent);font:600 13px var(--font);cursor:pointer}
.mx-empty{padding:var(--sp-3);text-align:center;color:var(--text-3);margin:0}
.ui-about .src{margin:6px 0 0;padding-left:18px}.ui-about p{margin:6px 0}.ui-about li{margin:3px 0}
kbd{font:12px var(--mono);border:1px solid var(--border-2);border-radius:4px;padding:0 4px}
@media (max-width:820px){
 table.mx,table.mx tbody,table.mx tr,table.mx td,table.mx th{display:block;width:auto}
 table.mx thead{display:none}
 table.mx tbody[hidden],table.mx tr[hidden]{display:none}
 table.mx tr.mr{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 12px;padding:12px var(--sp-2);border-top:1px solid var(--border)}
 table.mx tr.mr td{padding:0;border:0}
 table.mx td.c-name{grid-column:1/-1}
 table.mx td.c-st{grid-column:1}table.mx td.c-upd{grid-column:2;grid-row:2;text-align:right}
 table.mx td.c-cls{grid-column:1/-1}
 table.mx td.c-cls .cl,table.mx td.c-cls .gs{display:inline;margin-right:8px}
 tbody.mx-g th{padding:18px var(--sp-2) 8px}
 .mx-bar{top:56px}
}
@media (max-width:600px){tbody.mx-g .gm{display:none}.mx-sub{font-size:12.5px}td.c-name .nm code.tmn{font-size:12.5px}}
"""

MACH_JS = r"""
(function(){
 var bar=document.getElementById('bar');if(!bar)return;bar.hidden=false;
 var rows=[].slice.call(document.querySelectorAll('tr.mr[data-tm]'));
 var heads=[].slice.call(document.querySelectorAll('tbody.mx-g'));
 var bodies=[].slice.call(document.querySelectorAll('tbody.grp'));
 var q=document.getElementById('q'),shown=document.getElementById('shown'),more=document.getElementById('unmore'),
  none=document.getElementById('nomatch');
 var st={b:'',q:'',un:false},total={};
 rows.forEach(function(t){var d=t.dataset;total[d.b]=(total[d.b]||0)+1;t._s=[d.tm,d.c,d.tag||'',d.old740?'740 line '+d.old740:'',d.current698?'698 line '+d.current698:'',d.currentline?d.currentlist+' line '+d.currentline:''].join(' ').toLowerCase();
  t._g=(d.g||'').toLowerCase()});
 function norm(s){s=(s||'').trim();var m=s.match(/bbchallenge\.org\/([^&?#\s]+)/i);if(m)s=decodeURIComponent(m[1]);return s.toLowerCase()}
 function match(t,qq){if(!qq)return true;var m;
  if(/^(#\d+[a-z]?|r\d+|[a-z]\d*-\d+[a-z]?)$/.test(qq))return (t.dataset.rk||'').toLowerCase()===qq||(t.dataset.tag||'').toLowerCase()===qq;
  if((m=qq.match(/^(?:old\s*)?740\s*(?:line\s*)?(\d+)$/)))return t.dataset.old740===m[1];
  if((m=qq.match(/^698\s*(?:line\s*)?(\d+)$/)))return t.dataset.current698===m[1];
  if((m=qq.match(/^(\d+)\s*(?:line\s*)?(\d+)$/))&&m[1]===t.dataset.currentlist)return t.dataset.currentline===m[2];
  if((m=qq.match(/^(?:l|line\s*)(\d+)$/)))return t.dataset.l===m[1];
  return t._s.indexOf(qq)>=0||(t._g&&t._g.indexOf(qq)>=0)}
 function apply(){
  var qq=norm(st.q),n=0,per={},on=!!(st.b||qq);
  rows.forEach(function(t){var b=t.dataset.b,ok=(!st.b||st.b===b)&&match(t,qq);
   var fold=b==='untouched'&&!on&&!st.un;t.hidden=!ok||fold;if(ok){per[b]=(per[b]||0)+1;if(!fold)n++}});
  bodies.forEach(function(g){g.hidden=!g.querySelector('tr.mr:not([hidden])')});
  heads.forEach(function(h){var k=h.dataset.b,c=per[k]||0,t=total[k]||0;h.hidden=on&&!c;
   var g=h.querySelector('.gn');if(g)g.textContent=(!on||c===t)?'':(c+' of '+t+' shown')});
  if(more){var un=total.untouched||0;more.hidden=on||st.un||!un}
  var all=rows.length;shown.textContent=on?(n+' of '+all+' shown'):(all+' machines'+((total.untouched&&!st.un)?' · '+total.untouched+' not started folded':''));
  if(none)none.hidden=n>0;
  [].forEach.call(document.querySelectorAll('button.mx-chip'),function(b){b.setAttribute('aria-pressed',(b.dataset.fb||'')===st.b?'true':'false')});
 }
 function hashBucket(){var m=location.hash.match(/^#b-([a-z]+)$/);return m&&total[m[1]]!==undefined?m[1]:''}
 function reveal(id){var t=id&&document.getElementById(id);if(!t)return;
  if(t.closest('[hidden]')){st.b='';st.q='';q.value='';st.un=true;apply()}
  var d=t.closest('details');if(d&&!d.open)d.open=true;
  if(t.tagName==='TR'){t.classList.add('hl');setTimeout(function(){t.classList.remove('hl')},2400)}
  requestAnimationFrame(function(){t.scrollIntoView({block:'center'})})}
 bar.addEventListener('click',function(e){var b=e.target.closest('button.mx-chip');if(!b)return;
  var k=b.dataset.fb||'';st.b=(st.b===k)?'':k;apply()});
 if(more)more.addEventListener('click',function(){st.un=true;apply()});
 var tmr;q.addEventListener('input',function(){clearTimeout(tmr);tmr=setTimeout(function(){st.q=q.value;apply()},80)});
 q.addEventListener('keydown',function(e){if(e.key==='Escape'){q.value='';st.q='';apply()}});
 document.addEventListener('keydown',function(e){if(e.key==='/'&&document.activeElement!==q&&!/^(INPUT|TEXTAREA|SELECT)$/.test(document.activeElement.tagName)){e.preventDefault();q.focus()}});
 document.addEventListener('click',function(e){var a=e.target.closest&&e.target.closest('a[href^="#"]');
  if(a){var id;try{id=decodeURIComponent(a.getAttribute('href').slice(1))}catch(x){return}
   if(/^b-/.test(id)){e.preventDefault();st.b=id.slice(2);st.q='';q.value='';apply();bar.scrollIntoView()}else reveal(id)}});
 addEventListener('hashchange',function(){var k=hashBucket();if(k){st.b=k;st.q='';q.value='';apply()}
  else{try{reveal(decodeURIComponent(location.hash.slice(1)))}catch(x){}}});
 var hb=hashBucket();if(hb)st.b=hb;apply();
 if(!hb&&location.hash){try{reveal(decodeURIComponent(location.hash.slice(1)))}catch(x){}}
})();
"""

ROOT_INDEX = """<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="0; url=dashboard/index.html">
<title>BB(6) hunt</title>
<style>%TOKENS%
html,body{background:var(--page)}
body{margin:0;padding:24px 16px;color:var(--ink);font:15px/1.5 system-ui,-apple-system,"Segoe UI",sans-serif}
a{color:var(--accent)}
</style></head>
<body><p>Opening <a href="/busy-beaver/tools/dashboard/index.html">Home</a> ·
<a href="/busy-beaver/tools/dashboard/machines.html">Machines</a> · <a href="/busy-beaver/tools/dashboard/submissions.html">Submissions</a> ·
<a href="/busy-beaver/tools/dashboard/decisions.html">Decisions</a> · <a href="/busy-beaver/tools/dashboard/reports.html">Reports</a> ·
<a href="/busy-beaver/tools/tools/explorer/index.html">Explorer</a></p></body></html>
""".replace("%TOKENS%", S.TOKENS.strip())


def write_root_index(root: Path = ROOT) -> Path:
    p = root / "index.html"
    C.write_atomic(p, ROOT_INDEX)
    return p


def records_json(recs: list[dict]) -> str:
    keep = ("tm", "line", "line_prev", "bucket", "status", "stage", "step", "rank", "class", "class_src", "guess",
            "sim", "eqv", "flags", "sheet_status", "sheet_override", "live", "ask", "questions", "ask_via", "parent",
            "kill_no", "kill", "sub", "fam_name", "off", "eq_of", "table", "table_ref", "tier",
            "aid", "has_folder", "raw_status", "raw_stage", "old740_line", "current698_line", "line_740", "line_698",
            "prev_n", "current_line", "current_list_size", "current663_line", "local_proof", "upstream", "reconciliation", "external_submission")
    slim = {"table": ("tm", "name", "start", "mirror", "bucket"), "table_ref": ("tm", "name", "start", "mirror"),
            "ask_via": ("tm", "name"), "eq_of": ("tm", "name", "short")}

    def val(k, v):
        if k in slim:
            pick = slim[k]
            return [{x: o[x] for x in pick} for o in v] if isinstance(v, list) else {x: v[x] for x in pick}
        return v
    return json.dumps([{k: val(k, r.get(k)) for k in keep if r.get(k) not in (None, "", [], {})} for r in recs],
                      indent=0)


def build(out: Path = OUT, list_path: Path = LIST, machines: Path = MACHINES, thumbs: bool = True,
          force_thumbs: bool = False, root_index: bool = True, jobs: int = THUMB_JOBS,
          cards_index: bool | None = None, now: float | None = None, prev_path: Path | None = PREV_LIST,
          repo=None) -> dict:
    """Thumbnails, then Home (index.html), the Machines table (machines.html), data.json and the kill ledger
    (kills.json), and the repo-root redirect. repo: a sitekit.Repo to reuse (tools/site.py passes its own, so the
    records and kill summaries are computed once); else one is made for these paths. cards_index is accepted for
    old callers and ignored: the Machines page replaced machines/index.html."""
    del cards_index
    t0 = time.time()
    out = Path(out)
    out.mkdir(parents=True, exist_ok=True)
    tinfo = None
    if thumbs:
        tinfo = ensure_thumbs(shown_tms(list_path, Path(machines), prev_path), out, force=force_thumbs, jobs=jobs)
    if repo is None:
        repo = S.Repo(machines=Path(machines), list_path=Path(list_path), prev_path=prev_path, out=out, now=now)
    recs, meta = repo.recs, repo.meta
    C.write_atomic(out / S.PAGES["machines"], render_machines(repo))
    C.write_atomic(out / "index.html", render_home(repo))
    C.write_atomic(out / "data.json", records_json(recs) + "\n")
    C.write_atomic(meta["kill_ledger_path"], json.dumps(meta["kill_ledger"], indent=1, sort_keys=True) + "\n")
    if root_index:
        write_root_index(Path(machines).resolve().parent)
    counts = Counter(r["bucket"] for r in recs)
    counts7 = Counter(bucket7(r) for r in recs)
    return {"out": out / "index.html", "machines_page": out / S.PAGES["machines"],
            "counts": {k: counts.get(k, 0) for k in BUCKET_KEYS}, "counts7": {k: counts7.get(k, 0) for k in KEYS8},
            "thumbs": tinfo, "off_list": {r["tm"]: r["off"]["short"] for r in recs if r.get("off")}, "n": meta["n"],
            "seconds": round(time.time() - t0, 1), "missing_thumbs": sum(1 for r in recs if not r["thumb"]),
            "live": sum(1 for r in recs if r.get("live") and r["bucket"] not in SOLVED_BUCKETS)}


SCREENS_JS = r"""
const { chromium } = require(process.argv[2]);
(async () => {
  const [core, exe, base, dir, pagesJson] = process.argv.slice(2);
  const pages = JSON.parse(pagesJson);            // [[name, URL relative to dashboard/]]
  const browser = await chromium.launch({ executablePath: exe, headless: true });
  const shots = [];
  for (const [w, h] of [[1920, 1080], [1280, 720], [390, 844]]) {
    for (const scheme of (w === 1920 ? ['light', 'dark'] : ['light'])) {
      const ctx = await browser.newContext({ viewport: { width: w, height: h }, colorScheme: scheme });
      const page = await ctx.newPage();
      const errors = [];
      page.on('pageerror', e => errors.push(String(e)));
      const tag = `${w}x${h}` + (scheme === 'dark' ? '-dark' : '');
      const snap = async (name) => { await page.waitForTimeout(400); const f = `${dir}/${tag}-${name}.png`;
        await page.screenshot({ path: f }); shots.push(f); };
      for (const [name, rel] of pages) {
        await page.goto(new URL(rel, base).href, { waitUntil: 'load' });
        if (name === 'machines') {
          await page.evaluate(() => { try { sessionStorage.clear() } catch (e) {} });
          await page.reload({ waitUntil: 'load' });
        }
        await snap(name);
      }
      if (scheme === 'dark') { await ctx.close(); continue; }
      await page.goto(new URL('machines.html', base).href, { waitUntil: 'load' });
      for (const id of ['b-claimed', 'b-parked', 'untouched']) {
        await page.evaluate(i => { const e = document.getElementById(i); if (e.tagName === 'DETAILS') e.open = true;
          const u = document.getElementById('unmore'); if (i === 'untouched' && u && !u.hidden) u.click();
          e.scrollIntoView(); }, id);
        await snap('machines-' + id.replace('b-', ''));
      }
      if (w < 500) {
        await page.evaluate(() => scrollTo(0, 0));
        await page.click('details.sn-menu summary');
        await snap('nav-menu');
        await ctx.close(); continue;
      }
      await page.evaluate(() => scrollTo(0, 0));
      await page.fill('#q', 'bell eats');
      await page.waitForTimeout(300);
      await snap('machines-search-bell-eats');
      await page.fill('#q', '');
      await page.click('button.mx-chip[data-fb="parked"]');
      await page.waitForTimeout(200);
      await snap('machines-chip-parked');
      await ctx.close();
      if (errors.length) { console.error(errors.join('\n')); process.exit(1); }
    }
  }
  await browser.close();
  console.log(JSON.stringify(shots));
})().catch(e => { console.error(e); process.exit(1); });
"""


def screen_pages(repo) -> list[tuple[str, str]]:
    """What --screens shoots: [(name, URL relative to dashboard/)]: every top-level page, then 3 machine pages (a
    kill with its own card, a derived kill without observe.json, a cryptid candidate) when such folders exist."""
    pages = [(k, f) for k, f in S.PAGES.items()]
    picks: dict[str, str] = {}
    for r in sorted((r for r in repo.recs if r["tm"] in repo.dirs), key=lambda r: r.get("kill_no") or 999):
        has_obs = (repo.dirs[r["tm"]] / "observe.json").is_file()
        if r["status"] in KILLED and has_obs:
            picks.setdefault("machine-kill", r["tm"])
        elif r["status"] in KILLED and r.get("parent"):
            picks.setdefault("machine-delta-kill", r["tm"])
        elif r["status"] == "CRYPTID_CANDIDATE":
            picks.setdefault("machine-cryptid", r["tm"])
    for k in ("machine-kill", "machine-delta-kill", "machine-cryptid"):
        if k in picks:
            pages.append((k, f"../machines/{quote(picks[k])}/index.html"))
    return pages


PW_CORE = TOOLS / "explorer" / "node_modules" / "playwright-core"   # this project's own (CLAUDE.md)


def find_browser():
    """(node, playwright-core, chrome-headless-shell, extra lib dir or None) for headless checks of our own pages,
    or None. playwright-core is this project's (tools/explorer/node_modules, or $PLAYWRIGHT_CORE), never another
    project's."""
    import glob
    import shutil
    core = os.environ.get("PLAYWRIGHT_CORE") or (str(PW_CORE) if PW_CORE.is_dir() else None)
    exes = sorted(glob.glob(str(Path.home() / ".cache/ms-playwright/chromium_headless_shell-*/"
                                "chrome-headless-shell-linux64/chrome-headless-shell")))
    node = shutil.which("node")
    if not core or not exes or not node:
        return None
    libs = Path(__file__).resolve().parent / "explorer/.syslibs/usr/lib/x86_64-linux-gnu"
    return node, core, exes[-1], (str(libs) if (libs / "libnspr4.so").exists() else None)


def take_screens(out: Path = OUT, repo=None) -> list[str]:
    """Screenshots of every top-level page and 3 machine pages (screen_pages; 1920x1080 light + dark, 1280x720,
    390x844, plus the Machines groups, search, class menu and the phone nav menu) into dashboard/screens/. Needs
    playwright-core + chrome-headless-shell (find_browser). Uses the local server if it is up, else file://."""
    import subprocess
    import tempfile
    import urllib.request
    pw = find_browser()
    if not pw:
        raise SystemExit("screens: playwright-core / chrome-headless-shell not found")
    node, core, exe, libs = pw
    url = f"{SERVER}/dashboard/"
    try:
        urllib.request.urlopen(url, timeout=3).close()
        if out.resolve() != OUT.resolve():
            raise OSError
    except OSError:
        url = out.resolve().as_uri() + "/"
    sdir = out / "screens"
    sdir.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory() as td:
        js = Path(td) / "screens.js"
        js.write_text(SCREENS_JS)
        env = dict(os.environ)
        if libs:
            env["LD_LIBRARY_PATH"] = libs + (":" + env["LD_LIBRARY_PATH"] if env.get("LD_LIBRARY_PATH") else "")
        pages = screen_pages(repo or S.Repo(out=out))
        r = subprocess.run([node, str(js), core, exe, url, str(sdir), json.dumps(pages)], capture_output=True,
                           text=True, env=env, timeout=600)
    if r.returncode:
        raise SystemExit(f"screens failed: {r.stderr[-1500:]}")
    return json.loads(r.stdout.strip().splitlines()[-1])


def main(argv: list[str] | None = None) -> int:
    ap = argparse.ArgumentParser(description="Build the whole site (tools/sitekit.build_all, = tools/site.py): the "
                                             "thumbnails, every machine page, Home, Machines, Submissions, Reports, "
                                             "Decisions, data.json, kills.json and the root index.html.")
    ap.add_argument("--list", default=str(LIST), help="holdout list (default: %(default)s)")
    ap.add_argument("--prev-list", default=str(PREV_LIST),
                    help="previous list: line numbers of off-list machines (default: %(default)s; '' for none)")
    ap.add_argument("--out", default=str(OUT), help="output directory (default: %(default)s)")
    ap.add_argument("--no-thumbs", action="store_true", help="do not draw missing thumbnails")
    ap.add_argument("--force-thumbs", action="store_true", help="redraw every thumbnail")
    ap.add_argument("--jobs", type=int, default=THUMB_JOBS, help="thumbnail processes (max %(default)s, niced)")
    ap.add_argument("--no-root-index", action="store_true", help="do not write the repo-root redirect index.html")
    ap.add_argument("--no-cards-index", action="store_true",
                    help="skip the machine pages (machines/<tm>/index.html); everything else is built")
    ap.add_argument("--screens", action="store_true", help="after building, screenshot every top-level page and 3 "
                                                           "machine pages into dashboard/screens/")
    a = ap.parse_args(argv)
    out = Path(a.out).resolve()
    repo = S.Repo(list_path=Path(a.list).resolve(), prev_path=Path(a.prev_list).resolve() if a.prev_list else None,
                  out=out)
    res = S.build_all(repo, thumbs=not a.no_thumbs, force_thumbs=a.force_thumbs, jobs=a.jobs,
                      machine_pages=not a.no_cards_index, root_index=not a.no_root_index)
    d = res["dashboard"]
    t = res["thumbs"]
    if t:
        print(f"thumbnails: {t['drawn']} drawn in {t['seconds']} s" + (f", {len(t['errors'])} failed" if t["errors"] else ""))
        for tm, e in list(t["errors"].items())[:10]:
            print(f"   thumb error {tm}: {e}", file=sys.stderr)
    print(f"{d['n']} on the list; buckets: " + ", ".join(f"{k} {v}" for k, v in d["counts7"].items())
          + f" ({d['live']} working now)")
    if d["missing_thumbs"]:
        print(f"warn: {d['missing_thumbs']} machines have no thumbnail yet")
    for tm, why in d["off_list"].items():
        print(f"off the list (shown): {tm}: {why}")
    bad = [x for x in res["machines"] if x[2]]
    if not a.no_cards_index:
        print(f"{len(res['machines']) - len(bad)} machine pages (machines/<tm>/index.html)"
              + (f", {len(bad)} failed" if bad else ""))
    for tm, _, err in bad:
        print(f"   ERROR machines/{tm}/index.html: {err}", file=sys.stderr)
    url = C.served_url(d["out"])
    print(f"{d['out']}  {(url or '').replace('/index.html', '/')}  ({res['seconds']} s)")
    for f in (d["machines_page"], res["submissions"], res["decisions"]["out"], res["reports"]):
        print(f"{f}  {C.served_url(f) or ''}".rstrip())
    if a.screens:
        for f in take_screens(out, repo):
            print(f"screen: {f}")
    return 1 if bad else 0


if __name__ == "__main__":
    sys.exit(main())