systemless 0.92.0

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

#[test]
fn idle_snapshot_preserves_extended_cpu_state() {
    let mut cpu = m68k::CpuCore::new();
    cpu.fpr[0] = m68k::fpu::FloatX80::from_extended(0x3FFF, 0x8000_0000_0000_0000);
    let baseline = CpuArchitecturalSnapshot::capture(&cpu);

    cpu.change_of_flow = !cpu.change_of_flow;
    assert_eq!(
        baseline,
        CpuArchitecturalSnapshot::capture(&cpu),
        "internal flow bookkeeping must not participate in an idle-cycle proof"
    );

    cpu.fpr[0].mantissa ^= 1;
    assert_ne!(
        baseline,
        CpuArchitecturalSnapshot::capture(&cpu),
        "80-bit FPU precision must participate in an idle-cycle proof"
    );

    cpu.fpr[0].mantissa ^= 1;
    cpu.mmu_crp_aptr = 0x1234_5000;
    assert_ne!(
        baseline,
        CpuArchitecturalSnapshot::capture(&cpu),
        "canonical MMU state must participate in an idle-cycle proof"
    );

    cpu.mmu_crp_aptr = 0;
    cpu.prefetch_queue[1] = 0x4E71;
    assert_ne!(
        baseline,
        CpuArchitecturalSnapshot::capture(&cpu),
        "precise prefetch state must participate in an idle-cycle proof"
    );
}

#[test]
fn exact_idle_cycle_requires_cpu_and_memory_repeat() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let sp = 0x0010_0000u32;
    let scratch = 0x0020_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA975;
    runner.m68k.cpu.write_reg(Register::A7, sp);
    runner.bus.write_long(sp, 100);
    runner.bus.write_long(scratch, 0x1122_3344);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    assert!(runner.bus.fast_mem_window().is_none());

    // A complete guest iteration may use its stack and locals as long as
    // it restores every touched byte before returning to the boundary.
    runner.bus.write_long(scratch, 0xAABB_CCDD);
    runner.bus.write_long(scratch, 0x1122_3344);
    runner.note_idle_cycle_trap_result(0xA971); // null EventAvail result at SP

    assert!(runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert_eq!(runner.guest_tick(), 105);
    assert_eq!(runner.bus.read_long(0x016A), 105);
    assert_eq!(runner.bus.read_long(sp), 100);
    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.idle_cycle_sleep.is_some());
    assert!(
        runner.bus.fast_mem_window().is_none(),
        "the parked sleep keeps a write guard armed across the frontend boundary"
    );

    runner.dispatcher.set_sent_open_app_event_for_test(true);
    assert!(runner.try_resume_proven_idle_cycle(Some(110)));
    assert_eq!(runner.guest_tick(), 110);
    assert_eq!(runner.bus.read_long(sp), 100);
    assert!(runner.idle_cycle_sleep.is_some());

    runner.push_mouse_down(20, 30);
    assert!(
        !runner.try_resume_proven_idle_cycle(Some(115)),
        "new host input must revoke a proof before the guest event loop is skipped"
    );
    assert_eq!(runner.guest_tick(), 110);
    assert!(runner.idle_cycle_sleep.is_none());
    assert!(runner.bus.fast_mem_window().is_some());
}

#[test]
fn busy_poller_overflows_one_journal_then_backs_off_for_the_tick() {
    // EV Override's boot and speed calibration poll TickCount between
    // bursts of real work. Such a site must cost at most one capped
    // journal per tick, never a journal that grows with the work.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let work = 0x0030_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.set_guest_tick_for_test(100);

    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    assert!(runner.bus.fast_mem_window().is_none());

    // The "cycle" writes far more than a wait ever does: the journal
    // counts 32-bit words, so this touches twice the cap in words.
    for offset in 0..(8 * crate::memory::bus::WRITE_PROBE_MAX_ENTRIES as u32) {
        runner.bus.write_byte(work + offset, 0xAA);
    }
    assert!(
        runner.bus.fast_mem_window().is_some(),
        "the bus voids an overflowing journal immediately, without waiting for the runner"
    );

    // Back at the site: the observation is dropped and the site is
    // marked busy for this tick, so later same-tick arrivals do not
    // re-arm a journal that would only overflow again.
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.idle_cycle_site_is_busy(trap_pc, 100));
    for _ in 0..4 {
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_none());
        assert!(runner.bus.fast_mem_window().is_some());
    }
    assert_eq!(
        runner.guest_tick(),
        100,
        "a busy site is never fast-forwarded"
    );

    // A new tick lifts the back-off: the site is observed afresh.
    runner.set_guest_tick_for_test(101);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    assert!(runner.bus.fast_mem_window().is_none());
}

#[test]
fn a_site_that_keeps_failing_gets_two_probes_per_tick_then_none() {
    // The boot storm: EV Override started 928,781 probes in 17 s of
    // boot, 926,295 failing on changed memory, because a failed probe
    // was re-armed on the very next same-tick arrival. Now a site gets
    // a first probe and one retry per tick, then nothing until the
    // tick changes -- and every arrival in between costs no journal.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let scratch = 0x0020_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.set_guest_tick_for_test(100);

    // Arrival 1: baseline. Arrival 2: probe #1 armed.
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    // Work that does not restore memory; arrival 3 fails on memory and
    // re-arms once (probe #2).
    runner.bus.write_long(scratch, 0x1111_1111);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some(), "one retry is allowed");
    assert!(runner.bus.fast_mem_window().is_none());
    // More work; arrival 4 fails again: budget spent, no journal, and
    // every later same-tick arrival is a plain return.
    runner.bus.write_long(scratch, 0x2222_2222);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.bus.fast_mem_window().is_some());
    for _ in 0..8 {
        runner.bus.write_long(scratch, 0x3333_3333);
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_none());
        assert!(runner.bus.fast_mem_window().is_some());
    }
    assert_eq!(runner.guest_tick(), 100);

    // Next tick: the site is observed afresh, and a cycle that now
    // restores its writes proves and parks exactly as before.
    runner.set_guest_tick_for_test(101);
    runner.bus.write_long(0x016A, 101);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    runner.bus.write_long(scratch, 0xAAAA_AAAA);
    runner.bus.write_long(scratch, 0x3333_3333);
    runner.note_idle_cycle_trap_result(0xA971);
    assert!(runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert_eq!(runner.guest_tick(), 105);
    assert!(runner.idle_cycle_sleep.is_some());
}

#[test]
fn journal_complete_traps_do_not_cancel_an_idle_probe() {
    // EV Override's crawl idles in a GetKeys/Button cycle interleaved
    // with SANE math; SimCity 2000's dialog loops poll LocalToGlobal,
    // the Window Manager queries and TEIdle. The proof must survive every
    // one of those traps, in the plain and the auto-pop encodings, and
    // still cancel on anything with unjournaled consequences.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.set_guest_tick_for_test(100);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());

    for opcode in [
        0xA972u16, 0xA973, 0xA974, 0xA975, 0xA976, 0xA9EB, 0xA9EC, 0xA870, 0xA871, 0xA917, 0xA924,
        0xA92C, 0xA9DA, 0xA8AD, 0xAC70, 0xAC71, 0xAD17, 0xAD24, 0xAD2C, 0xADDA, 0xACAD,
    ] {
        runner.note_idle_cycle_trap_result(opcode);
        assert!(
            runner.idle_cycle_probe.is_some(),
            "journal-complete trap {opcode:04X} must not cancel the probe"
        );
    }
    // QDExtensions multiplexes on the D0 selector: the
    // GetGWorld/SetGWorld save/restore pair a poll loop brackets
    // its hit-testing with survives in both encodings.
    for selector in [0x0008_0005u32, 0x0008_0006] {
        runner.m68k.cpu.write_reg(Register::D0, selector);
        for opcode in [0xAB1Du16, 0xAF1D] {
            runner.note_idle_cycle_trap_result(opcode);
            assert!(
                runner.idle_cycle_probe.is_some(),
                "admitted QDExtensions selector {selector:08X} must not cancel the probe"
            );
        }
    }
    // MoveTo mirrors pnLoc into dispatcher state the journal cannot
    // see; anything with host-cached consequences must cancel.
    runner.note_idle_cycle_trap_result(0xA893);
    assert!(runner.idle_cycle_probe.is_none());
}

#[test]
fn handle_locks_and_rejected_sound_commands_do_not_cancel_an_idle_probe() {
    // Bad Mojo's demo loop polls GetNextEvent, FindWindow, HLock and a
    // no-wait SndDoCommand that the full channel queue rejects until
    // frame-boundary audio servicing drains it. Lock calls and rejected
    // commands leave the proof intact; an accepted command, which
    // changes channel state, and MoveHHi, which may write resource
    // backing, cancel.
    let probe = |runner: &mut FixtureRunner| {
        let trap_pc = 0x0002_0000u32;
        runner.idle_cycle_probe = None;
        runner.idle_cycle_sites = [IdleCycleSiteRecord::default(); IDLE_CYCLE_SITE_SLOTS];
        runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
        runner.set_guest_tick_for_test(100);
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_some());
    };
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    probe(&mut runner);
    for opcode in [0xA029u16, 0xA02A, 0xA229, 0xA42A] {
        runner.note_idle_cycle_trap_result(opcode);
        assert!(
            runner.idle_cycle_probe.is_some(),
            "handle lock trap {opcode:04X} must not cancel the probe"
        );
    }
    // SndDoCommand pops to its OSErr result.
    runner.bus.write_word(0x0010_0000, (-203i16) as u16); // queueFull
    for opcode in [0xA803u16, 0xAC03] {
        runner.note_idle_cycle_trap_result(opcode);
        assert!(
            runner.idle_cycle_probe.is_some(),
            "rejected SndDoCommand {opcode:04X} must not cancel the probe"
        );
    }
    runner.bus.write_word(0x0010_0000, 0); // noErr: the command was taken
    runner.note_idle_cycle_trap_result(0xA803);
    assert!(
        runner.idle_cycle_probe.is_none(),
        "an accepted command must cancel"
    );

    probe(&mut runner);
    runner.note_idle_cycle_trap_result(0xA064); // MoveHHi
    assert!(runner.idle_cycle_probe.is_none(), "MoveHHi must cancel");
}

#[test]
fn counted_idle_passes_stop_before_the_update_would_set_different_flags() {
    // ADDQ.W #1 from 0x001C: results up to 0x7FFF keep N, Z, V and C clear.
    assert_eq!(passes_with_unchanged_flags(0x001C, 1, 2), 0x7FFF - 0x001C);
    // Upper half: stop before the carry out at 0xFFFF -> 0x0000.
    assert_eq!(passes_with_unchanged_flags(0x8005, 1, 2), 0xFFFF - 0x8005);
    // The observed pass itself crossed the sign bit or produced zero.
    assert_eq!(passes_with_unchanged_flags(0x8000, 1, 2), 0);
    assert_eq!(passes_with_unchanged_flags(0x0000, 1, 2), 0);
    // Byte and long counters, and a step of four.
    assert_eq!(passes_with_unchanged_flags(0x10, 4, 1), (0x7F - 0x10) / 4);
    assert_eq!(
        passes_with_unchanged_flags(0x0001_0000, 1, 4),
        0x7FFF_FFFF - 0x0001_0000
    );
    // SUBQ.W #1 (step 0xFFFF): stop before zero, or before crossing back
    // below the sign bit.
    assert_eq!(passes_with_unchanged_flags(0x0010, 0xFFFF, 2), 0x0F);
    assert_eq!(passes_with_unchanged_flags(0x8010, 0xFFFF, 2), 0x10);
    assert_eq!(passes_with_unchanged_flags(0x7FFF, 0xFFFF, 2), 0);
}

#[test]
fn only_add_or_subtract_immediate_to_memory_may_update_an_idle_counter() {
    assert_eq!(add_immediate_to_memory_width(0x526D), Some(2)); // ADDQ.W #1,d16(A5)
    assert_eq!(add_immediate_to_memory_width(0x52B9), Some(4)); // ADDQ.L #1,abs.L
    assert_eq!(add_immediate_to_memory_width(0x5310), Some(1)); // SUBQ.B #1,(A0)
    assert_eq!(add_immediate_to_memory_width(0x066D), Some(2)); // ADDI.W #imm,d16(A5)
    assert_eq!(add_immediate_to_memory_width(0x04B8), Some(4)); // SUBI.L #imm,abs.W
    assert_eq!(add_immediate_to_memory_width(0x5241), None); // ADDQ.W #1,D1
    assert_eq!(add_immediate_to_memory_width(0x5249), None); // ADDQ.W #1,A1
    assert_eq!(add_immediate_to_memory_width(0x51C8), None); // DBF D0 (size 3)
    assert_eq!(add_immediate_to_memory_width(0x527A), None); // PC-relative destination
    assert_eq!(add_immediate_to_memory_width(0x302D), None); // MOVE.W d16(A5),D0
}

#[test]
fn an_idle_counter_is_verified_only_when_its_update_is_its_sole_reader() {
    use crate::memory::{AccessHit, AccessSource};
    let pc = 0x0061_7CAC;
    let hit = |write, address, len, source| AccessHit {
        write,
        address,
        len,
        source,
    };
    let rmw = AccessSource::Instruction(pc);
    let changes = [(0x0060_7724u32, 0x001C_0000u32, 0x001D_0000u32)];
    let opcode = |at: u32| if at == pc { 0x526D } else { 0x302D };
    let bytes = |address: u32| match address {
        0x0060_7724 => (0x00, 0x00),
        0x0060_7725 => (0x1C, 0x1D),
        _ => (0, 0),
    };
    let counter = IdleCounter {
        address: 0x0060_7724,
        width: 2,
        step: 1,
    };
    let pair = [
        hit(false, 0x0060_7724, 2, rmw),
        hit(true, 0x0060_7724, 2, rmw),
    ];
    assert_eq!(
        verified_idle_counter(&pair, &changes, opcode, bytes),
        Some(counter)
    );

    // Another instruction also reads it: its value can steer the loop.
    let other = AccessSource::Instruction(pc + 8);
    let read_elsewhere = [pair[0], pair[1], hit(false, 0x0060_7724, 2, other)];
    assert_eq!(
        verified_idle_counter(&read_elsewhere, &changes, opcode, bytes),
        None
    );
    // Host code (a trap) touched it.
    let host = [hit(false, 0x0060_7724, 2, AccessSource::Host), pair[1]];
    assert_eq!(verified_idle_counter(&host, &changes, opcode, bytes), None);
    // A load and a store by different instructions, or by a MOVE.
    let split = [pair[0], hit(true, 0x0060_7724, 2, other)];
    assert_eq!(verified_idle_counter(&split, &changes, opcode, bytes), None);
    let moved = [
        hit(false, 0x0060_7724, 2, other),
        hit(true, 0x0060_7724, 2, other),
    ];
    assert_eq!(verified_idle_counter(&moved, &changes, opcode, bytes), None);
    // Bad Mojo's ADDQ.L #1 on a long at $00607722: the bus stores only
    // the two low bytes that changed.
    let long_changes = [
        (0x0060_7720u32, 0x0000_0000u32, 0x0000_0000u32),
        (0x0060_7724, 0x0863_0000, 0x0864_0000),
    ];
    let long_changes = &long_changes[1..];
    let long_opcode = |at: u32| if at == pc { 0x52AD } else { 0x302D }; // ADDQ.L #1,d16(A5)
    let long_bytes = |address: u32| match address {
        0x0060_7724 => (0x08, 0x08),
        0x0060_7725 => (0x63, 0x64),
        _ => (0, 0),
    };
    let long_hits = [
        hit(false, 0x0060_7722, 4, rmw),
        hit(true, 0x0060_7724, 1, rmw),
        hit(true, 0x0060_7725, 1, rmw),
    ];
    assert_eq!(
        verified_idle_counter(&long_hits, long_changes, long_opcode, long_bytes),
        Some(IdleCounter {
            address: 0x0060_7722,
            width: 4,
            step: 1
        })
    );
    // A write outside the operand the instruction read.
    let stray = [long_hits[0], hit(true, 0x0060_7726, 1, rmw)];
    assert_eq!(
        verified_idle_counter(&stray, long_changes, long_opcode, long_bytes),
        None
    );
    // A changed byte the counter does not cover.
    let wider = [(0x0060_7724u32, 0x001C_0000u32, 0x001D_0001u32)];
    assert_eq!(verified_idle_counter(&pair, &wider, opcode, bytes), None);
}

#[test]
fn failed_counter_verifications_back_a_site_off_exponentially() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let site = 0x0002_0000u32;
    let resume = |runner: &FixtureRunner| {
        runner
            .idle_cycle_sites
            .iter()
            .find(|rec| rec.site == site)
            .unwrap()
            .counter_resume_tick
    };
    for (failure, wait) in [4u32, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 2048]
        .iter()
        .enumerate()
    {
        runner.note_idle_counter_verification(site, 1000, false);
        assert_eq!(resume(&runner), 1000 + wait, "failure {}", failure + 1);
    }
    runner.note_idle_counter_verification(site, 5000, true);
    assert_eq!(resume(&runner), 5000);
    runner.note_idle_counter_verification(site, 5000, false);
    assert_eq!(resume(&runner), 5004, "success resets the streak");
}

#[test]
fn idle_cycle_backoff_expires_across_tick_wrap() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.idle_cycle_sites[0] = IdleCycleSiteRecord {
        site: 0x20000,
        tick: u32::MAX - 1,
        probes: 0,
        cancel_streak: 2,
        resume_tick: (u32::MAX - 1).wrapping_add(4),
        ..IdleCycleSiteRecord::default()
    };
    assert!(runner.idle_cycle_site_is_busy(0x20000, u32::MAX));
    assert!(runner.idle_cycle_site_is_busy(0x20000, 0));
    assert!(runner.idle_cycle_site_is_busy(0x20000, 1));
    assert!(!runner.idle_cycle_site_is_busy(0x20000, 2));
}

#[test]
fn repeated_trap_cancels_back_a_site_off_and_a_closed_proof_resets_it() {
    // A poll loop can die to a foreign trap on every pass at
    // several sites. One cancel is routine; a streak engages an
    // exponential backoff so a doomed site stops paying the
    // armed-journal tax on every poll, and a probe that later
    // closes on its origin site clears the backoff again.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA975;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);

    for _ in 0..2 {
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_some());
        runner.note_idle_cycle_trap_result(0xA893); // MoveTo cancels
        assert!(runner.idle_cycle_probe.is_none());
    }

    // Two consecutive trap cancels back the site off: no probe can
    // begin here while the backoff runs.
    for _ in 0..4 {
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    }
    assert!(runner.idle_cycle_probe.is_none());

    // Backoff expired (streak 2 = 4 ticks): probing resumes, and a
    // proof that closes on its origin resets the streak entirely.
    runner.bus.write_long(0x016A, 104);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());
    assert!(runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    let rec = runner
        .idle_cycle_sites
        .iter()
        .find(|rec| rec.site == trap_pc)
        .expect("site record");
    assert_eq!(rec.cancel_streak, 0);
    assert_eq!(rec.resume_tick, 0);
}

#[test]
fn chrome_repaint_stays_out_of_an_armed_idle_journal() {
    // The runner repaints host-owned chrome every frame. Painted under an
    // armed idle-proof journal it would be recorded against the proof
    // (and at 8 bpp overflow it -- see
    // memory::bus::tests::suspended_write_probe_ignores_writes_and_rearms_intact);
    // the runner's wrapper must leave the journal armed and untouched.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let screen_base = 0x0040_0000u32;
    runner.dispatcher.screen_mode = (screen_base, 1024, 1024, 768, 8);
    runner.bus.write_long(0x0824, screen_base);
    runner.bus.write_word(0x0BAA, 20);

    runner.bus.begin_write_probe();
    runner.redraw_chrome_outside_idle_journal();
    assert!(!runner.bus.take_write_probe_overflow());
    assert!(
        runner.bus.suspend_write_probe().is_some(),
        "the journal must still be armed after the repaint"
    );
    runner.bus.cancel_write_probe();

    runner.bus.begin_write_probe();
    runner.redraw_chrome_outside_idle_journal();
    assert!(runner.bus.finish_write_probe_unchanged());
}

#[test]
fn first_parked_repaint_revokes_the_park_when_guest_overwrote_a_chrome_pixel() {
    // Issue #1052: the park reuses its proof without re-execution, so a
    // suspended repaint that is not byte-identical (guest code scribbled
    // over chrome before entering the idle loop) would silently change
    // guest RAM relative to the proven state. It must revoke the park.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let screen_base = 0x0040_0000u32;
    runner.dispatcher.screen_mode = (screen_base, 1024, 1024, 768, 8);
    runner.bus.write_long(0x0824, screen_base);
    runner.bus.write_word(0x0BAA, 20);

    runner.dispatcher.menus.push(crate::trap::menu::Menu {
        id: 1,
        title: String::from("Apple"),
        items: Vec::new(),
        enabled: true,
        handle: 0,
        in_menu_bar: true,
        hierarchical: false,
        visible_in_menu_bar: true,
    });
    runner.dispatcher.front_window = 0;
    runner.dispatcher.fullscreen_locked = false;
    runner.dispatcher.menu_bar_hidden = false;

    // Establish the current chrome pixels, then scribble one menu-bar
    // pixel the way pre-idle guest drawing would.
    runner.redraw_chrome_outside_idle_journal();
    let pixel = screen_base + 5 * 1024 + 100;
    assert_ne!(
        runner.bus.read_byte(pixel),
        0xAA,
        "fixture: a painted menu-bar pixel must differ from the sentinel"
    );
    runner.bus.write_byte(pixel, 0xAA);

    runner.park_proven_idle_cycle(0x0002_0000, 205);
    assert!(runner.idle_cycle_sleep.is_some());

    runner.redraw_chrome_outside_idle_journal();
    assert_ne!(
        runner.bus.read_byte(pixel),
        0xAA,
        "the repaint repainted the scribbled chrome pixel"
    );
    assert!(
        runner.idle_cycle_sleep.is_none(),
        "a repaint that changed guest RAM must revoke the park"
    );
    assert!(
        runner.bus.suspend_write_probe().is_none(),
        "the revoked park's journal must be closed"
    );
}

#[test]
fn byte_identical_parked_repaints_keep_the_park() {
    // The control for the revocation gate: chrome that is already
    // current repaints byte-identically, the park survives, and its
    // journal stays armed and unchanged.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let screen_base = 0x0040_0000u32;
    runner.dispatcher.screen_mode = (screen_base, 1024, 1024, 768, 8);
    runner.bus.write_long(0x0824, screen_base);
    runner.bus.write_word(0x0BAA, 20);

    runner.dispatcher.menus.push(crate::trap::menu::Menu {
        id: 1,
        title: String::from("Apple"),
        items: Vec::new(),
        enabled: true,
        handle: 0,
        in_menu_bar: true,
        hierarchical: false,
        visible_in_menu_bar: true,
    });
    runner.dispatcher.front_window = 0;
    runner.dispatcher.fullscreen_locked = false;
    runner.dispatcher.menu_bar_hidden = false;

    runner.redraw_chrome_outside_idle_journal();
    runner.park_proven_idle_cycle(0x0002_0000, 205);
    assert!(runner.idle_cycle_sleep.is_some());

    runner.redraw_chrome_outside_idle_journal();
    runner.redraw_chrome_outside_idle_journal();
    assert!(
        runner.idle_cycle_sleep.is_some(),
        "byte-identical repaints must keep the park"
    );
    let journal = runner
        .bus
        .suspend_write_probe()
        .expect("the park's journal must still be armed");
    runner.bus.resume_write_probe(journal);
    assert!(runner.bus.finish_write_probe_unchanged());
}

#[test]
fn host_snapshot_tracks_window_list_and_pending_native_menu_selection() {
    let mut runner = FixtureRunner::new(1024 * 1024, FixtureRunnerConfig::default());
    let before = IdleCycleHostSnapshot::capture(&runner.dispatcher);
    runner.dispatcher.window_list.push(0x0012_3456);
    assert_ne!(before, IdleCycleHostSnapshot::capture(&runner.dispatcher));
    runner.dispatcher.window_list.pop();
    assert_eq!(before, IdleCycleHostSnapshot::capture(&runner.dispatcher));
    runner
        .dispatcher
        .pending_native_menu_selection
        .stage((3, 1));
    assert_ne!(before, IdleCycleHostSnapshot::capture(&runner.dispatcher));
}

#[test]
fn window_and_textedit_mutators_still_cancel_an_idle_probe() {
    // The admission is a list of specific traps, not a range: the
    // neighbours that mutate host-mirrored window or TextEdit state
    // must go on cancelling.
    for opcode in [0xA918u16, 0xA91F, 0xA928, 0xA929, 0xA9D8, 0xA9D9, 0xA9DC] {
        let mut runner = FixtureRunner::new(1024 * 1024, FixtureRunnerConfig::default());
        let trap_pc = 0x0002_0000u32;
        runner.m68k.cpu.write_reg(Register::A7, 0x0008_0000);
        runner.set_guest_tick_for_test(100);
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_some());
        runner.note_idle_cycle_trap_result(opcode);
        assert!(
            runner.idle_cycle_probe.is_none(),
            "{opcode:04X} must cancel the probe"
        );
    }
}

#[test]
fn teidle_inside_a_proof_parks_when_idle_and_fails_on_memory_when_it_blinks() {
    // TEIdle is admitted because it either writes nothing or stamps
    // caretState/caretTime into guest RAM before it paints. Both halves
    // of that claim, through the real handler under a real probe.
    for (blink_due, expect_park) in [(false, true), (true, false)] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let trap_pc = 0x0002_0000u32;
        let sp = 0x0010_0000u32;
        let te_handle = 0x0020_0000u32;
        let te_rec = 0x0020_0100u32;
        runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
        runner.m68k.cpu.core.ppc = trap_pc;
        runner.m68k.cpu.core.ir = 0xA975; // the loop's TickCount anchor
        runner.bus.write_long(0x016A, 100);
        runner.set_guest_tick_for_test(100);
        runner.bus.write_long(te_handle, te_rec);
        runner.bus.write_word(te_rec + 0x20, 5); // selStart
        runner.bus.write_word(te_rec + 0x22, 5); // selEnd: an insertion point
        runner.bus.write_word(te_rec + 0x24, 1); // active
        runner
            .bus
            .write_long(te_rec + 0x34, if blink_due { 60 } else { 100 }); // caretTime
        runner.bus.write_word(te_rec + 0x38, 0); // caretState
                                                 // The argument slot holds hTE before the journal opens, so the
                                                 // loop's push below rewrites the same bytes.
        runner.bus.write_long(sp - 4, te_handle);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
        assert!(runner.idle_cycle_probe.is_some());

        let before = CpuArchitecturalSnapshot::capture(&runner.m68k.cpu.core);
        // One loop iteration: push hTE, call TEIdle (which pops it).
        runner.m68k.cpu.write_reg(Register::A7, sp - 4);
        runner.bus.write_long(sp - 4, te_handle);
        let result =
            runner
                .dispatcher
                .dispatch_dialog(true, 0x1DA, &mut runner.m68k.cpu, &mut runner.bus);
        assert!(result.unwrap().is_ok());
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
        runner.note_idle_cycle_trap_result(0xA9DA);
        assert!(runner.idle_cycle_probe.is_some(), "TEIdle is admitted");
        assert_eq!(
            before,
            CpuArchitecturalSnapshot::capture(&runner.m68k.cpu.core),
            "TEIdle must leave the architectural state as it found it"
        );
        assert_eq!(runner.bus.read_word(te_rec + 0x38), u16::from(blink_due));

        let parked = runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105));
        assert_eq!(parked, expect_park, "blink_due={blink_due}");
        assert_eq!(runner.idle_cycle_sleep.is_some(), expect_park);
    }
}

#[test]
fn poll_anchor_covers_the_input_family_only() {
    for opcode in [0xA972u16, 0xA973, 0xA974, 0xA975, 0xA976, 0xAD76] {
        assert!(is_poll_anchor_trap(opcode), "{opcode:04X}");
    }
    for opcode in [0xA970u16, 0xA971, 0xA991, 0xA9EB, 0xA893, 0x4E71] {
        assert!(!is_poll_anchor_trap(opcode), "{opcode:04X}");
    }
}

#[test]
fn input_poll_cycle_proves_and_parks_like_a_null_event_cycle() {
    // The crawl shape: a cycle anchored at a GetKeys site with no event
    // trap anywhere in it. The exact-state proof must park it to the
    // next tick exactly as it parks a null-event loop.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let sp = 0x0010_0000u32;
    let keymap = 0x0020_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA976;
    runner.m68k.cpu.write_reg(Register::A7, sp);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    // The prior (pre-proof) iteration already left the KeyMap and the
    // SANE-computed scroll position in place; the journal compares
    // against exactly this state.
    runner.bus.write_long(keymap, 0);
    runner.bus.write_long(keymap + 16, 0x0001_0000);

    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(105)));
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());

    // One full iteration: GetKeys rewrites the same all-zero KeyMap,
    // Button and TickCount report unchanged host state, SANE recomputes
    // the same scroll position into a scratch long.
    runner.bus.write_long(keymap, 0);
    runner.note_idle_cycle_trap_result(0xA976);
    runner.note_idle_cycle_trap_result(0xA974);
    runner.note_idle_cycle_trap_result(0xA975);
    runner.bus.write_long(keymap + 16, 0x0001_0000);
    runner.bus.write_long(keymap + 16, 0x0001_0000);
    runner.note_idle_cycle_trap_result(0xA9EB);
    assert!(
        runner.idle_cycle_probe.is_some(),
        "cycle traps kept the probe"
    );

    // At the frame's tick cap, a proven cycle parks (the GUI case:
    // sleep to the next frame instead of spinning out the cap).
    assert!(runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    assert_eq!(runner.guest_tick(), 100);
    assert!(runner.idle_cycle_sleep.is_some());
}

#[test]
fn period_two_poll_cycle_proves_and_advances() {
    // The measured EV Override crawl shape: the wait loop alternates
    // two polled keycodes through D5, so consecutive same-site
    // arrivals never match -- only every second one does. The proof
    // must hold its journal across the period and close on the
    // origin state.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    let set_d5 = |runner: &mut FixtureRunner, v: u32| runner.m68k.cpu.core.set_d(5, v);

    set_d5(&mut runner, 0x39);
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    assert!(
        runner.idle_cycle_probe.is_some(),
        "probe armed at 0x39 state"
    );

    set_d5(&mut runner, 0x2C);
    assert!(
        !runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)),
        "mid-period arrival must not prove"
    );
    assert!(
        runner.idle_cycle_probe.is_some(),
        "mid-period arrival must keep the probe alive"
    );

    set_d5(&mut runner, 0x39);
    assert!(
        runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)),
        "origin state closes the period-2 proof and parks at the cap"
    );
    assert!(runner.idle_cycle_sleep.is_some());
}

#[test]
fn aperiodic_state_walk_never_proves() {
    // A register marching through fresh values every pass is real
    // progress: the period tolerance must give up at the cap, not
    // fabricate a proof.
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    for step in 0..24u32 {
        runner.m68k.cpu.core.set_d(5, 0x1000 + step);
        assert!(
            !runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)),
            "step {step} must not prove"
        );
    }
    assert!(runner.idle_cycle_sleep.is_none());
}

#[test]
fn cycle_longer_than_period_cap_never_proves() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    runner.m68k.cpu.core.set_d(5, 0);
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    for state in 1..=IDLE_CYCLE_MAX_PERIOD {
        runner.m68k.cpu.core.set_d(5, u32::from(state));
        assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    }
    runner.m68k.cpu.core.set_d(5, 0);
    assert!(!runner.try_exact_null_event_cycle_fastfwd(trap_pc, Some(100)));
    assert!(runner.idle_cycle_sleep.is_none());
}

#[test]
fn exact_null_event_cycle_supports_alternating_sites_headlessly() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let site_a = 0x0002_0000u32;
    let site_b = 0x0002_1000u32;
    runner.m68k.cpu.write_reg(Register::PC, site_a + 2);
    runner.m68k.cpu.core.ppc = site_a;
    runner.m68k.cpu.core.ir = 0xA970;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    assert!(!runner.try_exact_null_event_cycle_fastfwd(site_a, None));
    assert!(!runner.try_exact_null_event_cycle_fastfwd(site_b, None));
    assert_eq!(runner.idle_cycle_last_seen, Some((site_a, 100)));

    assert!(!runner.try_exact_null_event_cycle_fastfwd(site_a, None));
    assert!(runner.idle_cycle_probe.is_some());
    assert!(!runner.try_exact_null_event_cycle_fastfwd(site_b, None));
    assert!(runner.idle_cycle_probe.is_some());

    assert!(!runner.try_exact_null_event_cycle_fastfwd(site_a, None));
    assert_eq!(runner.guest_tick(), 101);
    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.idle_cycle_sleep.is_none());
}

#[test]
fn exact_idle_cycle_rejects_an_architectural_cpu_change() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA970;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 101, Some(100)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 101, Some(100)));
    assert!(runner.idle_cycle_probe.is_some());

    runner.m68k.cpu.write_reg(Register::D3, 1);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 101, Some(100)));
    assert_eq!(runner.guest_tick(), 100);
    assert!(runner.idle_cycle_sleep.is_none());
    assert!(
        runner.idle_cycle_probe.is_some(),
        "a changed state may start a new observation but must not reuse the old proof"
    );
}

#[test]
fn exact_null_event_cycle_covers_the_complete_guest_state_machine() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let code = 0x0002_0000u32;
    let event = 0x0020_0000u32;
    let delay_base = 0x0021_0000u32;
    let tick_base = 0x0022_0000u32;
    let flag_base = 0x0023_0000u32;
    let stack = 0x0010_0000u32;

    // loop:
    //   SUBQ.W  #2,A7                 ; Boolean result slot
    //   MOVE.W  #-1,-(A7)             ; every event type
    //   PEA      event
    //   _GetNextEvent
    //   TST.W   (A7)+
    //   PEA      event.where
    //   _GlobalToLocal
    //   _SystemTask
    //   SUBQ.W  #4,A7                 ; TickCount result slot
    //   _TickCount
    //   MOVE.W  16(A0),D0             ; event/timeout predicate
    //   EXT.L   D0
    //   ADD.L   32(A1),D0
    //   CMP.L   (A7)+,D0
    //   SLT     D0
    //   TST.W   48(A2)
    //   SNE     D1
    //   OR.B    D1,D0
    //   BEQ.W   loop
    //
    // The event record is overwritten with host coordinates and then
    // converted to local coordinates on every pass. The write journal
    // must compare final values, not reject the temporary overwrite. The
    // post-TickCount words deliberately resemble a compiler-generated
    // event/timeout predicate. The proof is based on the complete cycle's
    // observed state, not on recognizing that instruction sequence.
    for (offset, word) in [
        (0, 0x554F),
        (2, 0x3F3C),
        (4, 0xFFFF),
        (6, 0x4879),
        (8, (event >> 16) as u16),
        (10, event as u16),
        (12, 0xA970),
        (14, 0x4A5F),
        (16, 0x4879),
        (18, ((event + 10) >> 16) as u16),
        (20, (event + 10) as u16),
        (22, 0xA871),
        (24, 0xA9B4),
        (26, 0x594F),
        (28, 0xA975),
        (30, 0x3028),
        (32, 16),
        (34, 0x48C0),
        (36, 0xD0A9),
        (38, 32),
        (40, 0xB09F),
        (42, 0x5DC0),
        (44, 0x4A6A),
        (46, 48),
        (48, 0x56C1),
        (50, 0x8001),
        (52, 0x6700),
        (54, 0xFFCA),
    ] {
        runner.bus.write_word(code + offset, word);
    }
    runner.m68k.cpu.write_reg(Register::PC, code);
    runner.m68k.cpu.write_reg(Register::A7, stack);
    runner.m68k.cpu.write_reg(Register::A0, delay_base);
    runner.m68k.cpu.write_reg(Register::A1, tick_base);
    runner.m68k.cpu.write_reg(Register::A2, flag_base);
    runner.m68k.cpu.write_reg(Register::D0, 0);
    runner.m68k.cpu.write_reg(Register::D1, 0);
    runner.bus.write_word(delay_base + 16, 5);
    runner.bus.write_long(tick_base + 32, 100);
    runner.bus.write_word(flag_base + 48, 0);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.dispatcher.set_sent_open_app_event_for_test(true);

    let (_, running) = runner.run_steps_internal(
        1_000,
        Some(100),
        0,
        true,
        false,
        FrameFinalization::Deferred,
    );
    assert!(running);
    let sleep = runner
        .idle_cycle_sleep
        .as_ref()
        .expect("the complete null-event state machine should prove an identity cycle");
    assert_eq!(sleep.trap_pc, code + 12);
    assert_eq!(sleep.wake_tick, 101);

    assert!(!runner.try_resume_proven_idle_cycle(Some(101)));
    assert_eq!(runner.guest_tick(), 101);
    assert!(runner.idle_cycle_sleep.is_none());
    assert_eq!(runner.m68k.cpu.core.pc, code + 14);
}

#[test]
fn proven_idle_cycle_stops_sleeping_at_its_known_dependency() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let sp = 0x0010_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA975;
    runner.m68k.cpu.write_reg(Register::A7, sp);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.dispatcher.set_sent_open_app_event_for_test(true);

    runner.park_proven_idle_cycle(trap_pc, 103);
    assert!(!runner.try_resume_proven_idle_cycle(Some(110)));
    assert_eq!(runner.guest_tick(), 103);
    assert!(runner.idle_cycle_sleep.is_none());
    assert!(runner.bus.fast_mem_window().is_some());
}

#[test]
fn exact_idle_cycle_rejects_changed_memory_and_non_quiescent_traps() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    let scratch = 0x0020_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.m68k.cpu.core.ppc = trap_pc;
    runner.m68k.cpu.core.ir = 0xA975;
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    runner.bus.write_byte(scratch, 1);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert_eq!(runner.guest_tick(), 100);

    runner.m68k.cpu.write_reg(Register::D0, 0x0004_0001); // LockPixels
    runner.note_idle_cycle_trap_result(0xAB1D); // non-admitted QDExtensions selector
    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.idle_cycle_last_seen.is_none());
    assert!(runner.bus.fast_mem_window().is_some());
}

#[test]
fn ordinary_tick_advance_cancels_an_exact_idle_cycle_probe() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0002_0000u32;
    runner.m68k.cpu.write_reg(Register::PC, trap_pc + 2);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(!runner.try_exact_idle_cycle_fastfwd(trap_pc, 200, Some(105)));
    assert!(runner.idle_cycle_probe.is_some());

    runner.advance_guest_tick();

    assert!(runner.idle_cycle_probe.is_none());
    assert!(runner.idle_cycle_last_seen.is_none());
    assert!(runner.bus.fast_mem_window().is_some());
}

#[test]
fn spin_fastfwd_template_f_saved_register_beq_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;

    // SUBQ.L #4,A7; _TickCount; MOVE.L (A7)+,D0
    // CMP.L D0,D7; BEQ.S back-to-SUBQ
    runner.bus.write_word(base, 0x598F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xBE80);
    runner.bus.write_word(base + 8, 0x67F6);
    runner.bus.write_word(base + 10, 0x4E71);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D7, 100);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 100);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 101);
    assert_eq!(runner.bus.read_long(sp - 4), 101);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(count, 0, "post-trap body remains for exact CPU execution");

    for _ in 0..3 {
        assert!(matches!(
            runner.m68k.cpu.step(&mut runner.bus),
            crate::cpu::StepResult::Ok
        ));
    }
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 101);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 10);
}

fn saved_register_deadline_wait(tick: u32, deadline: u32) -> FixtureRunner {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    for (offset, word) in [0x594F, 0xA975, 0x201F, 0xBA80, 0x62F6, 0x4E71]
        .into_iter()
        .enumerate()
    {
        runner.bus.write_word(base + offset as u32 * 2, word);
    }
    runner.bus.write_long(0x016A, tick);
    runner.set_guest_tick_for_test(tick);
    runner.m68k.cpu.write_reg(Register::D0, 0xDEAD_BEEF);
    runner.m68k.cpu.write_reg(Register::D5, deadline);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(0x0010_0000, tick);
    runner
}

#[test]
fn spin_fastfwd_saved_register_deadline_preserves_cpu_exit_state() {
    // SC2K's newspaper uses CMP.L D0,D5; BHI. Exercise both forms of
    // stack reservation and a deadline crossing the signed boundary.
    for preamble in [0x594F, 0x598F] {
        for (tick, deadline) in [(100, 101), (100, 107), (0x7FFF_FFFE, 0x8000_0001)] {
            let mut runner = saved_register_deadline_wait(tick, deadline);
            runner.bus.write_word(0x0001_0000, preamble);
            let mut count = 0;
            assert!(!runner.try_tickcount_spin_fastfwd(0x0001_0004, None, &mut count));
            assert_eq!(runner.guest_tick(), deadline);
            assert_eq!(runner.bus.read_long(0x0010_0000), deadline);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 0xDEAD_BEEF);
            assert_eq!(runner.m68k.cpu.read_reg(Register::D5), deadline);
            assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x0010_0000);
            assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0x0001_0004);
            assert_eq!(count, 0);
            // The real CPU executes MOVE/CMP/BHI, including stack and
            // condition flags, instead of synthesizing those side effects.
            for _ in 0..3 {
                assert!(matches!(
                    runner.m68k.cpu.step(&mut runner.bus),
                    crate::cpu::StepResult::Ok
                ));
            }
            assert_eq!(runner.m68k.cpu.read_reg(Register::D0), deadline);
            assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x0010_0004);
            assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0x0001_000A);
            assert_eq!(runner.m68k.cpu.core.get_sr() & 0x0F, 4);
        }
    }
}

#[test]
fn spin_fastfwd_saved_register_deadline_rejects_expired_or_unsafe_loops() {
    for (tick, deadline) in [(100, 100), (101, 100), (u32::MAX, 0), (100, 1_000_101)] {
        let mut runner = saved_register_deadline_wait(tick, deadline);
        let mut count = 0;
        assert!(!runner.try_tickcount_spin_fastfwd(0x0001_0004, None, &mut count));
        assert_eq!(runner.guest_tick(), tick);
        assert_eq!(runner.bus.read_long(0x0010_0000), tick);
        assert_eq!(count, 0);
    }
    for (address, replacement) in [
        (0x0001_0000, 0x4E71), // Missing stack reservation.
        (0x0001_0002, 0xA976), // Different trap.
        (0x0001_0006, 0xB080), // MOVE clobbers the comparison register.
        (0x0001_0008, 0x62F4), // Branch includes extra, unchecked work.
        (0x0001_0008, 0x6200), // Extended branch encoding.
        (0x0001_0008, 0x6EF6), // Signed comparison has different semantics.
    ] {
        let mut runner = saved_register_deadline_wait(100, 105);
        runner.bus.write_word(address, replacement);
        runner.m68k.cpu.write_reg(Register::D0, 105);
        let mut count = 0;
        assert!(!runner.try_tickcount_spin_fastfwd(0x0001_0004, None, &mut count));
        assert_eq!(runner.guest_tick(), 100);
        assert_eq!(runner.bus.read_long(0x0010_0000), 100);
        assert_eq!(count, 0);
    }
    let mut runner = saved_register_deadline_wait(100, 105);
    runner.bus.write_word(0x0001_0006, 0xB080);
    runner.bus.write_word(0x0001_0008, 0x67F6);
    runner.m68k.cpu.write_reg(Register::D0, 100);
    let mut count = 0;
    assert!(!runner.try_tickcount_spin_fastfwd(0x0001_0004, None, &mut count));
    assert_eq!(
        runner.guest_tick(),
        100,
        "CMP D0,D0; BEQ cannot become unequal"
    );
}

#[test]
fn spin_fastfwd_saved_register_deadline_honors_gui_cap_and_vbl_callbacks() {
    let mut runner = saved_register_deadline_wait(100, 105);
    runner.set_instructions_per_tick(1_000);
    runner.tick_budget = 777;
    let mut count = 0;
    assert!(runner.try_tickcount_spin_fastfwd(0x0001_0004, Some(102), &mut count));
    assert_eq!(runner.guest_tick(), 102);
    assert_eq!(runner.bus.read_long(0x0010_0000), 102);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0x0001_0004);
    assert_eq!(runner.tick_budget, 1_000);
    assert_eq!(count, 0);

    // Advancing the clock must yield to a due VBL callback before the
    // deadline; its stack and resume PC belong to ordinary callback code.
    let mut runner = saved_register_deadline_wait(100, 105);
    runner.m68k.cpu.core.set_sr_noint_nosp(0x2000);
    let task = 0x0020_2000;
    runner.bus.write_word(task + 4, 1);
    runner.bus.write_long(task + 6, 0x0004_1234);
    runner.bus.write_word(task + 10, 1);
    runner.bus.write_word(task + 12, 0);
    runner.dispatcher.vbl_tasks.push(VblTask {
        task_ptr: task,
        architecture: CallbackTaskArchitecture::M68k,
        slot: None,
        pending: false,
    });
    assert!(!runner.try_tickcount_spin_fastfwd(0x0001_0004, None, &mut count));
    assert_eq!(runner.guest_tick(), 101);
    assert_eq!(runner.bus.read_long(0x0010_0000), 100);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 0xDEAD_BEEF);
    assert_eq!(
        runner.m68k.cpu.read_reg(Register::PC),
        runner.vbl_trampoline
    );
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x000F_FFFC);
    assert_eq!(runner.bus.read_long(0x000F_FFFC), 0x0001_0004);
    let active = runner
        .active_interrupt_callback
        .expect("VBL callback pending");
    assert!(matches!(active.source, ActiveInterruptCallbackSource::Vbl));
    assert_eq!(active.resume_pc, 0x0001_0004);
    assert_eq!(active.resume_sp, 0x0010_0000);
}

#[test]
fn spin_fastfwd_template_f_rejects_stateful_branch_target() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;

    // The branch includes an ADDQ before the canonical TickCount preamble,
    // so skipping the loop would incorrectly discard stateful work.
    runner.bus.write_word(base, 0x52B8);
    runner.bus.write_word(base + 2, 0x0002);
    runner.bus.write_word(base + 4, 0x594F);
    runner.bus.write_word(base + 6, 0xA975);
    runner.bus.write_word(base + 8, 0x201F);
    runner.bus.write_word(base + 10, 0xBE80);
    runner.bus.write_word(base + 12, 0x67F2);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D7, 100);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.bus.write_long(sp - 4, 100);

    let mut count = 0usize;
    runner.try_tickcount_spin_fastfwd(base + 8, None, &mut count);

    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(runner.bus.read_long(sp - 4), 100);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0);
}

#[test]
fn spin_fastfwd_template_g_elapsed_frame_local_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let a6 = 0x0010_1000u32;
    let sp = 0x0010_0000u32;

    // SUBQ.L #4,A7; _TickCount; MOVE.L (A7)+,D0
    // MOVE.L D0,-4(A6); MOVE.L -4(A6),D0
    // SUB.L -36(A5),D0; MOVEA.W 8(A6),A0
    // CMPA.L D0,A0; BGT.S back-to-SUBQ
    runner.bus.write_word(base, 0x598F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0x2D40);
    runner.bus.write_word(base + 8, 0xFFFC);
    runner.bus.write_word(base + 10, 0x202E);
    runner.bus.write_word(base + 12, 0xFFFC);
    runner.bus.write_word(base + 14, 0x90AD);
    runner.bus.write_word(base + 16, 0xFFDC);
    runner.bus.write_word(base + 18, 0x306E);
    runner.bus.write_word(base + 20, 0x0008);
    runner.bus.write_word(base + 22, 0xB1C0);
    runner.bus.write_word(base + 24, 0x6EE6);
    runner.bus.write_word(base + 26, 0x4E71);

    runner.bus.write_long(a5 - 36, 400);
    runner.bus.write_word(a6 + 8, 5);
    runner.bus.write_long(0x016A, 401);
    runner.set_guest_tick_for_test(401);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 401);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 405);
    assert_eq!(runner.bus.read_long(sp - 4), 405);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(count, 0, "post-trap body remains for exact CPU execution");

    for _ in 0..7 {
        assert!(matches!(
            runner.m68k.cpu.step(&mut runner.bus),
            crate::cpu::StepResult::Ok
        ));
    }
    assert_eq!(runner.bus.read_long(a6 - 4), 405);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 5);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A0), 5);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 26);
}

/// Regression gate for the TickCount spin fast-forward template A
/// (classic MOVE+SUBQ+CMP+BHI with register target). Builds a
/// synthetic spin body in RAM, calls the fast-forward directly,
/// asserts the exit state matches what the guest loop's final
/// fall-through iteration would produce.
#[test]
fn spin_fastfwd_template_a_advances_ticks_and_skips_loop() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    // Synthesised spin body:
    //   $base+0: SUBQ.W #4, A7   (0x594F)
    //   $base+2: _TickCount      (0xA975) ← trap fires before call site
    //   $base+4: MOVE.L (A7)+, D0 (0x201F)
    //   $base+6: SUBQ.L #1, D0   (0x5380)
    //   $base+8: CMP.L D0, D3    (0xB680)
    //   $base+10: BHI.S *-12     (0x62F4)
    //   $base+12: sentinel       (0x4E71 NOP)
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0x5380);
    runner.bus.write_word(base + 8, 0xB680);
    runner.bus.write_word(base + 10, 0x62F4);
    runner.bus.write_word(base + 12, 0x4E71);

    // Initial tick 100, target D3=500 so target_tick = 501.
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D3, 500);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);

    let pc_after_trap = base + 4;
    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

    assert!(!hit_cap, "no tick_cap was set, cap should not trip");
    assert_eq!(runner.guest_tick(), 501, "advanced to D3+imm");
    assert_eq!(runner.bus.read_long(0x016A), 501, "bus $016A in sync");
    // After fall-through: Dn = final_tick - imm = 501 - 1 = 500 (= D3).
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 500);
    // A7 += 4 (the popped tick slot).
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x0010_0004);
    // PC past BHI (base + 12).
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 12);
    // 4 synthesised instructions accounted for.
    assert_eq!(count, 4);
}

#[test]
fn spin_fastfwd_refills_instruction_budget_at_each_elapsed_guest_tick() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    // Same template A shape as the witness above: the fast-forward
    // starts immediately after the TickCount trap.
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0x5380);
    runner.bus.write_word(base + 8, 0xB680);
    runner.bus.write_word(base + 10, 0x62F4);
    runner.bus.write_word(base + 12, 0x4E71);

    runner.set_instructions_per_tick(1_000);
    runner.tick_budget = 777;
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D3, 500);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 501);
    assert_eq!(runner.tick_budget, 1_000);
}

/// Rejection case — `MOVE.L (A7)+, D1` followed by `SUBQ.L #imm,
/// D0` (different registers) must NOT match. Ensures the
/// register-consistency check in `try_spin_template_a` guards
/// against false positives where an unrelated MOVE happens to
/// precede a SUBQ+CMP+BHI.
#[test]
fn spin_fastfwd_rejects_register_mismatch() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    // Same as template A but MOVE.L (A7)+ targets D1, while
    // SUBQ/CMP operate on D0. Template detector must reject.
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x221F); // MOVE.L (A7)+, D1 (NOT D0)
    runner.bus.write_word(base + 6, 0x5380); // SUBQ.L #1, D0
    runner.bus.write_word(base + 8, 0xB680); // CMP.L D0, D3
    runner.bus.write_word(base + 10, 0x62F4); // BHI.S

    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D3, 500);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    let pc_after_trap = base + 4;
    let mut count = 0usize;
    runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

    // No change: template rejected, guest Ticks stays at 100.
    assert_eq!(runner.guest_tick(), 100);
    // PC stays where it was (we passed pc_after_trap but the
    // fast-forward must have returned without mutating PC).
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0);
    assert_eq!(count, 0);
}

/// Regression gate for spin fast-forward template B (memory target,
/// BLS variant). Sets up the post-trap state with A6 pointing at
/// a stack frame and a target tick stored at `-4(A6)`; asserts the
/// matcher advances to the memory target and synthesises the
/// correct exit.
#[test]
fn spin_fastfwd_template_b_memory_target_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    // $base+0: SUBQ.W #4, A7   (0x594F) — pre-trap SP adjust
    // $base+2: _TickCount      (0xA975) — trap
    // $base+4: MOVE.L (A7)+, D0 (0x201F)
    // $base+6: CMP.L (-4, A6), D0 — opcode 0xB0AE, d16=0xFFFC
    //          (1011 000 010 101 110 = 0xB0AE; next word 0xFFFC = -4)
    // $base+10: BLS.S $base   (0x63F4) — back to the canonical preamble
    // $base+12: sentinel NOP  (0x4E71)
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0AE);
    runner.bus.write_word(base + 8, 0xFFFC);
    runner.bus.write_word(base + 10, 0x63F4);
    runner.bus.write_word(base + 12, 0x4E71);

    // Memory target at -4(A6). A6 points at mid-stack; -4(A6)
    // holds the target tick.
    let a6 = 0x0010_1000u32;
    runner.bus.write_long(a6.wrapping_sub(4), 400);

    // Initial state
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);

    let pc_after_trap = base + 4;
    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

    assert!(!hit_cap);
    // target_tick = mem_target + 1 = 400 + 1 = 401.
    assert_eq!(runner.guest_tick(), 401);
    assert_eq!(runner.bus.read_long(0x016A), 401);
    // Template B exit: D0 = final_tick (no SUBQ).
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 401);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x0010_0004);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 12);
    // Template B synthesises 3 instructions (MOVE, CMP, BLS).
    assert_eq!(count, 3);
}

/// A memory-target loop with stateful work before `_TickCount` must not be
/// fast-forwarded because synthesising the exit would skip that work.
#[test]
fn spin_fastfwd_template_b_rejects_stateful_pretrap_body() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let counter = 0x0001_8000u32;
    let a6 = 0x0001_9000u32;
    let sp = 0x0010_0000u32;

    // ADDQ.L #1,(A0,D3.L*4); SUBQ.W #4,A7; _TickCount;
    // MOVE.L (A7)+,D0; CMP.L (-4,A6),D0; BLS.S back-to-ADDQ.
    runner.bus.write_word(base, 0x52B0);
    runner.bus.write_word(base + 2, 0x3C00);
    runner.bus.write_word(base + 4, 0x594F);
    runner.bus.write_word(base + 6, 0xA975);
    runner.bus.write_word(base + 8, 0x201F);
    runner.bus.write_word(base + 10, 0xB0AE);
    runner.bus.write_word(base + 12, 0xFFFC);
    runner.bus.write_word(base + 14, 0x63F0);
    runner.bus.write_word(base + 16, 0x4E71);

    runner.bus.write_long(counter, 7);
    runner.bus.write_long(a6 - 4, 400);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A0, counter);
    runner.m68k.cpu.write_reg(Register::D3, 0);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 8, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(runner.bus.read_long(counter), 7);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(count, 0);
}

#[test]
fn spin_fastfwd_template_b_signed_ble_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let sp = 0x0010_0000u32;

    // Signed memory-target loop shape emitted by some classic compilers:
    //   SUBQ.W #4,A7; _TickCount; MOVE.L (A7)+,D0
    //   CMP.L (-16,A5),D0; BLE.S back-to-SUBQ
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0AD);
    runner.bus.write_word(base + 8, 0xFFF0);
    runner.bus.write_word(base + 10, 0x6FF4);
    runner.bus.write_word(base + 12, 0x4E71);

    runner.bus.write_long(a5 - 16, 400);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 401);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 401);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 12);
    assert_eq!(count, 3);
}

#[test]
fn spin_fastfwd_template_b_signed_blt_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let sp = 0x0010_0000u32;

    // Exclusive signed memory-target loop:
    //   SUBQ.W #4,A7; _TickCount; MOVE.L (A7)+,D0
    //   CMP.L (-16,A5),D0; BLT.S back-to-SUBQ
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0AD);
    runner.bus.write_word(base + 8, 0xFFF0);
    runner.bus.write_word(base + 10, 0x6DF4);
    runner.bus.write_word(base + 12, 0x4E71);

    runner.bus.write_long(a5 - 16, 400);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 400);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 400);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 12);
    assert_eq!(count, 3);
}

#[test]
fn spin_fastfwd_template_b_signed_ble_rejects_overflow_target() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let sp = 0x0010_0000u32;
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0AD);
    runner.bus.write_word(base + 8, 0xFFF0);
    runner.bus.write_word(base + 10, 0x6FF4);
    runner.bus.write_long(a5 - 16, i32::MAX as u32);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let mut count = 0usize;
    runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), 0);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(count, 0);
}

/// Regression gate for the TickCount spin fast-forward absolute
/// LongInt target variant:
///
///   SUBQ.W #4,A7
///   _TickCount
///   MOVE.L (A7)+,Dn
///   CMP.L  (xxx).L,Dn
///   BCS.S  back-to-SUBQ
///
/// This is the same wait-until-Ticks-reaches-memory-target shape as
/// template B, but older MPW/Think-era code may address the target
/// through an absolute long global instead of an A-register frame.
#[test]
fn spin_fastfwd_template_c_absolute_long_target_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let target_addr = 0x0002_FE44u32;

    // $base+0:  SUBQ.W #4, A7      (0x594F)
    // $base+2:  _TickCount         (0xA975)
    // $base+4:  MOVE.L (A7)+, D0   (0x201F)
    // $base+6:  CMP.L (xxx).L, D0  (0xB0B9 + absolute long)
    // $base+12: BCS.S $base        (0x65F2; base+14-14)
    // $base+14: sentinel NOP
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0B9);
    runner.bus.write_long(base + 8, target_addr);
    runner.bus.write_word(base + 12, 0x65F2);
    runner.bus.write_word(base + 14, 0x4E71);

    runner.bus.write_long(target_addr, 400);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);

    let pc_after_trap = base + 4;
    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 400);
    assert_eq!(runner.bus.read_long(0x016A), 400);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 400);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), 0x0010_0004);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 14);
    assert_eq!(count, 3);
}

#[test]
fn spin_fastfwd_template_e_computed_signed_deadline_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let a6 = 0x0010_1000u32;
    let sp = 0x0010_0000u32;

    // Signed computed-deadline loop:
    //   SUBQ.W #4,A7; _TickCount
    //   MOVE.W (-2,A6),D0; EXT.L D0; ADD.L (-16,A5),D0
    //   CMP.L (A7)+,D0; BGT.S back-to-SUBQ
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x302E);
    runner.bus.write_word(base + 6, 0xFFFE);
    runner.bus.write_word(base + 8, 0x48C0);
    runner.bus.write_word(base + 10, 0xD0AD);
    runner.bus.write_word(base + 12, 0xFFF0);
    runner.bus.write_word(base + 14, 0xB09F);
    runner.bus.write_word(base + 16, 0x6EEE);
    runner.bus.write_word(base + 18, 0x4E71);

    runner.bus.write_word(a6 - 2, 5);
    runner.bus.write_long(a5 - 16, 400);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp - 4, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 405);
    assert_eq!(runner.bus.read_long(sp - 4), 405);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0, "post-trap body remains for exact CPU execution");

    for _ in 0..5 {
        assert!(matches!(
            runner.m68k.cpu.step(&mut runner.bus),
            crate::cpu::StepResult::Ok
        ));
    }
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 405);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 18);
}

#[test]
fn spin_fastfwd_template_e_computed_signed_deadline_inclusive_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let a6 = 0x0010_1000u32;
    let sp = 0x0010_0000u32;

    // Inclusive signed computed-deadline loop:
    //   SUBQ.W #4,A7; _TickCount
    //   MOVE.W (-2,A6),D0; EXT.L D0; ADD.L (-16,A5),D0
    //   CMP.L (A7)+,D0; BGE.S back-to-SUBQ
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x302E);
    runner.bus.write_word(base + 6, 0xFFFE);
    runner.bus.write_word(base + 8, 0x48C0);
    runner.bus.write_word(base + 10, 0xD0AD);
    runner.bus.write_word(base + 12, 0xFFF0);
    runner.bus.write_word(base + 14, 0xB09F);
    runner.bus.write_word(base + 16, 0x6CEE);
    runner.bus.write_word(base + 18, 0x4E71);

    runner.bus.write_word(a6 - 2, 5);
    runner.bus.write_long(a5 - 16, 400);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp - 4, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 406);
    assert_eq!(runner.bus.read_long(sp - 4), 406);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0, "post-trap body remains for exact CPU execution");

    for _ in 0..5 {
        assert!(matches!(
            runner.m68k.cpu.step(&mut runner.bus),
            crate::cpu::StepResult::Ok
        ));
    }
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 405);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 18);
}

#[test]
fn spin_fastfwd_template_e_rejects_inclusive_signed_overflow() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let a5 = 0x0001_8000u32;
    let a6 = 0x0010_1000u32;
    let sp = 0x0010_0000u32;

    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x302E);
    runner.bus.write_word(base + 6, 0xFFFE);
    runner.bus.write_word(base + 8, 0x48C0);
    runner.bus.write_word(base + 10, 0xD0AD);
    runner.bus.write_word(base + 12, 0xFFF0);
    runner.bus.write_word(base + 14, 0xB09F);
    runner.bus.write_word(base + 16, 0x6CEE);

    runner.bus.write_word(a6 - 2, 0);
    runner.bus.write_long(a5 - 16, i32::MAX as u32);
    runner.bus.write_long(0x016A, 100);
    runner.bus.write_long(sp - 4, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::A5, a5);
    runner.m68k.cpu.write_reg(Register::A6, a6);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(runner.bus.read_long(sp - 4), 100);
    assert_eq!(count, 0);
}

#[test]
fn spin_fastfwd_template_e_rejects_mismatched_extension_register() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x302E); // MOVE.W (-2,A6),D0
    runner.bus.write_word(base + 6, 0xFFFE);
    runner.bus.write_word(base + 8, 0x48C1); // EXT.L D1, not D0
    runner.bus.write_word(base + 10, 0xD0AD);
    runner.bus.write_word(base + 12, 0xFFF0);
    runner.bus.write_word(base + 14, 0xB09F);
    runner.bus.write_word(base + 16, 0x6EEE);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);

    let mut count = 0usize;
    runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(count, 0);
}

#[test]
fn spin_fastfwd_template_d_bcc_stack_compare_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;

    // Stack-result BCC variant:
    //   CLR.L -(A7); _TickCount; CMP.L (A7)+,D7; BCC.S *-8
    runner.bus.write_word(base, 0x42A7);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0xBE9F);
    runner.bus.write_word(base + 6, 0x64F8);
    runner.bus.write_word(base + 8, 0x4E71);

    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D7, 500);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 100);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 501);
    assert_eq!(runner.bus.read_long(sp - 4), 501);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0, "CMP/BCC remain for exact CPU execution");

    assert!(matches!(
        runner.m68k.cpu.step(&mut runner.bus),
        crate::cpu::StepResult::Ok
    ));
    assert!(matches!(
        runner.m68k.cpu.step(&mut runner.bus),
        crate::cpu::StepResult::Ok
    ));
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 8);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
}

#[test]
fn spin_fastfwd_template_d_lemmings_beq_variant() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;

    // Exact loop emitted by Lemmings 1.5.2:
    //   CLR.L -(A7); _TickCount; CMP.L (A7)+,D7; BEQ.S *-8
    runner.bus.write_word(base, 0x42A7);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0xBE9F);
    runner.bus.write_word(base + 6, 0x67F8);
    runner.bus.write_word(base + 8, 0x4E71);

    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D7, 100);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 100);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 101);
    assert_eq!(runner.bus.read_long(sp - 4), 101);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0, "CMP/BEQ remain for exact CPU execution");

    assert!(matches!(
        runner.m68k.cpu.step(&mut runner.bus),
        crate::cpu::StepResult::Ok
    ));
    assert!(matches!(
        runner.m68k.cpu.step(&mut runner.bus),
        crate::cpu::StepResult::Ok
    ));
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 8);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
}

#[test]
fn spin_fastfwd_template_d_beq_does_not_advance_after_tick_changed() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;
    runner.bus.write_word(base, 0x42A7);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0xBE9F);
    runner.bus.write_word(base + 6, 0x67F8);

    runner.bus.write_long(0x016A, 101);
    runner.set_guest_tick_for_test(101);
    runner.m68k.cpu.write_reg(Register::D7, 100);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 101);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 101);
    assert_eq!(runner.bus.read_long(sp - 4), 101);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(count, 0);
}

#[test]
fn spin_fastfwd_template_d_honors_gui_tick_cap() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;
    runner.bus.write_word(base, 0x42A7);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0xBE9F);
    runner.bus.write_word(base + 6, 0x64F8);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.set_instructions_per_tick(1_000);
    runner.tick_budget = 777;
    runner.m68k.cpu.write_reg(Register::D7, 500);
    runner.m68k.cpu.write_reg(Register::A7, sp - 4);
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.bus.write_long(sp - 4, 100);

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, Some(102), &mut count);

    assert!(hit_cap);
    assert_eq!(runner.guest_tick(), 102);
    assert_eq!(runner.bus.read_long(sp - 4), 102);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 4);
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(
        runner.tick_budget,
        runner.instructions_per_tick() as i32,
        "a capped synthetic boundary must leave a fresh tick budget"
    );
}

#[test]
fn spin_fastfwd_leaves_interrupt_callback_state_unsynthesized() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let target_addr = 0x0002_FE44u32;
    let task_ptr = 0x0020_2000u32;
    let sp = 0x0010_0000u32;

    // Same absolute-long TickCount spin as template C. The VBL task
    // becomes due during the accelerated tick advance, before the
    // loop reaches its target tick.
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0xB0B9);
    runner.bus.write_long(base + 8, target_addr);
    runner.bus.write_word(base + 12, 0x65F2);
    runner.bus.write_word(base + 14, 0x4E71);

    runner.bus.write_long(target_addr, 400);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.set_instructions_per_tick(1_000);
    runner.tick_budget = 777;
    runner.m68k.cpu.write_reg(Register::PC, base + 4);
    runner.m68k.cpu.write_reg(Register::A7, sp);
    runner.m68k.cpu.write_reg(Register::D0, 0xDEAD_BEEF);
    runner.m68k.cpu.core.set_sr_noint_nosp(0x2000);
    runner.bus.write_long(sp, 100);

    runner.bus.write_word(task_ptr + 4, 1);
    runner.bus.write_long(task_ptr + 6, 0x0004_1234);
    runner.bus.write_word(task_ptr + 10, 1);
    runner.bus.write_word(task_ptr + 12, 0);
    runner.dispatcher.vbl_tasks.push(VblTask {
        task_ptr,
        architecture: CallbackTaskArchitecture::M68k,
        slot: None,
        pending: false,
    });

    let mut count = 0usize;
    let hit_cap = runner.try_tickcount_spin_fastfwd(base + 4, None, &mut count);

    assert!(!hit_cap);
    assert_eq!(runner.guest_tick(), 101);
    assert_eq!(runner.bus.read_long(0x016A), 101);
    assert_eq!(count, 0);
    assert_eq!(runner.m68k.cpu.read_reg(Register::D0), 0xDEAD_BEEF);
    assert_eq!(
        runner.m68k.cpu.read_reg(Register::PC),
        runner.vbl_trampoline
    );
    assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp - 4);
    assert_eq!(runner.bus.read_long(sp - 4), base + 4);

    assert_eq!(
        runner.tick_budget,
        runner.instructions_per_tick() as i32,
        "an interrupted synthetic boundary must leave a fresh tick budget"
    );

    let active = runner
        .active_interrupt_callback
        .expect("VBL callback should remain active for normal resume handling");
    assert!(matches!(active.source, ActiveInterruptCallbackSource::Vbl));
    assert_eq!(active.resume_pc, base + 4);
    assert_eq!(active.resume_sp, sp);
}

/// Regression gates for the spin-fastfwd override. Tests the
/// pure decision function so `OnceLock`-cached env vars don't
/// interfere across tests.
#[test]
fn spin_fastfwd_gate_defaults_on_with_gui_cadence_guarded_by_tick_cap() {
    // Neither force_on nor force_off → default behaviour:
    //   headless (yield_for_ui = false) → enabled
    //   capped GUI → enabled; tick_cap preserves visible cadence
    //   uncapped GUI → disabled; it could otherwise batch visible ticks
    assert!(spin_wait_fastfwd_gate(false, false, false, false));
    assert!(spin_wait_fastfwd_gate(false, false, false, true));
    assert!(spin_wait_fastfwd_gate(false, false, true, true));
    assert!(!spin_wait_fastfwd_gate(false, false, true, false));
}

#[test]
fn spin_fastfwd_gate_force_off_wins() {
    // force_off must dominate force_on and override the default in
    // either mode.
    assert!(!spin_wait_fastfwd_gate(false, true, false, false));
    assert!(!spin_wait_fastfwd_gate(false, true, true, true));
    assert!(!spin_wait_fastfwd_gate(true, true, false, true));
    assert!(!spin_wait_fastfwd_gate(true, true, true, false));
}

#[test]
fn spin_fastfwd_gate_force_on_remains_enabled() {
    // The legacy force-on override remains accepted, including for an
    // uncapped GUI caller that defaults to disabled.
    assert!(spin_wait_fastfwd_gate(true, false, false, false));
    assert!(spin_wait_fastfwd_gate(true, false, true, false));
}

#[test]
fn menu_flash_uses_frontend_time_while_application_ticks_are_frozen() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let mut tracking = crate::menu_manager::test_process_menu_tracking(128);
    tracking.set_flash_tick(100);
    tracking.begin_flash(3, 0x0080_0002);
    runner.process_context.set_menu_tracking(Some(tracking));
    runner.frozen_ticks = Some(100);
    runner.advance_menu_presentation_clock(std::time::Duration::from_millis(300));
    runner.run_steps_internal(0, Some(102), 0, true, false, FrameFinalization::Deferred);
    assert_eq!(runner.frozen_ticks, Some(100));
    assert_eq!(
        runner
            .process_context
            .with_menu_tracking_mut(|tracking| tracking.advance_flash())
            .unwrap(),
        crate::menu_manager::MenuFlashStep::Complete(0x0080_0002)
    );
}

#[test]
fn tracking_refire_freeze_policy_keeps_dialog_ticks_live() {
    // Menu/control tracking may freeze app-visible ticks while the GUI
    // renders intermediate tracking frames.
    assert!(tracking_refire_should_freeze_ticks(0xA93D));
    assert!(tracking_refire_should_freeze_ticks(0xAD3D));
    assert!(tracking_refire_should_freeze_ticks(0xA80B));
    assert!(tracking_refire_should_freeze_ticks(0xAC0B));
    assert!(tracking_refire_should_freeze_ticks(0xA968));
    assert!(tracking_refire_should_freeze_ticks(0xAD68));
    assert!(tracking_refire_should_freeze_ticks(0xA91E));
    assert!(tracking_refire_should_freeze_ticks(0xAD1E));
    assert!(tracking_refire_should_freeze_ticks(0xA925));
    assert!(tracking_refire_should_freeze_ticks(0xAD25));
    assert!(tracking_refire_should_freeze_ticks(0xA905));
    assert!(tracking_refire_should_freeze_ticks(0xAD05));
    assert!(tracking_refire_should_freeze_ticks(0xA926));
    assert!(tracking_refire_should_freeze_ticks(0xAD26));

    // ModalDialog must keep ticks/VBL/sound callbacks live. EV's pilot
    // dialog flow plays music through this path.
    assert!(!tracking_refire_should_freeze_ticks(0xA991));
    assert!(!tracking_refire_should_freeze_ticks(0xAD91));

    assert!(tracking_refire_uses_dialog_callbacks(0xA991));
    assert!(!tracking_refire_uses_dialog_callbacks(0xA9EA));
    assert!(tracking_refire_advances_gui_idle_tick(0xA991));
    for alert in [0xA985, 0xA986, 0xA987, 0xA988] {
        assert!(!tracking_refire_should_freeze_ticks(alert));
        assert!(tracking_refire_uses_dialog_callbacks(alert));
        assert!(tracking_refire_advances_gui_idle_tick(alert));
        assert!(tracking_refire_advances_gui_idle_tick(alert | 0x0400));
    }
    assert!(tracking_refire_advances_gui_idle_tick(0xA9EA));
}

#[test]
fn trackcontrol_refire_allows_guest_scrollbar_callback_to_execute() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let trap_pc = 0x0001_0000u32;
    let sp = 0x0010_0000u32;
    let marker = runner.bus.alloc(2);
    let action_proc = runner.bus.alloc(12);
    let ctrl_ptr = runner.bus.alloc(40);
    let ctrl_handle = runner.bus.alloc(4);

    runner.bus.write_word(trap_pc, 0xA968); // _TrackControl
    runner.bus.write_word(action_proc, 0x33FC); // MOVE.W #$7A5A,marker
    runner.bus.write_word(action_proc + 2, 0x7A5A);
    runner.bus.write_long(action_proc + 4, marker);
    runner.bus.write_word(action_proc + 8, 0x4E74); // RTD #6
    runner.bus.write_word(action_proc + 10, 6);
    runner.bus.write_long(ctrl_handle, ctrl_ptr);
    runner.bus.write_word(ctrl_ptr + 8, 60);
    runner.bus.write_word(ctrl_ptr + 10, 240);
    runner.bus.write_word(ctrl_ptr + 12, 220);
    runner.bus.write_word(ctrl_ptr + 14, 256);
    runner.bus.write_byte(ctrl_ptr + 16, 0xFF);
    runner.bus.write_word(ctrl_ptr + 18, 40);
    runner.bus.write_word(ctrl_ptr + 20, 0);
    runner.bus.write_word(ctrl_ptr + 22, 100);
    runner.dispatcher.control_manager.set_proc_id(ctrl_ptr, 16);
    runner
        .dispatcher
        .input_state
        .set_mouse_button_for_test(true);
    runner
        .dispatcher
        .input_state
        .set_mouse_position_for_test((210, 248));

    runner.bus.write_long(sp, action_proc);
    runner.bus.write_word(sp + 4, 210);
    runner.bus.write_word(sp + 6, 248);
    runner.bus.write_long(sp + 8, ctrl_handle);
    runner.bus.write_word(sp + 12, 0xBEEF);
    runner.m68k.cpu.write_reg(Register::PC, trap_pc);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let (_steps, running) = runner.run_steps(20, None);

    assert!(running);
    assert_eq!(runner.bus.read_word(marker), 0x7A5A);
    assert!(runner.dispatcher.is_control_tracking());
    assert!(!runner.dispatcher.is_control_action_callback_pending());
}

#[test]
fn standard_file_refires_yield_before_unrelated_modeless_callbacks() {
    for (selector, pop_total) in [(0x0002u16, 28u32), (0x0006, 16)] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let reply_ptr = runner.bus.alloc(80);
        let proc_addr = 0x0001_1000u32;

        runner.bus.write_word(base, 0xA9EA); // _Pack3
        runner.m68k.cpu.write_reg(Register::PC, base);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        runner.bus.write_word(sp, selector);
        runner.bus.write_long(sp + 2, reply_ptr);
        if selector == 0x0002 {
            runner.bus.write_long(sp + 10, 0); // typeList
            runner.bus.write_word(sp + 14, 0); // numTypes
        } else {
            runner.bus.write_long(sp + 6, 0); // typeList
            runner.bus.write_word(sp + 10, 0); // numTypes
        }
        runner.bus.write_word(proc_addr, 0x4E56); // plausible modeless draw proc
        runner
            .dispatcher
            .modeless_dialog_draw_proc_queue
            .push_back((0, proc_addr, 1));

        let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

        assert!(running);
        assert_eq!(steps, 1);
        assert!(runner.dispatcher.is_standard_file_get_tracking());
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base);
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
        assert!(runner.active_interrupt_callback.is_none());
        assert_eq!(
            runner.dispatcher.modeless_dialog_draw_proc_queue.len(),
            1,
            "selector ${selector:04X} must not consume another manager's callback"
        );

        let (idle_steps, idle_running) = runner.run_gui_slice_with_audio(16, 3, 0);
        assert!(idle_running);
        assert_eq!(idle_steps, 3);
        assert_eq!(runner.guest_tick(), 3);
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base);

        runner.dispatcher.modeless_dialog_draw_proc_queue.clear();
        runner
            .process_context
            .shared_event_queue()
            .push_back(QueuedEvent {
                what: 3,
                message: 0x0000_351B, // Escape
                when: 0,
                where_v: 0,
                where_h: 0,
                modifiers: 0,
            });
        let (cancel_steps, cancel_running) = runner.run_gui_slice_with_audio(1, 3, 0);

        assert!(cancel_running);
        assert_eq!(cancel_steps, 1);
        assert!(!runner.dispatcher.is_standard_file_get_tracking());
        assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base + 2);
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp + pop_total);
        assert_eq!(runner.bus.read_byte(reply_ptr), 0);
    }
}

#[test]
fn modal_dialog_refire_still_schedules_its_draw_callback() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;
    let proc_addr = 0x0001_1000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.bus.write_word(proc_addr, 0x4E56); // plausible userItem draw proc
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, sp);
    let mut tracking = dialog_tracking_for_test(0, 0);
    tracking.draw_proc_queue.push_back((proc_addr, 1));
    tracking.draw_procs_done = false;
    tracking.rendered_pixels_final = false;
    runner.dispatcher.dialog_tracking = Some(tracking);

    let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert!(matches!(
        runner.active_interrupt_callback,
        Some(ActiveInterruptCallback {
            source: ActiveInterruptCallbackSource::DialogDrawProc,
            ..
        })
    ));
    assert_ne!(runner.m68k.cpu.read_reg(Register::PC), base);
}

#[test]
fn modal_dialog_refire_preserves_application_cdef_callback_redirection() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;
    let side_effect = 0x0001_2000u32;
    let dialog_ptr = runner.bus.alloc(200);
    let control_handle = runner.bus.alloc(4);
    let control_ptr = runner.bus.alloc(36);
    let cdef_handle = runner.bus.alloc(4);
    let cdef_proc = runner.bus.alloc(20);

    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.bus.write_word(cdef_proc, 0x4E56); // LINK A6,#0
    runner.bus.write_word(cdef_proc + 2, 0);
    runner.bus.write_word(cdef_proc + 4, 0x33FC); // MOVE.W #$CAFE,(abs).L
    runner.bus.write_word(cdef_proc + 6, 0xCAFE);
    runner.bus.write_long(cdef_proc + 8, side_effect);
    runner.bus.write_word(cdef_proc + 12, 0x4E5E); // UNLK A6
    runner.bus.write_word(cdef_proc + 14, 0x4E74); // RTD #12
    runner.bus.write_word(cdef_proc + 16, 12);
    runner.bus.write_long(cdef_handle, cdef_proc);

    runner.dispatcher.init_cgraf_window(
        &mut runner.bus,
        &mut runner.m68k.cpu,
        dialog_ptr,
        0,
        100,
        120,
        220,
        360,
        "",
        2,
        true,
        false,
        false,
        0,
    );
    runner.dispatcher.front_window = dialog_ptr;
    runner.dispatcher.window_bounds = (100, 120, 220, 360);
    runner
        .dispatcher
        .dialog_items
        .insert(dialog_ptr, Vec::new());

    runner.bus.write_long(control_handle, control_ptr);
    runner.bus.write_long(control_ptr, 0);
    runner.bus.write_long(control_ptr + 4, dialog_ptr);
    runner.bus.write_word(control_ptr + 8, 10);
    runner.bus.write_word(control_ptr + 10, 10);
    runner.bus.write_word(control_ptr + 12, 50);
    runner.bus.write_word(control_ptr + 14, 80);
    runner.bus.write_byte(control_ptr + 16, 255);
    runner.bus.write_byte(control_ptr + 17, 0);
    runner.bus.write_long(control_ptr + 24, cdef_handle);
    runner.bus.write_long(dialog_ptr + 140, control_handle);
    runner
        .dispatcher
        .control_manager
        .register(control_handle, control_ptr, 160 << 4, 0);

    let item_hit = runner.bus.alloc(2);
    runner.bus.write_long(sp, item_hit);
    runner.bus.write_long(sp + 4, 0);
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, sp);

    let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(
        runner.m68k.cpu.read_reg(Register::PC),
        runner.dispatcher.control_def_trampoline,
        "ModalDialog must not replace the CDEF callback entry with its refire PC"
    );

    let (_steps, running) = runner.run_steps(64, None);
    assert!(running);
    assert_eq!(
        runner.bus.read_word(side_effect),
        0xCAFE,
        "the application CDEF must execute before ModalDialog refires"
    );
}

#[test]
fn tracking_refire_survives_async_callback_injection() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let sp = 0x0010_0000u32;

    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, sp);
    let mut tracking = dialog_tracking_for_test(0, 0);
    tracking.flash_remaining = 6;
    tracking.flash_delay = 3;
    runner.dispatcher.dialog_tracking = Some(tracking);

    // Model a timer/VBL callback that was injected after the tracking
    // trap's A-line instruction advanced PC to base + 2. The callback
    // must return to that post-trap PC before the runner re-fires A991.
    runner.active_interrupt_callback = Some(ActiveInterruptCallback {
        source: ActiveInterruptCallbackSource::Timer,
        resume_pc: base + 2,
        resume_sp: sp,
        d_regs: [0; 8],
        a_regs: [0, 0, 0, 0, 0, 0, 0, sp],
        sr: 0x2000,
        ccr: 0,
        restore_port: None,
    });

    let (steps, running) = runner.run_steps(2, None);

    assert!(running);
    assert_eq!(steps, 2);
    assert!(
        runner.active_interrupt_callback.is_none(),
        "active={:?} deferred={:?} pc=${:08X} sp=${:08X}",
        runner.active_interrupt_callback.map(|active| (
            active.source,
            active.resume_pc,
            active.resume_sp
        )),
        runner.deferred_tracking_refire_pc,
        runner.m68k.cpu.read_reg(Register::PC),
        runner.m68k.cpu.read_reg(Register::A7),
    );
    assert!(runner.deferred_tracking_refire_pc.is_none());
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base);
}

#[test]
fn gui_modaldialog_idle_refire_advances_one_tick() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 0);
    runner.set_guest_tick_for_test(0);
    runner.set_instructions_per_tick(1_000_000);
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

    let (steps, running) = runner.run_gui_slice_with_audio(1, 1, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.guest_tick(), 1);
    assert_eq!(runner.tick_budget, runner.instructions_per_tick() as i32);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base);
}

#[test]
fn time_driven_modal_wait_avoids_instruction_budget_refire_storm() {
    fn modal_runner() -> FixtureRunner {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        runner.bus.write_word(0x10000, 0xA991);
        runner.m68k.cpu.write_reg(Register::PC, 0x10000);
        runner.m68k.cpu.write_reg(Register::A7, 0x100000);
        runner.set_guest_tick_for_test(0);
        runner.bus.write_long(0x016A, 0);
        runner.set_instructions_per_tick(10_000);
        runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));
        runner
    }
    let mut diagnostic = modal_runner();
    let mut timed = modal_runner();
    let (diagnostic_steps, diagnostic_running) = diagnostic.run_steps(20_000, Some(2));
    let (timed_steps, timed_running) = timed.run_gui_cpu_slice(20_000, 2);
    assert!(diagnostic_running && timed_running);
    assert_eq!(diagnostic.guest_tick(), 2);
    assert_eq!(timed.guest_tick(), 2);
    assert!(
        diagnostic_steps > 1_000,
        "legacy mode consumes synthetic refires"
    );
    assert_eq!(timed_steps, 2, "one idle refire per simulated tick");
    for register in [Register::PC, Register::A7] {
        assert_eq!(
            diagnostic.m68k.cpu.read_reg(register),
            timed.m68k.cpu.read_reg(register)
        );
    }
}

#[test]
fn gui_modaldialog_idle_refire_runs_until_tick_cap() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 0);
    runner.set_guest_tick_for_test(0);
    runner.set_instructions_per_tick(1_000_000);
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

    let (steps, running) = runner.run_gui_slice_with_audio(16, 2, 0);

    assert!(running);
    assert_eq!(steps, 2);
    assert_eq!(runner.guest_tick(), 2);
    assert_eq!(runner.m68k.cpu.read_reg(Register::PC), base);
}

#[test]
fn gui_modaldialog_refire_unfreezes_prior_control_tracking() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 182);
    runner.set_guest_tick_for_test(182);
    runner.frozen_ticks = Some(182);
    runner.set_instructions_per_tick(1_000_000);
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(0, 0));

    let (steps, running) = runner.run_gui_slice_with_audio(16, 184, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.frozen_ticks, None);
    assert_eq!(runner.guest_tick(), 184);
    assert_eq!(runner.guest_tick(), 184);
}

#[test]
fn gui_modaldialog_null_filter_fires_at_tick_cap() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let filter_proc = 0x0001_1000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 0);
    runner.set_guest_tick_for_test(0);
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));

    let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.guest_tick(), 0);
    assert_ne!(runner.m68k.cpu.read_reg(Register::PC), base);
    assert!(!runner.has_pending_sound_work());
    assert!(
        !runner
            .dispatcher
            .dialog_tracking
            .as_ref()
            .unwrap()
            .rendered_pixels_final
    );
}

#[test]
fn gui_modaldialog_update_filter_fires_at_tick_cap() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let filter_proc = 0x0001_1000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 0);
    runner.set_guest_tick_for_test(0);
    runner
        .process_context
        .shared_event_queue()
        .push_back(QueuedEvent {
            what: 6,
            message: 0,
            when: 0,
            where_v: 0,
            where_h: 0,
            modifiers: 0,
        });
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));

    let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_eq!(runner.guest_tick(), 0);
    assert_ne!(runner.m68k.cpu.read_reg(Register::PC), base);
    assert!(
        !runner
            .dispatcher
            .dialog_tracking
            .as_ref()
            .unwrap()
            .rendered_pixels_final
    );
}

#[test]
fn gui_modaldialog_mouse_down_goes_to_filter_before_default_handling() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    let filter_proc = 0x0001_1000u32;
    runner.bus.write_word(base, 0xA991); // _ModalDialog
    runner.bus.write_word(filter_proc, 0x4E56); // LINK A6, valid filter entry
    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 0);
    runner.set_guest_tick_for_test(0);
    runner
        .process_context
        .shared_event_queue()
        .push_back(QueuedEvent {
            what: 1,
            message: 0,
            when: 0,
            where_v: 12,
            where_h: 24,
            modifiers: 0,
        });
    let mut tracking = dialog_tracking_for_test(filter_proc, 0x0010_0100);
    tracking.items.push(DialogItem {
        item_type: 4,
        rect: (8, 16, 20, 30),
        text: String::from("OK"),
        resource_id: 0,
        proc_ptr: 0,
        sel_start: 0,
        sel_end: 0,
    });
    runner.dispatcher.dialog_tracking = Some(tracking);

    let (steps, running) = runner.run_gui_slice_with_audio(1, 0, 0);

    assert!(running);
    assert_eq!(steps, 1);
    assert_ne!(runner.m68k.cpu.read_reg(Register::PC), base);
    let event_ptr = runner.dialog_filter_event;
    assert_eq!(runner.bus.read_word(event_ptr), 1);
    assert_eq!(runner.bus.read_word(event_ptr + 10), 12);
    assert_eq!(runner.bus.read_word(event_ptr + 12), 24);
    assert!(
        runner.process_context.event_queue().is_empty(),
        "the filter callback should consume a queued button mouseDown event"
    );
}

#[test]
fn modaldialog_filter_null_event_is_paced_per_guest_tick() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let filter_proc = 0x0001_1000u32;
    let dialog_ptr = 0x0020_0000u32;
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));
    runner.set_guest_tick_for_test(42);
    runner.bus.write_long(0x016A, 42);

    assert!(runner.should_fire_dialog_filter_proc());

    runner.dialog_filter_last_null_event_tick = Some((dialog_ptr, 42));
    assert!(
        !runner.should_fire_dialog_filter_proc(),
        "a synthetic null event should not refire twice in the same guest tick"
    );

    runner.set_guest_tick_for_test(43);
    runner.bus.write_long(0x016A, 43);
    assert!(
        runner.should_fire_dialog_filter_proc(),
        "the next guest tick should allow another ModalDialog null-event filter call"
    );
}

#[test]
fn modaldialog_filter_real_events_bypass_null_event_pacing() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let filter_proc = 0x0001_1000u32;
    let dialog_ptr = 0x0020_0000u32;
    runner.dispatcher.dialog_tracking = Some(dialog_tracking_for_test(filter_proc, 0x0010_0100));
    runner.set_guest_tick_for_test(42);
    runner.bus.write_long(0x016A, 42);
    runner.dialog_filter_last_null_event_tick = Some((dialog_ptr, 42));
    runner
        .process_context
        .shared_event_queue()
        .push_back(QueuedEvent {
            what: 1,
            message: 0,
            when: 0,
            where_v: 12,
            where_h: 34,
            modifiers: 0,
        });

    assert!(
        runner.should_fire_dialog_filter_proc(),
        "mouse/key/update events must still enter the filter immediately"
    );

    runner.process_context.shared_event_queue().clear();
    let window_ptr = runner.bus.alloc(170);
    runner.dispatcher.init_cgraf_window(
        &mut runner.bus,
        &mut runner.m68k.cpu,
        window_ptr,
        0,
        100,
        120,
        220,
        360,
        "",
        2,
        true,
        false,
        false,
        0,
    );
    runner
        .dispatcher
        .dialog_tracking
        .as_mut()
        .unwrap()
        .dialog_ptr = window_ptr;
    runner.dialog_filter_last_null_event_tick = Some((window_ptr, 42));

    assert!(
        runner.should_fire_dialog_filter_proc(),
        "a pending updateEvt for the active dialog must bypass null-event pacing"
    );
}

#[test]
fn spin_fastfwd_rejects_wrong_branch_target() {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    let base = 0x0001_0000u32;
    runner.bus.write_word(base, 0x594F);
    runner.bus.write_word(base + 2, 0xA975);
    runner.bus.write_word(base + 4, 0x201F);
    runner.bus.write_word(base + 6, 0x5380);
    runner.bus.write_word(base + 8, 0xB680);
    // BHI.S with disp8 = 0xF6 (= -10, not -12). Target would
    // land at base+8, not at the SUBQ.W #4, A7 at base+0.
    runner.bus.write_word(base + 10, 0x62F6);

    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.m68k.cpu.write_reg(Register::D3, 500);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    let pc_after_trap = base + 4;
    let mut count = 0usize;
    runner.try_tickcount_spin_fastfwd(pc_after_trap, None, &mut count);

    assert_eq!(runner.guest_tick(), 100);
    assert_eq!(count, 0);
}

/// One arm of the virtual-cursor equivalence test: a held-button poll loop
/// (StillDown, SetRect into a record, a load of a word the host may change)
/// that the parking prover leaves alone, because SetRect is not on its
/// list, plus a Time Manager task and a Sound Manager doubleback callback,
/// both written in 68k code.
struct VirtualIdleArm {
    runner: FixtureRunner,
    rect: u32,
    watched: u32,
    timer_marker: u32,
    sound_marker: u32,
    callback: u32,
}

fn virtual_idle_arm(virtual_idle: bool) -> VirtualIdleArm {
    let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
    runner.virtual_idle_enabled = virtual_idle;
    let base = 0x0001_0000u32;
    let rect = 0x0003_0000u32;
    let watched = 0x0003_0010u32;
    let timer_marker = 0x0003_0020u32;
    let sound_marker = 0x0003_0030u32;
    let timer_callback = 0x0002_0000u32;
    let sound_callback = 0x0002_0100u32;

    // `watched` is read just after the anchor, so a host write to it
    // between slices reaches the CPU only after the next arrival: only the
    // write journal can tell a kept recording that its pass changed.
    let mut program = vec![
        0x554F, // SUBQ.W #2,A7
        0xA973, // _StillDown
        0x121F, // MOVE.B (A7)+,D1
        0x3439, // MOVE.W watched,D2
        (watched >> 16) as u16,
        watched as u16,
        0x4879, // PEA rect
        (rect >> 16) as u16,
        rect as u16,
    ];
    for coordinate in [10u16, 20, 30, 40] {
        program.extend([0x3F3C, coordinate]); // MOVE.W #coordinate,-(A7)
    }
    program.extend([
        0xA8A7, // _SetRect
        0x60DA, // BRA.S base
    ]);
    for (index, word) in program.into_iter().enumerate() {
        runner.bus.write_word(base + 2 * index as u32, word);
    }
    // Time Manager task: ADDQ.W #1,timer_marker; RTS.
    for (index, word) in [
        0x5279,
        (timer_marker >> 16) as u16,
        timer_marker as u16,
        0x4E75,
    ]
    .into_iter()
    .enumerate()
    {
        runner.bus.write_word(timer_callback + 2 * index as u32, word);
    }
    // Doubleback procedure: ADDQ.W #1,sound_marker; RTD #8 (two Pascal
    // arguments).
    for (index, word) in [
        0x5279,
        (sound_marker >> 16) as u16,
        sound_marker as u16,
        0x4E74,
        0x0008,
    ]
    .into_iter()
    .enumerate()
    {
        runner.bus.write_word(sound_callback + 2 * index as u32, word);
    }

    runner.m68k.cpu.write_reg(Register::PC, base);
    runner.m68k.cpu.write_reg(Register::A7, 0x0010_0000);
    runner.bus.write_long(0x016A, 100);
    runner.set_guest_tick_for_test(100);
    runner.set_instructions_per_tick(20_000);
    runner.dispatcher.input_state.set_mouse_button_for_test(true);
    runner.dispatcher.timer_tasks.push(TimerTask {
        task_ptr: 0x0039_38C8,
        architecture: CallbackTaskArchitecture::M68k,
        extended: false,
        callback: timer_callback,
        active: true,
        fire_at_tick: 101,
        // Well inside tick 101, so a cursor must stop short of it.
        fire_at_subtick: 101_437_000,
        last_fired_tick: None,
    });
    VirtualIdleArm {
        runner,
        rect,
        watched,
        timer_marker,
        sound_marker,
        callback: sound_callback,
    }
}

impl VirtualIdleArm {
    /// Everything a slice boundary exposes: what the slice reported, the
    /// clock and budget, the CPU, and all of guest RAM.
    fn observe(&self, steps: usize, running: bool) -> (usize, bool, u32, i32, u64, CpuArchitecturalSnapshot, u64) {
        use std::hash::{Hash, Hasher};
        let mut ram = std::collections::hash_map::DefaultHasher::new();
        self.runner.bus.ram_slice(0, self.runner.bus.ram_size()).hash(&mut ram);
        (
            steps,
            running,
            self.runner.guest_tick(),
            self.runner.tick_budget,
            self.runner.total_instructions,
            CpuArchitecturalSnapshot::capture(&self.runner.m68k.cpu.core),
            ram.finish(),
        )
    }
}

#[test]
fn virtual_idle_cursor_is_invisible_across_fixed_slices() {
    // The same guest runs with the virtual cursor off and on, through the
    // same fixed slices (sizes chosen to end mid-pass), with a doubleback
    // callback queued between two slices, a host write to the polled
    // record and to a word the loop reads, and a Time Manager task due
    // mid-tick. Every slice must report the same steps and leave the same
    // tick, budget, instruction count, CPU and memory.
    let mut plain = virtual_idle_arm(false);
    let mut cursor = virtual_idle_arm(true);
    let slices = [2_993usize, 4_001, 997, 6_007, 3_331, 5_003, 7_919, 1_009];
    for round in 0..12 {
        for (index, &slice) in slices.iter().enumerate() {
            for arm in [&mut plain, &mut cursor] {
                match (round, index) {
                    (2, 3) => {
                        arm.runner.bus.write_word(arm.rect + 2, 0x7777);
                        arm.runner.bus.write_word(arm.watched, 0x1234);
                    }
                    (4, 1) | (7, 6) => {
                        let header = 0x0020_0000;
                        let buffer = 0x0020_1000;
                        arm.runner.bus.write_long(header + 12, buffer);
                        arm.runner.bus.write_long(buffer + 4, 1);
                        arm.runner.dispatcher.sound_manager.queue_doubleback_callback(
                            PendingDoubleBackCallback {
                                callback_addr: arm.callback,
                                chan_ptr: 0x0039_3000,
                                header_ptr: header,
                                exhausted_buffer_index: 0,
                            },
                        );
                    }
                    _ => {}
                }
            }
            let (steps, running) = plain.runner.run_steps(slice, None);
            let expected = plain.observe(steps, running);
            let (steps, running) = cursor.runner.run_steps(slice, None);
            assert!(
                expected == cursor.observe(steps, running),
                "round {round} slice {index}: the cursor changed what the slice exposed"
            );
        }
    }
    assert_eq!(plain.runner.bus.read_word(plain.timer_marker), 1, "the timer ran");
    assert_eq!(plain.runner.bus.read_word(plain.sound_marker), 2, "both callbacks ran");
    assert_eq!(plain.runner.virtual_idle_entries, 0);
    assert!(
        cursor.runner.virtual_idle_entries > 0,
        "the cursor must actually have skipped passes"
    );
}

#[test]
fn track_control_custom_cdef_preserves_guest_parts_and_release_cancellation() {
    for (initial_part, release_part) in [(42u16, 42u16), (42, 17), (42, 0), (0, 0)] {
        let mut runner = FixtureRunner::new(8 * 1024 * 1024, FixtureRunnerConfig::default());
        let base = 0x0001_0000u32;
        let sp = 0x0010_0000u32;
        let port = runner.bus.alloc(200);
        let handle = runner.bus.alloc(4);
        let pointer = runner.bus.alloc(36);
        let cdef_handle = runner.bus.alloc(4);
        let cdef = runner.bus.alloc(48);
        let tested_point = runner.bus.alloc(4);
        let supplied_part = runner.bus.alloc(4);
        let calls = runner.bus.alloc(2);
        runner.bus.write_long(supplied_part, u32::from(initial_part));
        runner.bus.write_word(base, 0xA968);
        runner.bus.write_word(base + 2, 0x60FE); // caller waits here after TrackControl
        runner.bus.write_word(cdef, 0x4E56); // LINK A6,#0
        runner.bus.write_word(cdef + 2, 0);
        runner.bus.write_word(cdef + 4, 0x0C6E); // CMPI.W #1,12(A6): testCntl only
        runner.bus.write_word(cdef + 6, 1);
        runner.bus.write_word(cdef + 8, 12);
        runner.bus.write_word(cdef + 10, 0x6608); // BNE.S skip point capture
        runner.bus.write_word(cdef + 12, 0x23EE); // MOVE.L 8(A6),tested_point
        runner.bus.write_word(cdef + 14, 8);
        runner.bus.write_long(cdef + 16, tested_point);
        runner.bus.write_word(cdef + 20, 0x2039); // MOVE.L supplied_part,D0
        runner.bus.write_long(cdef + 22, supplied_part);
        runner.bus.write_word(cdef + 26, 0x2D40); // MOVE.L D0,20(A6): Pascal result
        runner.bus.write_word(cdef + 28, 20);
        runner.bus.write_word(cdef + 30, 0x5279); // ADDQ.W #1,calls
        runner.bus.write_long(cdef + 32, calls);
        runner.bus.write_word(cdef + 36, 0x4E5E); // UNLK A6
        runner.bus.write_word(cdef + 38, 0x4E74); // RTD #12
        runner.bus.write_word(cdef + 40, 12);
        runner.bus.write_long(cdef_handle, cdef);
        runner.bus.write_long(handle, pointer);
        runner.bus.write_long(pointer + 4, port);
        runner.bus.write_word(port + 8, (-100i16) as u16);
        runner.bus.write_word(port + 10, (-120i16) as u16);
        for (offset, value) in [(8, 10), (10, 10), (12, 50), (14, 80)] {
            runner.bus.write_word(pointer + offset, value);
        }
        runner.bus.write_byte(pointer + 16, 255);
        runner.bus.write_long(pointer + 24, cdef_handle);
        runner
            .dispatcher
            .control_manager
            .register(handle, pointer, 160 << 4, 0);
        runner
            .dispatcher
            .input_state
            .set_mouse_button_for_test(true);
        runner
            .dispatcher
            .input_state
            .set_mouse_position_for_test((120, 140));
        runner.bus.write_long(sp, 0);
        runner.bus.write_word(sp + 4, 120); // live global point: local (20,20)
        runner.bus.write_word(sp + 6, 140);
        runner.bus.write_long(sp + 8, handle);
        runner.m68k.cpu.write_reg(Register::PC, base);
        runner.m68k.cpu.write_reg(Register::A7, sp);
        let (_, running) = runner.run_steps(512, None);
        assert!(running);
        if initial_part == 0 {
            assert!(!runner.dispatcher.is_control_tracking());
            assert_eq!(runner.bus.read_word(sp + 12), 0);
            assert_eq!(runner.bus.read_word(calls), 1);
            assert_eq!(runner.bus.read_byte(pointer + 17), 0);
            assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp + 12);
            continue;
        }
        assert!(runner.dispatcher.is_control_tracking());
        assert_eq!(runner.bus.read_byte(pointer + 17), 42);
        assert_eq!(runner.bus.read_long(tested_point), (20 << 16) | 20);
        assert_eq!(
            runner.bus.read_word(calls),
            2,
            "guest test and pressed drawing must execute once"
        );
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp);
        runner
            .bus
            .write_long(supplied_part, u32::from(release_part));
        runner
            .dispatcher
            .input_state
            .set_mouse_position_for_test((105, 125));
        runner
            .dispatcher
            .input_state
            .set_mouse_button_for_test(false);
        runner
            .bus
            .write_byte(crate::memory::globals::addr::MB_STATE, 0x80);
        let (_, running) = runner.run_steps(512, None);
        assert!(running);
        assert!(!runner.dispatcher.is_control_tracking());
        assert_eq!(
            runner.bus.read_word(sp + 12),
            if release_part == 42 { 42 } else { 0 }
        );
        assert_eq!(runner.bus.read_byte(pointer + 17), 0);
        assert_eq!(runner.bus.read_long(tested_point), (5 << 16) | 5);
        assert_eq!(
            runner.bus.read_word(calls),
            4,
            "release hit test and restoration must execute"
        );
        assert_eq!(runner.m68k.cpu.read_reg(Register::A7), sp + 12);
    }
}