ps-qa 0.5.7

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

use std::collections::{HashMap, HashSet};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::time::{Duration, Instant};

use blitz_control_protocol::{
    AgentAction, AgentControlRequest, AgentSnapshot, CaptureRequest, CapturedImage, DebugResponse,
    DebugStream, DiagnosticsRequest, InputCommand, Modifiers, PointerPhase, RendererMetrics,
    SemanticNode, SnapshotRequest, WindowComposition,
};
use eyre::{Context, Result, bail, eyre};

use crate::capture_analysis::{
    CHANNEL_TOLERANCE as CAPTURE_CHANNEL_TOLERANCE, measure_ink, measure_interior_ink,
    pixel_delta as captured_pixel_delta, pixels_change, pixels_hold,
    pixels_hold_with_tolerance as captured_pixels_hold, rgb_pixels_hold,
    save_artifacts as save_pixel_artifacts, write_ppm as write_capture_ppm,
};
use crate::computed_style::{
    font_size, full_opacity, opaque_background, transparent_background, wait_for_larger_font,
};
use crate::diagnostics::{dom, metrics, nodes, panes, spill, transcript};
use crate::inspector::{Client, inspect, inspect_subtree};
use crate::interaction::{
    click_named, hover_over, press_key, scroll, scroll_events, type_keys, type_text,
};
use crate::layout_report::layout;
use crate::target::{
    exact_selector_matches_node, locate_control, name_matches, offscreen, painted_bounds,
    painted_named, resolved_action_target, selector_matches_node, viewport_of,
};
use crate::timing::{check_timeout, sleep_pace};
use crate::{app, audit, cli, inspector, paint_audit, qa, reach, report, sweep};

/// Wait only for the destination a navigation check declared.
///
/// Background counters and provider refreshes can keep the whole semantic tree
/// changing indefinitely. They are irrelevant to whether the requested panel
/// arrived, so navigation gets the same sub-second budget as every other QA
/// action and polls its exact marker.
async fn wait_for_arrival(
    client: &mut Client,
    destination: Option<&reach::Surface>,
    want_here: &str,
) -> Result<bool> {
    let deadline = tokio::time::Instant::now() + check_timeout(900);
    let mut painted_streak = 0;
    let mut root = None;
    loop {
        let (tree, scoped) = if let Some(node_id) = root {
            match inspect_subtree(client, node_id).await {
                Ok((tree, _)) => (tree, true),
                // A reconciliation may replace the node between samples. One
                // full read reacquires it; a stale id is not a failed check.
                Err(_) => {
                    root = None;
                    painted_streak = 0;
                    (inspect(client).await?.0, false)
                }
            }
        } else {
            (inspect(client).await?.0, false)
        };
        let arrived = arrival_sample_matches(&tree.nodes, destination, want_here, scoped);
        if arrived && root.is_none() {
            root = arrival_anchor(&tree.nodes, destination, want_here);
        } else if !arrived && root.is_some() {
            root = None;
        }
        if stable_arrival(&mut painted_streak, arrived) {
            return Ok(true);
        }
        if tokio::time::Instant::now() >= deadline {
            return Ok(false);
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
}

fn arrival_sample_matches(
    nodes: &[SemanticNode],
    destination: Option<&reach::Surface>,
    want_here: &str,
    scoped: bool,
) -> bool {
    if scoped {
        // The anchor subtree intentionally excludes permanent chrome such as
        // the selected tab. The preceding full snapshot already proved that
        // chrome state; scoped polls only need to prove that the destination
        // marker remains painted. Reapplying the whole-surface rule here made
        // every permanent surface oscillate full -> subtree -> full until its
        // deadline.
        arrival_anchor(nodes, destination, want_here).is_some()
    } else {
        destination.map_or_else(
            || painted_named(nodes, want_here),
            |surface| reach::on_surface(nodes, surface),
        )
    }
}

/// The smallest node that proves an arrival condition.
///
/// Its id is used only as the next snapshot root. If the framework remounts it,
/// the caller clears the id and reacquires from one full snapshot.
fn arrival_anchor(
    nodes: &[SemanticNode],
    destination: Option<&reach::Surface>,
    want_here: &str,
) -> Option<u64> {
    let marker = destination.and_then(|surface| surface.marker.as_deref());
    nodes
        .iter()
        .find(|node| {
            reach::onscreen(node)
                && marker.map_or_else(
                    || selector_matches_node(node, want_here),
                    |marker| node.name.contains(marker),
                )
        })
        .map(|node| node.id)
}

/// Wait for the specific document tab, not merely any document-shaped pane.
///
/// Switching between projects leaves the outgoing project surface painted
/// while the incoming pane reconciles. A generic project marker therefore
/// reports arrival hundreds of milliseconds too early. Permanent surfaces do
/// not share that ambiguity and keep the cheaper ordinary arrival path.
async fn wait_for_navigation_arrival(
    client: &mut Client,
    destination: Option<&reach::Surface>,
    want_here: &str,
    named_document: bool,
    document_name: &str,
) -> Result<bool> {
    if !named_document {
        return wait_for_arrival(client, destination, want_here).await;
    }
    let deadline = tokio::time::Instant::now() + check_timeout(900);
    let mut painted_streak = 0;
    let mut selected_tab = None;
    loop {
        let (tree, scoped) = if let Some(node_id) = selected_tab {
            match inspect_subtree(client, node_id).await {
                Ok((tree, _)) => (tree, true),
                Err(_) => {
                    selected_tab = None;
                    painted_streak = 0;
                    (inspect(client).await?.0, false)
                }
            }
        } else {
            (inspect(client).await?.0, false)
        };
        // The exact selected tab disambiguates the incoming document from any
        // retained outgoing pane. Do not require the final action target here:
        // it may intentionally live in a collapsed or search-deferred section
        // that can only be materialized after navigation has completed.
        let arrived = named_document_is_active(&tree.nodes, document_name)
            && (scoped
                || destination.is_some_and(|surface| reach::on_surface(&tree.nodes, surface)));
        if arrived && selected_tab.is_none() {
            let tab_name = format!("{document_name}{document_name}");
            selected_tab = tree
                .nodes
                .iter()
                .find(|node| {
                    node.role.eq_ignore_ascii_case("button")
                        && node.name.eq_ignore_ascii_case(&tab_name)
                        && node.selected
                        && reach::onscreen(node)
                })
                .map(|node| node.id);
        } else if !arrived && selected_tab.is_some() {
            selected_tab = None;
        }
        if stable_arrival(&mut painted_streak, arrived) {
            return Ok(true);
        }
        if tokio::time::Instant::now() >= deadline {
            return Ok(false);
        }
        tokio::time::sleep(Duration::from_millis(25)).await;
    }
}

/// A newly mounted overlay or hover action can paint for one renderer snapshot,
/// reconcile, and immediately receive a different node id. Treating that first
/// frame as ready races the actual action against the remount. Three consecutive
/// painted snapshots cost only 50ms in the stable case and prove the control a
/// user sees is still present when the harness drives it.
fn stable_arrival(painted_streak: &mut u8, arrived: bool) -> bool {
    if arrived {
        *painted_streak = painted_streak.saturating_add(1);
    } else {
        *painted_streak = 0;
    }
    *painted_streak >= 3
}

/// Drive every panel check and report what the renderer did.
///
/// Each check runs against the live tree, and the three steps are separated on
/// purpose: hovering is what makes the row controls exist at all, and a check
/// that skips it reports a missing feature rather than a test driving the app
/// wrongly. That mistake is why the hover regression shipped.
///
/// Returns the number of failures, so the caller can set an exit code.
/// A spawned host that is killed when it goes out of scope.
///
/// `kill` on the happy path is not enough: anything that leaves the loop early
/// (a panic, a `?`, a break) orphans the process, and an orphaned host holds a
/// socket and a document for the rest of the session. One leaked during a sweep
/// that panicked on a missing profile, and it had to be found and killed by
/// hand.
struct HostProcess(std::process::Child);

impl Drop for HostProcess {
    fn drop(&mut self) {
        let _ = self.0.kill();
        let _ = self.0.wait();
    }
}

/// A node to park the pointer on between hovers.
///
/// The largest painted node, which is the window or its root container: it is
/// always present, and it is never the small control a check is hovering.
async fn away_target(client: &mut Client) -> Result<Option<u64>> {
    let (snapshot, _) = inspect(client).await?;
    Ok(snapshot
        .nodes
        .iter()
        .filter_map(|node| node.bounds.map(|b| (node.id, b[2] * b[3])))
        .max_by(|a, b| a.1.total_cmp(&b.1))
        .map(|(id, _)| id))
}

/// Move the pointer to the document root and let authored hover state settle.
async fn park_pointer(client: &mut Client) -> std::result::Result<(), String> {
    if let Some(root) = away_target(client)
        .await
        .map_err(|error| error.to_string())?
    {
        client
            .agent(&AgentControlRequest::Act(AgentAction::Hover {
                node_id: root,
            }))
            .await
            .map_err(|error| error.to_string())?;
    }
    Ok(())
}

/// Enter a named control repeatedly, leaving between entries.
///
/// Kept separate from the QA loop because overlays need the same abuse after
/// their trigger has prepared them, while ordinary hover-revealed controls
/// need it before preparation.
async fn repeat_hover(
    client: &mut Client,
    hover: &qa::Hover,
    leave_after: bool,
) -> std::result::Result<(), String> {
    let want = hover.target();
    let node_id = scroll_hover_target_into_view(client, want).await?;
    if cli::trace() {
        println!("        hovering {want:?} (id {node_id})");
    }

    // A previous check may have left the pointer on this exact node. Sending
    // Hover to it again is then a move within the same target, not a new enter,
    // so hover-revealed row actions never mount. Every declared hover cycle
    // starts from the same neutral state, including the first one.
    if let Some(root) = away_target(client)
        .await
        .map_err(|error| error.to_string())?
    {
        client
            .agent(&AgentControlRequest::Act(AgentAction::Hover {
                node_id: root,
            }))
            .await
            .map_err(|error| error.to_string())?;
    }

    for turn in 0..hover.times() {
        if turn > 0
            && let Some(root) = away_target(client)
                .await
                .map_err(|error| error.to_string())?
        {
            client
                .agent(&AgentControlRequest::Act(AgentAction::Hover {
                    node_id: root,
                }))
                .await
                .map_err(|error| error.to_string())?;
        }
        client
            .agent(&AgentControlRequest::Act(AgentAction::Hover { node_id }))
            .await
            .map_err(|error| error.to_string())?;
    }

    if leave_after
        && let Some(root) = away_target(client)
            .await
            .map_err(|error| error.to_string())?
    {
        client
            .agent(&AgentControlRequest::Act(AgentAction::Hover {
                node_id: root,
            }))
            .await
            .map_err(|error| error.to_string())?;
    }

    Ok(())
}

type HoverSignature = (String, String, Option<String>, Option<String>);

/// Count stable semantic identities on the active surface.
///
/// A later hover may legitimately mount one new status node. Accumulation is
/// narrower: a semantic identity that was already present gains additional
/// retained copies on every entry. Comparing these counts avoids treating an
/// unrelated whole-document update as a component leak.
fn hover_signature_counts(
    nodes: &[SemanticNode],
) -> std::collections::BTreeMap<HoverSignature, usize> {
    let scope = outcome_poll_scope(nodes).map(|scope| scope.baseline_ids);
    let mut counts = std::collections::BTreeMap::new();
    for node in nodes.iter().filter(|node| {
        scope
            .as_ref()
            .is_none_or(|surface_ids| surface_ids.contains(&node.id))
    }) {
        if node.name.is_empty() && node.slot.is_none() && node.dom_id.is_none() {
            continue;
        }
        let signature = (
            node.role.to_ascii_lowercase(),
            node.name.clone(),
            node.slot.clone(),
            node.dom_id.clone(),
        );
        *counts.entry(signature).or_insert(0) += 1;
    }
    counts
}

fn accumulated_hover_signatures(
    baseline: &std::collections::BTreeMap<HoverSignature, usize>,
    after: &std::collections::BTreeMap<HoverSignature, usize>,
) -> Vec<(HoverSignature, usize)> {
    after
        .iter()
        .filter_map(|(signature, count)| {
            let before = baseline.get(signature).copied().unwrap_or_default();
            (before > 0 && *count > before).then(|| (signature.clone(), count - before))
        })
        .collect()
}

/// Put a future hover target in its final viewport position without entering it.
///
/// Pixel checks must do this before their baseline capture. Letting the hover
/// helper scroll after that capture compares two viewport positions and reports
/// movement as a paint regression.
async fn scroll_hover_target_into_view(
    client: &mut Client,
    want: &str,
) -> std::result::Result<u64, String> {
    let explicit_role = want.split_once(':').map(|(role, _)| role);
    let any_role = ["*"];
    let roles = explicit_role.as_slice();
    let roles = if roles.is_empty() { &any_role } else { roles };
    locate_control(client, want, roles)
        .await
        .map(|(node_id, _)| node_id)
        .map_err(|error| format!("could not hover {want:?}: {error}"))
}

/// Capture one declared rendered region through the renderer's own paint path.
fn capture_node_id(nodes: &[SemanticNode], selector: &str) -> std::result::Result<u64, String> {
    // Decorative SVGs are intentionally aria-hidden and therefore semantic
    // `visible=false` even while the renderer gives them a real box. Only an
    // explicit presentation-role selector opts into capturing that artwork;
    // hidden controls and retained overlays keep the ordinary visibility gate.
    let captures_decorative_art = selector
        .split_once(':')
        .is_some_and(|(role, _)| role.eq_ignore_ascii_case("presentation"));
    nodes
        .iter()
        .filter(|node| {
            selector_matches_node(node, selector)
                && (node.visible || captures_decorative_art && node.role == "presentation")
                && node.bounds.is_some_and(|b| b[2] > 0.0 && b[3] > 0.0)
        })
        .max_by(|a, b| {
            let area = |node: &&SemanticNode| {
                node.bounds
                    .map(|bounds| bounds[2] * bounds[3])
                    .unwrap_or_default()
            };
            area(a).total_cmp(&area(b))
        })
        .map(|node| node.id)
        .ok_or_else(|| format!("no painted capture region matching {selector:?}"))
}

async fn capture_region(
    client: &mut Client,
    selector: &str,
) -> std::result::Result<CapturedImage, String> {
    let (tree, _) = inspect(client).await.map_err(|error| error.to_string())?;
    let node_id = capture_node_id(&tree.nodes, selector)?;
    capture_node_region(client, node_id, selector).await
}

/// Put the complete pixel subject at the start of each enclosing scrollport.
///
/// Action targeting only needs some clickable portion on screen, whereas a
/// region comparison needs every compared pixel to come from the document.
/// `locate_control` deliberately accepts partial visibility, so capture setup
/// must issue ScrollIntoView unconditionally.
async fn reveal_capture_region(
    client: &mut Client,
    selector: &str,
) -> std::result::Result<u64, String> {
    let (tree, _) = inspect(client).await.map_err(|error| error.to_string())?;
    let node_id = capture_node_id(&tree.nodes, selector)?;
    client
        .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
            node_id,
        }))
        .await
        .map_err(|error| error.to_string())?;
    tokio::time::sleep(Duration::from_millis(25)).await;
    Ok(node_id)
}

/// Require a captured component to contain visible raster output.
async fn visible_ink(client: &mut Client, selector: &str) -> std::result::Result<(), String> {
    let image = capture_region(client, selector).await?;
    let ink = measure_ink(&image).map_err(|error| error.to_string())?;
    if ink.visible == 0 {
        Err(format!(
            "{selector:?} occupies {}x{} but draws no pixels distinguishable from its background",
            image.width, image.height
        ))
    } else {
        Ok(())
    }
}

/// Require visible content inside a control, rather than counting its border.
async fn interior_ink(client: &mut Client, selector: &str) -> std::result::Result<(), String> {
    let image = capture_region(client, selector).await?;
    let ink = measure_interior_ink(&image).map_err(|error| error.to_string())?;
    if ink.visible == 0 {
        Err(format!(
            "{selector:?} occupies {}x{} but its interior contains no pixels distinguishable from its background",
            image.width, image.height
        ))
    } else {
        Ok(())
    }
}

/// Require the platform compositor to carry no application tint at zero.
///
/// This deliberately does not inspect pixels. An unknown desktop and native
/// blur make pixel attribution probabilistic; the runtime can report the
/// surface mode and the exact tint installed on its native glass view.
async fn transparent_window_tint(client: &mut Client) -> std::result::Result<(), String> {
    let answer = client
        .diagnostics(&DiagnosticsRequest::WindowComposition)
        .await
        .map_err(|error| format!("could not inspect native window composition: {error}"))?;
    let composition = match answer.response {
        DebugResponse::WindowComposition(composition) => composition,
        other => {
            return Err(format!(
                "asked for native window composition, got {other:?}"
            ));
        }
    };
    if cli::trace() {
        eprintln!(
            "        native window: transparent={} glass={} backend={} tint={:?} radius={:?}",
            composition.surface_transparent,
            composition.glass_enabled,
            composition.glass_backend.as_deref().unwrap_or("unknown"),
            composition.tint_rgba,
            composition.radius,
        );
    }
    require_transparent_window_tint(&composition)
}

fn require_transparent_window_tint(
    composition: &WindowComposition,
) -> std::result::Result<(), String> {
    if !composition.supported {
        return Err("this host cannot inspect native window composition".into());
    }
    if !composition.surface_transparent {
        return Err("the native window surface is opaque".into());
    }
    if !composition.glass_enabled {
        return Err("the native glass layer was not installed".into());
    }
    let backend = composition.glass_backend.as_deref().unwrap_or("unknown");
    let Some([red, green, blue, alpha]) = composition.tint_rgba else {
        return Err(format!(
            "native glass backend {backend:?} did not expose an applied tint"
        ));
    };
    if alpha != 0 {
        return Err(format!(
            "native glass backend {backend:?} retains tint rgba({red}, {green}, {blue}, {alpha}) at zero opacity"
        ));
    }
    Ok(())
}

/// Capture a node whose identity has already been resolved.
///
/// Stability checks take several frames of the same region. Re-inspecting the
/// whole semantic tree before every one made the check mostly a tree-transfer
/// benchmark and could not fit four frames inside its own interaction budget.
async fn capture_node_region(
    client: &mut Client,
    node_id: u64,
    selector: &str,
) -> std::result::Result<CapturedImage, String> {
    // CPU rendering is diagnostic work, not a control interaction. Keep the
    // sub-second action contract for clicks and keys, but do not kill a valid
    // capture merely because shaping/rasterising its first frame is slower.
    let previous_timeout = client.request_timeout();
    client.set_request_timeout(Duration::from_secs(15));
    let started = std::time::Instant::now();
    let answer = client
        .diagnostics(&DiagnosticsRequest::Capture(CaptureRequest {
            node_id: Some(node_id),
            scale: 1.0,
        }))
        .await;
    client.set_request_timeout(previous_timeout);
    if cli::trace_capture() {
        eprintln!("capture {selector:?}: request took {:?}", started.elapsed());
    }
    let answer = answer.map_err(|error| format!("could not capture {selector:?}: {error}"))?;
    match answer.response {
        DebugResponse::Captured(image) => Ok(image),
        other => Err(format!("asked for a rendered frame, got {other:?}")),
    }
}

/// Capture once the rendered region stops changing, without guessing how long
/// its authored transition lasts.
async fn capture_stable_region(
    client: &mut Client,
    selector: &str,
    settle_timeout: Duration,
) -> std::result::Result<CapturedImage, String> {
    // Two adjacent samples are not a settled animation. A delayed RAF or one
    // quiet interval between keyframes can produce the same pixels twice and
    // then keep moving; fast regional capture exposed that old assumption.
    // Four matching samples span three refresh intervals, long enough to
    // cross an ordinary frame scheduling gap without baking any component's
    // authored transition duration into the harness.
    const QUIET_SAMPLES: usize = 4;
    let (tree, _) = inspect(client).await.map_err(|error| error.to_string())?;
    let node_id = capture_node_id(&tree.nodes, selector)?;
    let mut previous = capture_node_region(client, node_id, selector).await?;
    // The deadline budgets authored motion and quiet intervals, not the
    // renderer's capture work. A CPU-backed regional capture can legitimately
    // take longer than one refresh interval; charging that work to the quiet
    // deadline made an unchanged frame fail before four samples existed.
    let mut deadline = tokio::time::Instant::now() + settle_timeout;
    let mut matching = 1;
    loop {
        tokio::time::sleep(Duration::from_millis(16)).await;
        let capture_started = tokio::time::Instant::now();
        let current = capture_node_region(client, node_id, selector).await?;
        deadline += tokio::time::Instant::now().duration_since(capture_started);
        let held =
            captured_pixels_hold(&previous, &current, CAPTURE_CHANNEL_TOLERANCE).unwrap_or(false);
        if cli::trace_capture() {
            let delta = captured_pixel_delta(&previous, &current)
                .map(|(pixels, max)| format!("{pixels} pixel(s), max {max}"))
                .unwrap_or_else(|error| error);
            eprintln!(
                "capture {selector:?}: {}x{} -> {}x{}, held={held}, streak={matching}, {delta}",
                previous.width, previous.height, current.width, current.height
            );
        }
        if held {
            matching += 1;
            if matching >= QUIET_SAMPLES {
                return Ok(current);
            }
        } else {
            matching = 1;
        }
        if tokio::time::Instant::now() >= deadline {
            let detail = if previous.width != current.width || previous.height != current.height {
                format!(
                    "; last frame changed size from {}x{} to {}x{}",
                    previous.width, previous.height, current.width, current.height
                )
            } else {
                captured_pixel_delta(&previous, &current)
                    .map(|(pixels, max)| {
                        format!("; last frame changed {pixels} pixel(s), max channel delta {max}")
                    })
                    .unwrap_or_else(|error| format!("; {error}"))
            };
            return Err(format!(
                "rendered region {selector:?} did not settle within {}ms{detail}",
                settle_timeout.as_millis()
            ));
        }
        previous = current;
    }
}

/// Wait only for the first authored hover frame, not for the whole animation.
///
/// Capturing immediately after pointer delivery races the renderer: a valid
/// transition still has its pre-hover pixels until the next frame. A 100 ms
/// ceiling keeps the interaction contract responsive while allowing that one
/// frame to be produced.
async fn wait_for_pixels_change(
    client: &mut Client,
    selector: &str,
    before: &CapturedImage,
    timeout: Duration,
) -> std::result::Result<(), String> {
    let deadline = tokio::time::Instant::now() + timeout;

    loop {
        let after = capture_region(client, selector).await?;
        if pixels_change(before, &after).is_ok() {
            return Ok(());
        }
        if tokio::time::Instant::now() >= deadline {
            return pixels_change(before, &after);
        }
        tokio::time::sleep(Duration::from_millis(8)).await;
    }
}

/// Launch a host for one page and wait for the descriptor it announces.
///
/// Waiting for the line rather than sleeping is what makes this reliable on a
/// loaded machine: a fixed sleep reads a slow first paint as a host that never
/// started.
fn start_host(
    host: &std::path::Path,
    page: &std::path::Path,
    startup_timeout: Duration,
) -> std::result::Result<(HostProcess, std::path::PathBuf), String> {
    use std::io::BufRead;

    let mut child = HostProcess(
        std::process::Command::new(host)
            // The page this host is to serve. `QA_INSPECT_PAGE` is
            // `qa-inspect-host`'s interface; a host with a different one can
            // read its own environment and ignore this.
            .env("QA_INSPECT_PAGE", page)
            .stdout(std::process::Stdio::piped())
            // Host diagnostics belong to the sweep artifact. Discarding them
            // turns a startup or renderer failure into only "never announced
            // a descriptor", which hides the one message that explains it.
            .stderr(std::process::Stdio::inherit())
            .spawn()
            .map_err(|error| format!("launching {}: {error}", host.display()))?,
    );

    // Read on a thread with a deadline around it: a host that dies before
    // announcing would otherwise block for ever on a pipe that will never
    // produce a line.
    let stdout = child.0.stdout.take().expect("stdout was piped");
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let mut reader = std::io::BufReader::new(stdout);
        let mut line = String::new();
        let _ = reader.read_line(&mut line);
        let _ = tx.send(line);

        // Keep consuming stdout for the lifetime of the host. Closing the
        // pipe after the descriptor line would deliver EPIPE if a host emits
        // later diagnostics and could terminate an otherwise healthy sweep.
        let mut diagnostic = String::new();
        while reader.read_line(&mut diagnostic).unwrap_or_default() > 0 {
            eprint!("host: {diagnostic}");
            diagnostic.clear();
        }
    });

    match rx.recv_timeout(startup_timeout) {
        Ok(line) if !line.trim().is_empty() => {
            Ok((child, std::path::PathBuf::from(line.trim().to_owned())))
        }
        _ => Err("the host never announced a descriptor".to_owned()),
    }
}

/// Drive a component library one component at a time.
///
/// Each component gets its own host process, its own document and its own
/// socket, and the process is torn down before the next one starts. That
/// isolation is the whole design: a shared process makes every check
/// order-dependent, so a failure caused by the previous component's leftover
/// state is indistinguishable from a real one, and a component that wedges the
/// renderer takes down every component after it.
///
/// The host is expected to print its descriptor path on stdout once it is
/// serving. Waiting for that line rather than sleeping a fixed interval is what
/// makes this reliable on a loaded machine: a slow first paint would otherwise
/// read as a component that never mounted.
async fn sweep_components(
    ids: &[String],
    host: &std::path::Path,
    dists: &std::path::Path,
    checks_dir: Option<&std::path::Path>,
    startup_timeout: Duration,
    mode: cli::CheckMode,
) -> Result<usize> {
    /*
     * A directory per component, or a page per component.
     *
     * A bundler that emits `button.html` beside `button.js` already produces
     * one page per component; requiring a directory each meant every project
     * copied its build into throwaway directories first. Both layouts are
     * discovered here so neither needs a staging step.
     */
    let ids: Vec<String> = if ids.is_empty() {
        let mut found: Vec<String> = std::fs::read_dir(dists)
            .with_context(|| format!("reading {}", dists.display()))?
            .filter_map(|entry| entry.ok())
            .filter_map(|entry| {
                let path = entry.path();
                if path.is_dir() {
                    entry.file_name().into_string().ok()
                } else if path.extension().is_some_and(|ext| ext == "html") {
                    path.file_stem()
                        .and_then(|stem| stem.to_str())
                        .map(str::to_owned)
                } else {
                    None
                }
            })
            .collect();
        found.sort();
        found.dedup();
        found
    } else {
        ids.to_vec()
    };

    if ids.is_empty() {
        bail!("no components to sweep under {}", dists.display());
    }

    let mut passed = 0_usize;
    let mut failed = 0_usize;
    let mut verdicts: Vec<(String, bool, String)> = Vec::new();

    for id in &ids {
        // A directory holding `index.html`, or `<id>.html` beside its siblings.
        // The host accepts either, so prefer whichever this build produced.
        let as_dir = dists.join(id);
        let as_page = dists.join(format!("{id}.html"));
        let dist = if as_dir.is_dir() {
            as_dir
        } else if as_page.is_file() {
            as_page
        } else {
            println!(
                "FAIL {id}: no built page at {} or {}",
                as_dir.display(),
                as_page.display()
            );
            verdicts.push((id.clone(), false, "no built page".to_owned()));
            failed += 1;
            continue;
        };

        /*
         * One host per *check*, not per component.
         *
         * Checks share a document otherwise, and a check then runs against
         * whatever its predecessor left behind. Measured on Dropdown: `-opens`
         * leaves the menu open, `-changes` presses the same trigger to prepare
         * itself, that press closes the menu, and the click lands on an item
         * that was on screen a moment earlier. Select failed the same way.
         * Both pass alone, so the sweep reported two working components as
         * broken.
         *
         * `run_qa` deliberately assumes the opposite for an application: there,
         * a later check inherits the surface an earlier one navigated to, and
         * re-navigating would be wrong. A component page has no surfaces and
         * nothing to inherit, so the isolation the checks assume has to come
         * from somewhere, and the host lifecycle is where it is cheapest.
         */
        let check_ids: Vec<String> = match qa::checks(checks_dir) {
            Ok(all) => all
                .iter()
                .filter(|check| check.group == *id)
                .map(|check| check.id.clone())
                .collect(),
            Err(error) => {
                println!("FAIL {id}: {error}");
                verdicts.push((id.clone(), false, error));
                failed += 1;
                continue;
            }
        };

        if check_ids.is_empty() {
            println!("FAIL {id}: no checks in group {id:?}");
            verdicts.push((id.clone(), false, "no checks".to_owned()));
            failed += 1;
            continue;
        }

        // One run per check, or a single run of the whole group when the caller
        // asked for the application's shared-state behaviour.
        let runs: Vec<String> = if mode == cli::CheckMode::Sweep {
            vec![id.clone()]
        } else {
            check_ids.clone()
        };

        let mut component_failed = 0_usize;
        let mut launch_error: Option<String> = None;

        for check_id in &runs {
            let started = match start_host(host, &dist, startup_timeout) {
                Ok(started) => started,
                Err(error) => {
                    launch_error = Some(error);
                    break;
                }
            };
            let (child, descriptor_path) = started;

            let outcome = run_component(&descriptor_path, Some(check_id), checks_dir).await;

            // Dropped here, which kills this check's host before the next
            // one starts.
            drop(child);

            match outcome {
                Ok(count) => component_failed += count,
                Err(error) => {
                    launch_error = Some(error.to_string());
                    break;
                }
            }
        }

        let outcome: Result<usize> = match launch_error {
            Some(error) => Err(eyre!(error)),
            None => Ok(component_failed),
        };

        match outcome {
            Ok(0) => {
                println!("PASS {id}");
                verdicts.push((id.clone(), true, String::new()));
                passed += 1;
            }
            Ok(count) => {
                println!("FAIL {id}: {count} check(s) failed");
                verdicts.push((id.clone(), false, format!("{count} check(s) failed")));
                failed += 1;
            }
            Err(error) => {
                println!("FAIL {id}: {error}");
                verdicts.push((id.clone(), false, error.to_string()));
                failed += 1;
            }
        }
    }

    println!();
    println!("passed: {passed}  failed: {failed}  of {}", ids.len());
    Ok(failed)
}

/// Attach to one component's host and judge its checks.
async fn run_component(
    descriptor_path: &std::path::Path,
    selector: Option<&str>,
    checks_dir: Option<&std::path::Path>,
) -> Result<usize> {
    let descriptor = inspector::discover(descriptor_path.to_str())?;
    let mut client = Client::connect(&descriptor.socket_path()).await?;
    client.initialize().await?;
    run_qa(&mut client, selector, checks_dir).await
}

async fn run_qa(
    client: &mut Client,
    group: Option<&str>,
    checks_dir: Option<&std::path::Path>,
) -> Result<usize> {
    let all = qa::checks(checks_dir).map_err(|error| eyre!(error))?;
    // A group *or* one check's id, so chasing a single failure does not mean
    // re-running its neighbours against the real app every time.
    // Stable surface buckets: keep dependent checks in manifest order while
    // avoiding repeated remounts of the same large application pane. The
    // application profile owns the surface openers; an unknown plain opener is
    // the configured dynamic document, while role-qualified openers stay in
    // the current bucket because they open a dialog within that surface.
    let surfaces = reach::surfaces();
    let dynamic = surfaces
        .iter()
        .position(|surface| surface.opener == reach::DYNAMIC_DOCUMENT)
        .unwrap_or(0);
    let mut affinity = dynamic;
    let mut selected: Vec<(usize, &qa::Check)> = Vec::new();
    for check in &all {
        if let Some(opener) = check.open.as_deref() {
            if let Some(index) = surfaces
                .iter()
                .position(|surface| surface.opener.eq_ignore_ascii_case(opener))
            {
                affinity = index;
            } else if !opener.contains(':') {
                affinity = dynamic;
            }
        }
        if group.is_none_or(|want| check.group == want || check.id == want) {
            selected.push((affinity, check));
        }
    }
    // Surface affinity amortizes large retained-pane mounts. Destructive
    // sequences outrank that optimization: deleting fixture state before a
    // later surface uses it makes an ordered shared sweep conflict with itself.
    selected.sort_by_key(|(surface, check)| (check.destructive, *surface));
    let selected: Vec<&qa::Check> = selected.into_iter().map(|(_, check)| check).collect();
    if selected.is_empty() {
        let mut names: Vec<String> = all
            .iter()
            .map(|check| format!("{} ({})", check.id, check.group))
            .collect();
        names.sort();
        bail!(
            "no check or group matching {group:?}. known:\n  {}",
            names.join("\n  ")
        );
    }

    let mut results: Vec<CheckResult<'_>> = Vec::new();
    for check in selected {
        let full_check_started = Instant::now();
        let mut retries = 0;
        // Navigation and disclosure materialization are suite setup. Give them
        // a bounded but realistic budget; the measured control action below
        // switches the transport to the sub-second contract.
        client.set_request_timeout(Duration::from_secs(15));
        /*
         * Navigate first, and snapshot *after*, or the baseline is the wrong
         * surface entirely and every count is measured against a screen the
         * check is not about.
         *
         * A failure here is the check's own setup failing, reported as such:
         * "could not open" rather than a verdict about the control, which is a
         * distinction that cost a round of chasing a control that was simply
         * on another surface.
         */
        /*
         * Navigation is best-effort: already being on the surface is success.
         *
         * Checks run in sequence, so a later one often inherits exactly the
         * screen it would have navigated to, and the control it navigates *by*
         * is no longer on it. Treating that as a failure reported "could not
         * open" for a check whose own press had already worked - the verdict
         * was right there and got overwritten by its own setup.
         *
         * A genuinely unreachable surface still fails, one step later, when
         * the check cannot find the control it is about.
         */
        let mut open_error = None;
        let mut pixel_outcome: Option<std::result::Result<(), String>> = None;
        if let Some(want) = check.open.as_deref() {
            /*
             * A permanent surface marker can answer "already there". A
             * document marker cannot: every document renders the same
             * composer, so `Send` only proves that some document is in front.
             *
             * Named documents are activated every time. Activating an already
             * active tab is idempotent, and is safer than probing a check
             * target that may legitimately be collapsed, deferred, or mounted
             * only after hover.
             */
            let want_here: &str = check
                .hover
                .as_ref()
                .map(qa::Hover::target)
                .or(check.prepare.as_deref())
                .or(check.click.as_deref())
                .or(check.type_into.as_deref())
                .or(check.key_on.as_deref())
                .unwrap_or(&check.subject);
            let destination = surface_for_opener(want);
            let named_document = is_named_document_opener(want);
            let (here, _) = inspect(client).await?;
            let active_document_matches = named_document_is_active(&here.nodes, want);
            let arrived = arrived_without_navigation(
                &here.nodes,
                destination,
                want_here,
                named_document,
                active_document_matches,
            );
            if cli::trace() {
                let surface = reach::surfaces()
                    .iter()
                    .find(|surface| reach::on_surface(&here.nodes, surface))
                    .map(|surface| surface.name.as_str())
                    .unwrap_or("none");
                println!(
                    "        arrival want={want:?} destination={} target={want_here:?} \
                     named_document={named_document} arrived={arrived} on_surface={surface}",
                    destination.map_or("dynamic", |surface| surface.name.as_str()),
                );
            }
            if !arrived {
                /*
                 * Two steps, because the opener may not be on this surface.
                 *
                 * A document can be opened from a root-surface row, and once
                 * the document is in front that row is gone, so a check that navigates by it
                 * failed with "no visible, enabled, sized button" for a
                 * surface that was one press away. The configured root opener
                 * provides the recovery path.
                 */
                /*
                 * A tab is pressed, a row is double clicked, and which one
                 * this is cannot be known from the name - so try the cheap
                 * gesture first and escalate.
                 *
                 * Double clicking a tab-strip entry may toggle it rather than
                 * navigating, while a single row click may fold it, so
                 * committing to either gesture broke the other set of checks.
                 */
                let first_click = click_opener_quiet(client, want, named_document).await;
                let mut there = wait_for_navigation_arrival(
                    client,
                    destination,
                    want_here,
                    named_document,
                    want,
                )
                .await?;
                // A surface transition can briefly remove the opener before
                // its replacement paints. Retry the same semantic click after
                // settling; escalating that transient miss straight to a
                // document-row double-click skips ordinary button handlers.
                if !there && first_click.is_err() {
                    let _ = click_named_quiet(client, want).await;
                    there = wait_for_navigation_arrival(
                        client,
                        destination,
                        want_here,
                        named_document,
                        want,
                    )
                    .await?;
                }
                if !there && open_named(client, want).await.is_ok() {
                    there = wait_for_navigation_arrival(
                        client,
                        destination,
                        want_here,
                        named_document,
                        want,
                    )
                    .await?;
                }
                if !there {
                    if let Some(home) = reach::profile().home_opener.as_deref() {
                        let _ = click_named_quiet(client, home).await;
                    }
                    if let Err(error) = open_named(client, want).await {
                        open_error = Some(format!("could not open {want:?}: {error}"));
                    } else if !wait_for_navigation_arrival(
                        client,
                        destination,
                        want_here,
                        named_document,
                        want,
                    )
                    .await?
                    {
                        open_error = Some(format!(
                            "could not open {want:?}: destination did not paint within {}ms",
                            check_timeout(900).as_millis()
                        ));
                    }
                }
            }
            // The declared outcome below is the settle condition. Waiting for
            // an unrelated whole-tree node count to stabilize makes every
            // check pay for background updates and can hide transient UI
            // acknowledgements such as "Copied".
        }

        if open_error.is_none()
            && let (Some(field), Some(value)) = (
                check.setup_type_into.as_deref(),
                check.setup_text.as_deref(),
            )
            && let Err(error) = type_text(client, field, value).await
        {
            open_error = Some(format!(
                "could not establish setup value in {field:?}: {error}"
            ));
        }

        /*
         * A check must be independent of whichever disclosure a previous
         * check left closed. The application profile already identifies its
         * collapsible sections for inventory and coverage; use that same
         * app-owned information when the check's action target is not exposed.
         *
         * Only expand when the target is missing. This preserves intentional
         * collapse/expand round trips: an `Expand …` action remains available
         * after the preceding check closed its section and is not pre-empted.
         */
        let setup_target = check
            .hover
            .as_ref()
            .map(qa::Hover::target)
            .or(check.after_prepare_hover.as_ref().map(qa::Hover::target))
            .or(check.reveal_before_capture.as_deref())
            .or(check.prepare.as_deref())
            .or(check.click.as_deref())
            .or(check.type_into.as_deref())
            .or(check.key_on.as_deref())
            .unwrap_or(&check.subject);
        let (current, _) = inspect(client).await?;
        if !painted_named(&current.nodes, setup_target)
            && let Some(surface) = reach::surfaces()
                .iter()
                .find(|surface| reach::on_surface(&current.nodes, surface))
        {
            let opened = expand_everything(client, surface).await?;
            if cli::trace() && opened > 0 {
                println!("        opened {opened} collapsed section(s) for {setup_target:?}");
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }

        let (expanded, _) = inspect(client).await?;
        if open_error.is_none()
            && !painted_named(&expanded.nodes, setup_target)
            && let Some(surface) = reach::surfaces()
                .iter()
                .find(|surface| reach::on_surface(&expanded.nodes, surface))
        {
            match reveal_deferred_content(client, surface, setup_target).await {
                Ok(reveals) => {
                    if cli::trace() && reveals > 0 {
                        println!(
                            "        revealed deferred content for {setup_target:?} in {reveals} step(s)"
                        );
                    }
                }
                Err(error) => {
                    open_error = Some(format!(
                        "could not materialize pagination for {setup_target:?}: {error}"
                    ));
                }
            }
            tokio::time::sleep(Duration::from_millis(25)).await;
        }

        // A deferred surface cannot reveal a node it has not mounted yet.
        // Materialize above, then move the pixel subject into its final
        // viewport position before any baseline capture.
        if open_error.is_none()
            && let Some(reveal) = check.reveal_before_capture.as_deref()
        {
            let arrived = wait_for_arrival(client, None, reveal).await?;
            if !arrived {
                open_error = Some(format!(
                    "could not reveal {reveal:?}: it did not paint within {}ms",
                    check_timeout(900).as_millis()
                ));
            } else if let Err(error) = scroll_hover_target_into_view(client, reveal).await {
                open_error = Some(error);
            } else {
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        }

        let mut nodes_after_first_hover = None;

        // Hover first: the row actions do not exist until `pointerenter`.
        //
        // Aimed at a node inside the panel column, not merely one whose name
        // matches. Another retained surface may render the same control names,
        // so hovering by name alone can land in the wrong list.
        if open_error.is_none()
            && let Some(hover) = check.hover.as_ref()
        {
            let already_hovered = if let Some(unless) = check.hover_unless.as_deref() {
                let (snapshot, _) = inspect(client).await?;
                painted_named(&snapshot.nodes, unless)
            } else {
                false
            };
            if already_hovered {
                // The declared revealed state is already established.
            } else {
                let hovered = if hover.times() > 1 {
                    let first = qa::Hover::Once(hover.target().to_owned());
                    match repeat_hover(client, &first, false).await {
                        Err(error) => Err(error),
                        Ok(()) => {
                            tokio::time::sleep(Duration::from_millis(30)).await;
                            let snapshot = inspect(client).await?.0;
                            nodes_after_first_hover = Some(hover_signature_counts(&snapshot.nodes));
                            match park_pointer(client).await {
                                Err(error) => Err(error),
                                Ok(()) => {
                                    let remaining = qa::Hover::Times(
                                        hover.target().to_owned(),
                                        hover.times() - 1,
                                    );
                                    repeat_hover(client, &remaining, false).await
                                }
                            }
                        }
                    }
                } else {
                    repeat_hover(client, hover, false).await
                };
                if let Err(error) = hovered {
                    open_error = Some(error);
                } else if let Some(next) = check.prepare.as_deref().or(check.click.as_deref()) {
                    if !wait_for_arrival(client, None, next).await? {
                        // A virtualized row can reconcile after ScrollIntoView
                        // and lose the hover that was sent to its prior node.
                        // Reacquire it once; silently continuing turns a setup
                        // race into a misleading "could not click" failure.
                        if let Err(error) = repeat_hover(client, hover, false).await {
                            open_error = Some(error);
                        } else if !wait_for_arrival(client, None, next).await? {
                            open_error = Some(format!(
                                "hovering {:?} did not reveal {next:?}",
                                hover.target()
                            ));
                        }
                    }
                } else {
                    tokio::time::sleep(Duration::from_millis(25)).await;
                }
            }
        }

        // Preparation may itself be a hover-mounted control (for example a
        // row action that opens a dialog). Hover must therefore happen first;
        // the baseline remains after both setup actions so only the declared
        // outcome is measured.
        if open_error.is_none()
            && let Some(want) = check.prepare.as_deref()
        {
            let already_prepared = if let Some(unless) = check.prepare_unless.as_deref() {
                let (snapshot, _) = inspect(client).await?;
                snapshot.nodes.iter().any(|node| {
                    node.visible
                        && selector_matches_node(node, unless)
                        && painted_bounds(node).is_some()
                })
            } else {
                false
            };
            let mut prepared = if already_prepared {
                Ok(())
            } else if let Some(key) = check.prepare_key.as_deref() {
                press_key(client, key, 1, want, true).await.map(|_| ())
            } else if check.prepare_press {
                press_named(client, want).await
            } else {
                click_named_quiet(client, want).await.map(|_| ())
            };
            if prepared.is_err() {
                retries += 1;
                // A retained sibling document may expose the same target name
                // and make the global precheck skip expansion on the selected
                // document. Recover against the check's declared destination,
                // then retry the exact preparation once.
                let declared_surface = check.open.as_deref().and_then(surface_for_opener);
                let live_surface = if declared_surface.is_some() {
                    declared_surface
                } else {
                    let (snapshot, _) = inspect(client).await?;
                    reach::surfaces()
                        .iter()
                        .find(|surface| reach::on_surface(&snapshot.nodes, surface))
                };
                if let Some(surface) = live_surface {
                    let _ = expand_everything(client, surface).await?;
                    let _ = reveal_deferred_content(client, surface, want).await?;
                    prepared = if let Some(key) = check.prepare_key.as_deref() {
                        press_key(client, key, 1, want, true).await.map(|_| ())
                    } else if check.prepare_press {
                        press_named(client, want).await
                    } else {
                        click_named_quiet(client, want).await.map(|_| ())
                    };
                }
            }
            if let Err(error) = prepared {
                /*
                 * Say what *is* addressable, not just what was not found.
                 *
                 * "could not prepare \"Switch\": no visible, enabled, sized
                 * semantic control matching it" is true and nearly useless: it
                 * does not distinguish a broken component from a check naming a
                 * control that never existed. Ten components failed exactly
                 * that way, every one of them a manifest guess rather than a
                 * defect, and each cost a manual measurement to tell apart.
                 *
                 * Listing the named controls that are on screen turns the
                 * common case into a one-line fix: the trigger reads
                 * "Effort: medium", not "Effort".
                 */
                let nearby = match inspect(client).await {
                    Ok((snapshot, _)) => {
                        let mut names: Vec<String> = snapshot
                            .nodes
                            .iter()
                            .filter(|node| {
                                !node.name.is_empty()
                                    && node.visible
                                    && node.bounds.is_some_and(|b| b[2] > 0.0 && b[3] > 0.0)
                            })
                            .map(|node| format!("{}:{}", node.role, node.name))
                            .collect();
                        names.sort();
                        names.dedup();
                        names.truncate(8);
                        if names.is_empty() {
                            String::new()
                        } else {
                            format!("; on screen: {}", names.join(", "))
                        }
                    }
                    Err(_) => String::new(),
                };
                open_error = Some(format!("could not prepare {want:?}: {error}{nearby}"));
            }
            if let Some(next) = check
                .click
                .as_deref()
                .or(check.type_into.as_deref())
                .or(check.key_on.as_deref())
            {
                let _ = wait_for_arrival(client, None, next).await?;
            } else {
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
        }

        // Overlay contents do not exist until their trigger has prepared
        // them. Exercise their pointer-driven incremental resolves now, then
        // leave the pointer away so the final authored hover state is stable.
        if open_error.is_none()
            && let Some(hover) = check.after_prepare_hover.as_ref()
        {
            if check.expect == qa::Expect::PixelsHold {
                let measured = async {
                    park_pointer(client).await?;
                    // A dropdown keeps the last entered item active after the
                    // pointer leaves. Establish that authored state once so
                    // the two frames differ only if later resolves accumulate
                    // renderer paint entries.
                    let establish = qa::Hover::Once(hover.target().to_owned());
                    repeat_hover(client, &establish, true).await?;
                    let before = capture_stable_region(
                        client,
                        &check.subject,
                        declared_outcome_timeout(check),
                    )
                    .await
                    .map_err(|error| format!("before hover: {error}"))?;
                    repeat_hover(client, hover, true).await?;
                    let after = capture_stable_region(
                        client,
                        &check.subject,
                        declared_outcome_timeout(check),
                    )
                    .await
                    .map_err(|error| format!("after hover: {error}"))?;
                    pixels_hold(&before, &after)
                }
                .await;
                pixel_outcome = Some(measured);
            } else if check.expect == qa::Expect::PixelsHoldAfterHover {
                let measured = async {
                    match wait_for_arrival(client, None, hover.target()).await {
                        Ok(true) => {}
                        Ok(false) => {
                            return Err(format!(
                                "could not prepare hover target {:?}: it did not finish painting",
                                hover.target()
                            ));
                        }
                        Err(error) => return Err(error.to_string()),
                    }
                    scroll_hover_target_into_view(client, hover.target()).await?;
                    park_pointer(client).await?;
                    let before = capture_stable_region(
                        client,
                        &check.subject,
                        declared_outcome_timeout(check),
                    )
                    .await
                    .map_err(|error| format!("before hover: {error}"))?;
                    repeat_hover(client, hover, true).await?;
                    let after = capture_stable_region(
                        client,
                        &check.subject,
                        declared_outcome_timeout(check),
                    )
                    .await
                    .map_err(|error| format!("after hover: {error}"))?;
                    let comparison = rgb_pixels_hold(&before, &after);
                    if comparison.is_err()
                        && let Err(error) = save_pixel_artifacts(&check.id, &before, &after)
                    {
                        eprintln!("could not save pixel artifacts for {}: {error}", check.id);
                    }
                    comparison
                }
                .await;
                pixel_outcome = Some(measured);
            } else if check.expect == qa::Expect::PixelsChange {
                let measured = async {
                    // The hover target can be a child on the subject's edge.
                    // Revealing only that child may leave most of the region
                    // outside the viewport, where both captures are clipped to
                    // identical black pixels. Place the persistent comparison
                    // subject first; its descendant is then already visible.
                    reveal_capture_region(client, &check.subject).await?;
                    let node_id = scroll_hover_target_into_view(client, hover.target()).await?;
                    park_pointer(client).await?;
                    let before = capture_region(client, &check.subject).await?;
                    let event_driven = client
                        .arm_paint_events()
                        .await
                        .map_err(|error| error.to_string())?;
                    let require_events = cli::require_paint_events();
                    if require_events && !event_driven {
                        return Err("the inspector does not provide paint events".to_owned());
                    }
                    client
                        .agent(&AgentControlRequest::Act(AgentAction::Hover { node_id }))
                        .await
                        .map_err(|error| error.to_string())?;

                    let paint_committed = if event_driven {
                        client
                            .wait_for_paint(declared_outcome_timeout(check))
                            .await
                            .map_err(|error| error.to_string())?
                    } else {
                        false
                    };
                    if require_events && !paint_committed {
                        return Err("no paint event arrived after hover".to_owned());
                    }

                    if paint_committed {
                        let after = capture_region(client, &check.subject).await?;
                        let comparison = pixels_change(&before, &after);
                        if comparison.is_err()
                            && let Err(error) = save_pixel_artifacts(&check.id, &before, &after)
                        {
                            eprintln!("could not save pixel artifacts for {}: {error}", check.id);
                        }
                        comparison
                    } else {
                        // Compatibility with runtimes and headless hosts that
                        // predate paint notifications. Bounded to 100 ms and
                        // removed once the fleet has adopted the stream.
                        wait_for_pixels_change(
                            client,
                            &check.subject,
                            &before,
                            declared_outcome_timeout(check),
                        )
                        .await
                    }
                }
                .await;
                pixel_outcome = Some(measured);
            } else if let Err(error) = repeat_hover(client, hover, true).await {
                open_error = Some(error);
            }
        }

        /*
         * Nothing accumulated across explicitly repeated hover cycles.
         *
         * Entering a control can legitimately mount something, so compare the
         * first completed hover with the final completed hover. Both snapshots
         * have the same authored pointer state. A single-hover check has no
         * second state to compare and must not treat unrelated asynchronous
         * rendering as a leak.
         *
         * Checks request repetition explicitly because it is deliberate abuse,
         * but the accumulation assertion comes with that request automatically.
         */
        if let Some(after_first) = nodes_after_first_hover
            && open_error.is_none()
        {
            let snapshot = inspect(client).await?.0;
            let after_repeats = hover_signature_counts(&snapshot.nodes);
            let retained = accumulated_hover_signatures(&after_first, &after_repeats);
            if !retained.is_empty() {
                let details = retained
                    .iter()
                    .take(3)
                    .map(|((role, name, slot, dom_id), extra)| {
                        format!("{role}:{name:?} slot={slot:?} id={dom_id:?} +{extra}")
                    })
                    .collect::<Vec<_>>()
                    .join(", ");
                open_error = Some(format!(
                    "repeated hover retained extra copies of existing semantic nodes: {details}"
                ));
            }
        }

        // Action-driven pixel assertions compare a persistent subject while
        // clicking some other control. Put that subject fully in the viewport
        // before the baseline: a minimally visible trigger can otherwise
        // expose only the clipped edge of its text, making two different
        // labels produce the same captured pixels.
        if open_error.is_none()
            && check.expect == qa::Expect::PixelsChange
            && check.after_prepare_hover.is_none()
            && let Err(error) = scroll_hover_target_into_view(client, &check.subject).await
        {
            open_error = Some(format!("could not reveal pixel subject: {error}"));
        }

        // Resolve and reveal the ordinary click target before the baseline and
        // before the outcome clock. Semantic lookup and ScrollIntoView are
        // harness preparation, not time the application takes to respond to a
        // click; counting them made latency proportional to tree size and to a
        // fixed scroll-settle delay.
        let mut prepared_click = None;
        if open_error.is_none()
            && !check.press
            && let Some(want) = check.click.as_deref()
        {
            match locate_control(client, want, &[]).await {
                Ok((node_id, _)) => prepared_click = Some(node_id),
                Err(error) => {
                    open_error = Some(format!("could not locate {want:?}: {error}"));
                }
            }
        }

        // Hover can mount the action that the check will drive. Capture the
        // baseline afterward: inspecting before hover both omitted that real
        // pre-action state and paid for an immediately discarded snapshot.
        let (before, _) = inspect(client).await?;

        if open_error.is_none() && check.expect == qa::Expect::OpaqueBackground {
            pixel_outcome = Some(opaque_background(client, &check.subject).await);
        } else if open_error.is_none() && check.expect == qa::Expect::TransparentBackground {
            pixel_outcome = Some(transparent_background(client, &check.subject).await);
        } else if open_error.is_none() && check.expect == qa::Expect::FullOpacity {
            pixel_outcome = Some(full_opacity(client, &check.subject).await);
        } else if open_error.is_none() && check.expect == qa::Expect::TransparentWindowTint {
            pixel_outcome = Some(transparent_window_tint(client).await);
        } else if open_error.is_none() && check.expect == qa::Expect::VisibleInk {
            pixel_outcome = Some(visible_ink(client, &check.subject).await);
        } else if open_error.is_none() && check.expect == qa::Expect::InteriorInk {
            pixel_outcome = Some(interior_ink(client, &check.subject).await);
        } else if open_error.is_none() && check.expect == qa::Expect::Contrast {
            pixel_outcome = Some(
                paint_audit::contrast(client, &check.subject, 4.5, 3.0)
                    .await
                    .map_err(|error| error.to_string()),
            );
        }

        let before_font_size = if open_error.is_none() && check.expect == qa::Expect::FontSizeGrows
        {
            match font_size(client, &check.subject).await {
                Ok(size) => Some(size),
                Err(error) => {
                    pixel_outcome = Some(Err(error));
                    None
                }
            }
        } else {
            None
        };

        let before_action_pixels = if open_error.is_none()
            && check.expect == qa::Expect::PixelsChange
            && check.after_prepare_hover.is_none()
        {
            Some(match capture_node_id(&before.nodes, &check.subject) {
                Ok(node_id) => capture_node_region(client, node_id, &check.subject)
                    .await
                    .map(|image| (node_id, image)),
                Err(error) => Err(error),
            })
        } else {
            None
        };

        /*
         * The tree is mostly nodes somebody can see.
         *
         * Every other assertion here names one control and asks about it, so a
         * document can fill with abandoned subtrees while every check passes:
         * the control they name is still present and still correct, and the
         * dead nodes are 0x0 and hidden, so they do not even perturb the
         * measurement. Measured on a real instance after a few hours of use,
         * 96,263 nodes where a fresh one holds 635, and 91% of them zero-box.
         * Every check passed throughout, and `ps-qa ghost`, which exists for
         * exactly this, could not finish because the tree had grown past what
         * the inspector would serve.
         *
         * So the question has to be asked for free, on every check, rather
         * than written into one somebody thinks to add. A view legitimately
         * holds hidden nodes - a closed menu, a collapsed row - so this is a
         * ratio and an absolute floor. A deliberately filtered settings
         * catalog can hold a few thousand valid zero-box descendants after a
         * full inventory; the leak this protects against grows into tens of
         * thousands. Past 5,000 dead nodes and five dead for every live one,
         * something is being retained rather than reused.
         */
        {
            let dead = before
                .nodes
                .iter()
                .filter(|node| !node.bounds.is_some_and(|b| b[2] > 0.0 && b[3] > 0.0))
                .count();
            let live = before.nodes.len().saturating_sub(dead);
            const MIN_SUSPICIOUS_DEAD_NODES: usize = 5_000;
            const MAX_DEAD_TO_LIVE_RATIO: usize = 5;
            if live > 0
                && dead > MIN_SUSPICIOUS_DEAD_NODES
                && dead > live.saturating_mul(MAX_DEAD_TO_LIVE_RATIO)
            {
                open_error = Some(format!(
                    "the document holds {dead} node(s) with no box against {live} with one, \
                     out of {}; something is retaining subtrees rather than reusing them",
                    before.nodes.len()
                ));
            }
        }
        let mut check_started = (check.click.is_none()
            && check.text.is_none()
            && check.key.is_none()
            && check.scroll_over.is_none())
        .then(Instant::now);

        let live_paint_expect = matches!(
            check.expect,
            qa::Expect::PixelsHold
                | qa::Expect::PixelsHoldAfterHover
                | qa::Expect::PixelsChange
                | qa::Expect::VisibleInk
                | qa::Expect::InteriorInk
                | qa::Expect::OpaqueBackground
                | qa::Expect::TransparentBackground
                | qa::Expect::FullOpacity
                | qa::Expect::TransparentWindowTint
                | qa::Expect::Contrast
                | qa::Expect::FontSizeGrows
        );
        let drives_action = check.click.is_some()
            || check.text.is_some()
            || check.key.is_some()
            || check.scroll_over.is_some();
        let action_paint_armed = if drives_action && !live_paint_expect {
            client.arm_paint_events().await.unwrap_or(false)
        } else {
            false
        };

        // Then the action, if this check is about one. A click that cannot be
        // dispatched is itself a failure, not a skip.
        client.set_request_timeout(check_timeout(check.outcome_timeout_ms.max(900)));
        let mut action_error = open_error;
        let mut action_target = None;
        let mut action_node_id = None;
        if action_error.is_none()
            && let Some(want) = check.click.as_deref()
        {
            if check.text.is_none() && check.key.is_none() {
                check_started = Some(Instant::now());
            }
            if check.expect == qa::Expect::TargetPaints && !check.press {
                let (tree, _) = inspect(client).await?;
                action_target = resolved_action_target(&tree.nodes, want);
            }
            let driven = drive_check_action(client, want, check.press, prepared_click).await;
            action_error = driven.as_ref().err().cloned();
            action_node_id = driven.ok().flatten();
            // The exact declared outcome below polls the renderer. A generic
            // whole-tree settle here both duplicates that work and waits on
            // unrelated background updates.
        }

        if action_error.is_none()
            && let Some(text) = check.text.as_deref()
        {
            if check.key.is_none() {
                check_started = Some(Instant::now());
            }
            if let Some(field) = check.type_into.as_deref() {
                match type_text(client, field, text).await {
                    Ok(node_id) => action_node_id = Some(node_id),
                    Err(error) => {
                        action_error = Some(format!("could not type into {field:?}: {error}"));
                    }
                }
            } else {
                action_error = Some("text requires type_into".to_owned());
            }
        }
        if action_error.is_none()
            && let Some(key) = check.key.as_deref()
        {
            check_started = Some(Instant::now());
            let target = check
                .key_on
                .as_deref()
                .or(check.type_into.as_deref())
                .unwrap_or("");
            if let Err(error) = press_key(client, key, 1, target, check.key_on.is_some()).await {
                action_error = Some(format!("could not send {key:?}: {error}"));
            }
        }
        if action_error.is_none()
            && let Some(target) = check.scroll_over.as_deref()
        {
            check_started = Some(Instant::now());
            match hover_over(client, target).await {
                Ok(true) => {
                    if let Err(error) =
                        scroll_events(client, check.scroll_ticks, check.scroll_delta).await
                    {
                        action_error = Some(format!("could not scroll over {target:?}: {error}"));
                    }
                }
                Ok(false) => action_error = Some(format!("no painted node matching {target:?}")),
                Err(error) => {
                    action_error = Some(format!("could not aim at {target:?}: {error}"));
                }
            }
        }
        if action_error.is_none() && action_paint_armed {
            // A real committed frame is the cheapest happens-after boundary.
            // Some valid actions change no pixels, so absence is a bounded
            // compatibility fallback rather than a verdict by itself.
            let _ = client.wait_for_paint(declared_outcome_timeout(check)).await;
        }
        let transport_timed_out = action_error
            .as_deref()
            .is_some_and(|error| error.contains("inspector did not answer within"));
        if pixel_outcome.is_none()
            && let Some(before_pixels) = before_action_pixels
        {
            pixel_outcome = Some(match before_pixels {
                Ok((node_id, before_pixels)) => {
                    match capture_node_region(client, node_id, &check.subject).await {
                        Ok(after_pixels) => pixels_change(&before_pixels, &after_pixels),
                        Err(error) => Err(error),
                    }
                }
                Err(error) => Err(error),
            });
        }
        if pixel_outcome.is_none()
            && let Some((node_id, before_size)) = before_font_size
        {
            pixel_outcome = Some(
                wait_for_larger_font(
                    client,
                    node_id,
                    &check.subject,
                    before_size,
                    check_timeout(if check.outcome_timeout_ms == 0 {
                        900
                    } else {
                        check.outcome_timeout_ms
                    }),
                )
                .await,
            );
        }

        let fallback_after = || AgentSnapshot {
            nodes: before.nodes.clone(),
            ..AgentSnapshot::default()
        };
        let (after, settle_error, settle_iterations) = if live_paint_expect {
            match inspect(client).await {
                Ok((snapshot, _)) => (snapshot, None, 0),
                Err(error) => (
                    fallback_after(),
                    Some(format!("could not inspect after the action: {error}")),
                    0,
                ),
            }
        } else if action_error.is_none() || transport_timed_out {
            match settle_for_outcome(
                client,
                check,
                &before.nodes,
                action_target.as_deref(),
                action_node_id,
            )
            .await
            {
                Ok(settled) => settled,
                Err(error) => (
                    fallback_after(),
                    Some(format!("could not inspect the rendered outcome: {error}")),
                    0,
                ),
            }
        } else {
            match inspect(client).await {
                Ok((snapshot, _)) => (snapshot, None, 0),
                Err(error) => (
                    fallback_after(),
                    Some(format!(
                        "could not inspect after the failed action: {error}"
                    )),
                    0,
                ),
            }
        };
        let mut outcome = if live_paint_expect {
            match action_error {
                Some(error) => Err(error),
                None => pixel_outcome.unwrap_or_else(|| {
                    Err("the live paint expectation was not measured".to_owned())
                }),
            }
        } else {
            match action_error {
                Some(error) if transport_timed_out => outcome_verdict(
                    check,
                    &before.nodes,
                    &after.nodes,
                    action_target.as_deref(),
                    action_node_id,
                )
                .map_err(|outcome| format!("{error}; rendered outcome also failed: {outcome}")),
                Some(error) => Err(error),
                None => outcome_verdict(
                    check,
                    &before.nodes,
                    &after.nodes,
                    action_target.as_deref(),
                    action_node_id,
                ),
            }
        };
        if let Some(error) = settle_error {
            outcome = Err(match outcome {
                Ok(()) => error,
                Err(existing) => format!("{existing}; {error}"),
            });
        }
        // Preparation is not the outcome latency. Opening an editor, hovering
        // its row, and filling a field establish the precondition; the final
        // click, value commit, or key is the user action whose rendered result
        // must arrive inside the verdict budget. An overloaded runner can opt
        // into a visible multiplier; the default remains the strict contract.
        let elapsed = check_started.unwrap_or_else(Instant::now).elapsed();
        let declared_outcome = if check.outcome_timeout_ms == 0 {
            900
        } else {
            check.outcome_timeout_ms
        };
        let verdict_budget = check_timeout(1_250.max(declared_outcome.saturating_add(250)));
        if elapsed > verdict_budget {
            let timing = format!(
                "check exceeded {}ms ({:.0}ms)",
                verdict_budget.as_millis(),
                elapsed.as_secs_f64() * 1000.0
            );
            outcome = Err(match outcome {
                Ok(()) => timing,
                Err(error) => format!("{error}; {timing}"),
            });
        }
        if cli::trace() {
            match &outcome {
                Ok(()) => println!(
                    "        verdict pass: {} ({:.0}ms)",
                    check.id,
                    elapsed.as_secs_f64() * 1000.0
                ),
                Err(error) => println!(
                    "        verdict fail: {} ({:.0}ms): {error}",
                    check.id,
                    elapsed.as_secs_f64() * 1000.0
                ),
            }
        }
        results.push(CheckResult {
            check,
            outcome,
            duration_ms: full_check_started.elapsed().as_millis() as u64,
            settle_iterations,
            retries,
        });
        if check.settle_after_ms > 0 {
            tokio::time::sleep(Duration::from_millis(check.settle_after_ms)).await;
        }
    }

    let failed = results
        .iter()
        .filter(|result| result.outcome.is_err())
        .count();
    let tally_input: Vec<_> = results
        .iter()
        .map(|result| (result.check, result.outcome.clone()))
        .collect();
    let tally = qa::tally(&tally_input);
    let mut groups: Vec<_> = tally.iter().collect();
    groups.sort_by_key(|(name, _)| *name);

    /*
     * TOON, for a caller that is a program - usually a language model.
     *
     * The column format below is for a person: reading it back means splitting
     * on whitespace, which loses any field containing a space. `what` always
     * contains one and a failure message nearly always does. That mis-parse is
     * not hypothetical - it is how a node at `[0,58 0x0]` got read as painting.
     *
     * TOON rather than JSON because a uniform array declares its length and
     * field names once, then spends one line per row instead of repeating every
     * key in every object. For a run of two dozen checks that is a large
     * fraction of the tokens, and the declared `[n]` lets the reader verify it
     * received every row rather than a truncated list.
     *
     * Nesting is why this is not flat TSV: reporting wants a check to carry its
     * own detail, and TOON keeps that expressible without giving up the tabular
     * economy.
     *
     * Encoded by `toon-format` rather than by hand. Quoting is the whole
     * problem here - a check description and a failure message both routinely
     * contain the delimiter ("Edit " went 19 -> 21, expected no change) - and a
     * hand-written emitter is a guess at the specification that drifts from it
     * silently. The crate is generic over `serde::Serialize`, so anything with
     * a `Serialize` impl encodes without a bespoke path.
     */

    let report = Report {
        passed: results.len() - failed,
        failed,
        groups: groups
            .into_iter()
            .map(|(name, (passed, total))| GroupRow {
                name: name.to_string(),
                passed: *passed,
                total: *total,
            })
            .collect(),
        checks: results.iter().map(CheckRow::from).collect(),
    };
    println!(
        "{}",
        toon_format::encode_default(&report).map_err(|e| eyre!(e.to_string()))?
    );
    Ok(failed)
}

fn outcome_verdict(
    check: &qa::Check,
    before: &[SemanticNode],
    after: &[SemanticNode],
    action_target: Option<&str>,
    action_node_id: Option<u64>,
) -> std::result::Result<(), String> {
    if check.expect == qa::Expect::TargetPaints {
        let Some(subject) = action_target else {
            return Err("could not resolve the exact click target".to_owned());
        };
        let mut targeted = check.clone();
        targeted.subject = subject.to_owned();
        targeted.expect = qa::Expect::Paints;
        qa::verdict(&targeted, before, after)
    } else if check.expect == qa::Expect::ValueChanges
        && action_target.is_some_and(|target| target == check.subject)
        && let Some(node_id) = action_node_id
    {
        qa::value_changed(node_id, before, after)
    } else if check.expect == qa::Expect::SelectionChanges
        && action_target.is_some_and(|target| target == check.subject)
        && let Some(node_id) = action_node_id
    {
        qa::selection_changed(node_id, before, after)
    } else {
        qa::verdict(check, before, after)
    }
}

#[derive(Default)]
struct OutcomeStability {
    fingerprint: Option<u64>,
    since: Option<tokio::time::Instant>,
}

impl OutcomeStability {
    fn observe(
        &mut self,
        now: tokio::time::Instant,
        fingerprint: u64,
        passing: bool,
        required: Duration,
    ) -> bool {
        if !passing {
            self.fingerprint = None;
            self.since = None;
            return false;
        }
        if required.is_zero() {
            return true;
        }
        if self.fingerprint != Some(fingerprint) {
            self.fingerprint = Some(fingerprint);
            self.since = Some(now);
            return false;
        }
        self.since
            .is_some_and(|since| now.duration_since(since) >= required)
    }

    fn remaining(&self, now: tokio::time::Instant, required: Duration) -> Duration {
        self.since
            .map(|since| required.saturating_sub(now.saturating_duration_since(since)))
            .unwrap_or_default()
    }
}

fn semantic_fingerprint(nodes: &[SemanticNode]) -> u64 {
    let mut fingerprint = DefaultHasher::new();
    nodes.len().hash(&mut fingerprint);
    for node in nodes {
        node.dom_id.hash(&mut fingerprint);
        node.id.hash(&mut fingerprint);
        node.parent.hash(&mut fingerprint);
        node.role.hash(&mut fingerprint);
        node.name.hash(&mut fingerprint);
        node.value.hash(&mut fingerprint);
        node.enabled.hash(&mut fingerprint);
        node.visible.hash(&mut fingerprint);
        node.selected.hash(&mut fingerprint);
        node.bounds
            .map(|bounds| bounds.map(f64::to_bits))
            .hash(&mut fingerprint);
        node.slot.hash(&mut fingerprint);
    }
    fingerprint.finish()
}

struct OutcomePollScope {
    root: u64,
    baseline_ids: HashSet<u64>,
}

/// The active application surface is the largest honest outcome boundary.
///
/// Polling from the document root serialized every retained pane and permanent
/// chrome node every 25ms. The surface helper already identifies the pane by
/// ancestry for inventory; reuse that exact ownership boundary here.
fn outcome_poll_scope(nodes: &[SemanticNode]) -> Option<OutcomePollScope> {
    let surface = reach::surfaces()
        .iter()
        .find(|surface| reach::on_surface(nodes, surface))?;
    let ids = reach::on_surface_subtree(nodes, surface);
    let root = *ids.first()?;
    // A markerless surface returns the whole document and buys nothing.
    (ids.len() < nodes.len()).then(|| OutcomePollScope {
        root,
        baseline_ids: ids.into_iter().collect(),
    })
}

/// Adopt a newly activated surface after a full-document outcome probe.
///
/// Navigation legitimately moves the declared subject out of the old pane.
/// Once it appears in the new active pane, continuing to fingerprint the full
/// document makes unrelated background updates reset its stability window.
/// A subject that exists only outside the active pane is portal-owned, so that
/// outcome deliberately retains document scope.
fn scope_for_passing_snapshot(nodes: &[SemanticNode], subject: &str) -> Option<OutcomePollScope> {
    let candidate = outcome_poll_scope(nodes)?;
    subject_belongs_to_scope(nodes, subject, &candidate.baseline_ids).then_some(candidate)
}

fn subject_belongs_to_scope(
    nodes: &[SemanticNode],
    subject: &str,
    scope_ids: &HashSet<u64>,
) -> bool {
    let mut subject_seen = false;
    let mut subject_in_surface = false;
    for node in nodes
        .iter()
        .filter(|node| selector_matches_node(node, subject))
    {
        subject_seen = true;
        subject_in_surface |= scope_ids.contains(&node.id);
    }
    subject_seen && subject_in_surface
}

/// Reconstruct a complete comparison snapshot from one freshly inspected pane.
///
/// Count/family verdicts must still see nodes outside the pane. They are
/// unchanged during this action, so retain them from the baseline and replace
/// only the scoped descendants with the live result.
fn merge_outcome_snapshot(
    before: &[SemanticNode],
    mut scoped: AgentSnapshot,
    baseline_ids: &HashSet<u64>,
) -> AgentSnapshot {
    let mut nodes: Vec<_> = before
        .iter()
        .filter(|node| !baseline_ids.contains(&node.id))
        .cloned()
        .collect();
    nodes.append(&mut scoped.nodes);
    scoped.nodes = nodes;
    scoped
}

/// Wait for the declared result, not merely for a tree that already contains
/// the subject.
///
/// A refresh indicator exists both before and after its button is activated.
/// Waiting for that node to paint therefore returned immediately, even when
/// its backend read was still running. QA is an interactive contract: a result
/// that cannot paint inside one second is reported as slow rather than making
/// every later check wait behind it.
async fn settle_for_outcome(
    client: &mut Client,
    check: &qa::Check,
    before: &[SemanticNode],
    action_target: Option<&str>,
    action_node_id: Option<u64>,
) -> Result<(AgentSnapshot, Option<String>, u32)> {
    let outcome_timeout = declared_outcome_timeout(check);
    let deadline = tokio::time::Instant::now() + outcome_timeout;
    let stable_for = Duration::from_millis(check.stable_for_ms);
    let mut stability = OutcomeStability::default();
    let mut iterations = 0;
    let mut scope = outcome_poll_scope(before);
    let mut probed_full_document = false;
    let event_driven = client.arm_paint_events().await.unwrap_or(false);
    loop {
        let mut after = if let Some(scoped) = scope.as_ref() {
            match inspect_subtree(client, scoped.root).await {
                Ok((snapshot, _)) => merge_outcome_snapshot(before, snapshot, &scoped.baseline_ids),
                // Reconciliation can replace the pane root. Reacquire from one
                // full snapshot instead of treating a stale id as failure.
                Err(_) => {
                    let full = inspect(client).await?.0;
                    scope = outcome_poll_scope(&full.nodes);
                    full
                }
            }
        } else {
            inspect(client).await?.0
        };
        iterations += 1;
        let now = tokio::time::Instant::now();
        let mut passing =
            outcome_verdict(check, before, &after.nodes, action_target, action_node_id).is_ok();
        if !passing && scope.is_some() && !probed_full_document {
            // Portalled dialogs and global toasts may live outside the active
            // pane. Probe the full document once when the scoped verdict says
            // the result is absent; subsequent stability samples remain
            // scoped if the outcome belongs to the pane after all.
            after = inspect(client).await?.0;
            probed_full_document = true;
            passing =
                outcome_verdict(check, before, &after.nodes, action_target, action_node_id).is_ok();
            scope = if passing {
                // Navigation can replace the active pane. Adopt that new
                // subtree when it owns the declared subject; a portal-owned
                // dialog or toast stays on document scope.
                scope_for_passing_snapshot(&after.nodes, &check.subject)
            } else {
                outcome_poll_scope(&after.nodes)
            };
        }
        if stability.observe(now, semantic_fingerprint(&after.nodes), passing, stable_for) {
            return Ok((after, None, iterations));
        }
        if now >= deadline {
            let error = (passing && !stable_for.is_zero()).then(|| {
                format!(
                    "rendered outcome did not remain complete and unchanged for {}ms within {}ms",
                    stable_for.as_millis(),
                    outcome_timeout.as_millis()
                )
            });
            return Ok((after, error, iterations));
        }
        if event_driven {
            // A rendered outcome cannot change without a committed frame.
            // Wait on the runtime's event stream instead of serialising even
            // a scoped tree every 25ms. When the verdict is already passing,
            // wake at the end of its stability window even if no new frame is
            // committed; an unchanged tree is exactly what that window asks
            // us to prove. Older runtimes retain the bounded polling fallback.
            let until_deadline = deadline.saturating_duration_since(now);
            let wait = if passing {
                stability.remaining(now, stable_for).min(until_deadline)
            } else {
                until_deadline
            };
            if !wait.is_zero() {
                let _ = client.wait_for_paint(wait).await?;
            }
        } else {
            tokio::time::sleep(Duration::from_millis(25)).await;
        }
    }
}

/// The one deadline a check declared for its rendered result.
///
/// Capture settling, semantic settling and transport waits must all derive
/// from this value. Independent literals let one layer give up while another
/// still claims the outcome has time remaining.
fn declared_outcome_timeout(check: &qa::Check) -> Duration {
    check_timeout(if check.outcome_timeout_ms == 0 {
        900
    } else {
        check.outcome_timeout_ms
    })
}

/// Resolve an application-owned surface opener.
///
/// Dynamic document names and ordinary controls are not interchangeable, so
/// document names are explicit profile data rather than guessed from an
/// arbitrary unknown label.
fn surface_for_opener(want: &str) -> Option<&'static reach::Surface> {
    reach::surfaces()
        .iter()
        .find(|surface| surface.opener == want)
        .or_else(|| {
            reach::profile()
                .document_openers
                .iter()
                .any(|opener| opener.eq_ignore_ascii_case(want))
                .then(|| {
                    reach::surfaces()
                        .iter()
                        .find(|surface| surface.opener == reach::DYNAMIC_DOCUMENT)
                })
                .flatten()
        })
}

/// Whether an opener names one document among several instances of a surface.
///
/// A surface marker distinguishes Settings from Home, but cannot distinguish
/// one project from another. The application's profile owns the stable fixture
/// names, so it also owns this classification.
fn is_named_document_opener(want: &str) -> bool {
    named_document_opener_for(reach::profile(), want)
}

fn named_document_opener_for(profile: &crate::app::AppProfile, want: &str) -> bool {
    profile
        .document_openers
        .iter()
        .any(|opener| opener.eq_ignore_ascii_case(want))
}

fn arrived_without_navigation(
    nodes: &[SemanticNode],
    destination: Option<&reach::Surface>,
    want_here: &str,
    named_document: bool,
    active_document_matches: bool,
) -> bool {
    if named_document {
        active_document_matches
            && destination.is_some_and(|surface| reach::on_surface(nodes, surface))
    } else {
        destination.map_or_else(
            || painted_named(nodes, want_here),
            |surface| reach::on_surface(nodes, surface),
        )
    }
}

/// Whether the exact named document is the live selected tab.
///
/// Every project surface paints the same generic marker, so only the tab can
/// distinguish which one owns it. Agency exposes `aria-current="page"`; Blitz
/// maps that live state to `selected` rather than asking the runner to remember
/// which arbitrary action may have changed documents.
fn named_document_is_active(nodes: &[SemanticNode], want: &str) -> bool {
    named_document_is_active_with_permanent(nodes, want, &reach::profile().permanent_surfaces)
}

fn named_document_is_active_with_permanent(
    nodes: &[SemanticNode],
    want: &str,
    permanent_surfaces: &[String],
) -> bool {
    let tab_name = format!("{want}{want}");
    let exact_document_selected = nodes.iter().any(|node| {
        node.role == "button"
            && node.name.eq_ignore_ascii_case(&tab_name)
            && node.selected
            && node.visible
            && painted_bounds(node).is_some()
    });
    let permanent_surface_selected = nodes.iter().any(|node| {
        node.role == "button"
            && node.selected
            && node.visible
            && painted_bounds(node).is_some()
            && permanent_surfaces.iter().any(|surface| {
                node.name.eq_ignore_ascii_case(surface)
                    || node
                        .name
                        .eq_ignore_ascii_case(&format!("{surface}{surface}"))
            })
    });
    exact_document_selected && !permanent_surface_selected
}

/// Activate a surface opener without confusing a document tab for its Close
/// button.
///
/// A tab's accessible name is the document label doubled. Prefer that exact
/// role-qualified selector, then fall back to the ordinary opener so a profile
/// with no open tab can still use its Home row.
async fn click_opener_quiet(client: &mut Client, want: &str, named_document: bool) -> Result<u64> {
    if named_document {
        let tab = format!("button:{want}{want}");
        if let Ok(node_id) = click_named_quiet(client, &tab).await {
            return Ok(node_id);
        }
    }
    click_named_quiet(client, want).await
}

async fn click_by_id(client: &mut Client, node_id: u64) -> Result<()> {
    client
        .agent(&AgentControlRequest::Act(AgentAction::Click { node_id }))
        .await?;
    Ok(())
}

/// A finished run, as a machine reads it.
///
/// Serialized rather than printed field by field: `toon-format` is generic over
/// `serde::Serialize`, so the shape below *is* the output format, and there is
/// no second hand-written description of it to drift.
#[derive(serde::Serialize)]
struct Report {
    passed: usize,
    failed: usize,
    groups: Vec<GroupRow>,
    checks: Vec<CheckRow>,
}

struct CheckResult<'a> {
    check: &'a qa::Check,
    outcome: std::result::Result<(), String>,
    /// End-to-end check time, including setup and teardown around the measured
    /// interaction. The verdict's stricter action budget is enforced
    /// separately; this is artifact cost.
    duration_ms: u64,
    /// Semantic snapshots taken while waiting for the declared outcome.
    settle_iterations: u32,
    /// Explicitly repeated actions after a failed first attempt.
    retries: u32,
}

#[derive(serde::Serialize)]
struct GroupRow {
    name: String,
    passed: usize,
    total: usize,
}

/// One check's outcome. Uniform, so TOON emits it as a table: the field names
/// are declared once and each check costs a single line.
#[derive(serde::Serialize)]
struct CheckRow {
    verdict: &'static str,
    group: String,
    id: String,
    duration_ms: u64,
    settle_iterations: u32,
    retries: u32,
    error: String,
    what: String,
}

impl From<&CheckResult<'_>> for CheckRow {
    fn from(result: &CheckResult<'_>) -> Self {
        Self {
            verdict: if result.outcome.is_ok() {
                "pass"
            } else {
                "fail"
            },
            group: result.check.group.clone(),
            id: result.check.id.clone(),
            duration_ms: result.duration_ms,
            settle_iterations: result.settle_iterations,
            retries: result.retries,
            error: result.outcome.clone().err().unwrap_or_default(),
            what: result.check.what.clone(),
        }
    }
}

/// One control, as `find` reports it.
#[derive(serde::Serialize)]
struct FoundRow {
    id: u64,
    role: String,
    name: String,
    x: f64,
    y: f64,
    w: f64,
    h: f64,
    /// `visible`, `hidden`, `disabled`, `0x0`, `offscreen`, comma-joined. The
    /// question behind most lookups is "why can nobody press this", and the
    /// answer is a combination of those rather than any one of them.
    state: String,
}

/// Every control matching a role, a name pattern and a state.
///
/// Replaces the `layout | awk` pipeline that every non-trivial question used to
/// need. The filters are the ones that were actually reassembled by hand, over
/// and over: which buttons are off screen, what is painting at 0x0, what does
/// this surface contain.
#[expect(
    clippy::too_many_arguments,
    reason = "each one is a filter the caller asks for by name"
)]
async fn find(
    client: &mut Client,
    pattern: &str,
    roles: &[String],
    visible: bool,
    hidden: bool,
    painted: bool,
    offscreen_only: bool,
    disabled: bool,
    count_only: bool,
    limit: Option<usize>,
) -> Result<()> {
    let (snapshot, elapsed) = inspect(client).await?;
    let viewport = viewport_of(&snapshot);

    let rows: Vec<FoundRow> = snapshot
        .nodes
        .iter()
        .filter(|node| {
            roles.is_empty()
                || roles
                    .iter()
                    .any(|role| role.eq_ignore_ascii_case(&node.role))
        })
        // `@slot` addresses the part the library named rather than the text it
        // carries, so a trigger and the thing it opens are distinguishable even
        // though they share an accessible name.
        .filter(|node| match pattern.strip_prefix('@') {
            Some(slot) => node.slot.as_deref().is_some_and(|have| have == slot),
            None => name_matches(&node.name, pattern),
        })
        .filter(|node| !visible || node.visible)
        .filter(|node| !hidden || !node.visible)
        .filter(|node| !disabled || !node.enabled)
        .filter(|node| {
            !painted
                || node
                    .bounds
                    .is_some_and(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
        })
        .filter(|node| {
            !offscreen_only
                || node
                    .bounds
                    .is_some_and(|bounds| offscreen(bounds, viewport))
        })
        .map(|node| {
            let bounds = node.bounds.unwrap_or([0.0; 4]);
            let mut state: Vec<&str> = Vec::new();
            state.push(if node.visible { "visible" } else { "hidden" });
            if !node.enabled {
                state.push("disabled");
            }
            if node.selected {
                state.push("selected");
            }
            if bounds[2] <= 0.0 || bounds[3] <= 0.0 {
                state.push("0x0");
            } else if offscreen(bounds, viewport) {
                state.push("offscreen");
            }
            // Rounded to a tenth. Layout arrives as f64 and prints as
            // `20.8799991607666`, which is six times the tokens of `20.9` and
            // tells the reader nothing a control's geometry depends on.
            let round = |value: f64| (value * 10.0).round() / 10.0;
            FoundRow {
                id: node.id,
                role: node.role.clone(),
                name: node.name.clone(),
                x: round(bounds[0]),
                y: round(bounds[1]),
                w: round(bounds[2]),
                h: round(bounds[3]),
                state: state.join(","),
            }
        })
        .collect();

    let matched = rows.len();
    let shown: Vec<FoundRow> = match limit {
        Some(limit) => rows.into_iter().take(limit).collect(),
        None => rows,
    };

    #[derive(serde::Serialize)]
    struct Found {
        matched: usize,
        of: usize,
        inspect_ms: f64,
        controls: Vec<FoundRow>,
    }

    let report = Found {
        matched,
        of: snapshot.nodes.len(),
        inspect_ms: (elapsed * 10.0).round() / 10.0,
        controls: if count_only { Vec::new() } else { shown },
    };
    println!(
        "{}",
        toon_format::encode_default(&report).map_err(|error| eyre!(error.to_string()))?
    );
    Ok(())
}

/// Glob-style name matching.
///
/// `chat*` for a prefix, `*close*` for anywhere, `*` for everything. A pattern
/// with no `*` is a substring, because that is how a control is remembered:
/// asking for `Rename` should find `Rename project` without ceremony.
async fn locate_button(client: &mut Client, want: &str) -> Result<(u64, [f64; 4])> {
    locate_control(client, want, &["button"]).await
}

/// Double click the first visible match, for reaching a surface.
///
/// A document row may fold on a single click and open on a double; two separate
/// `press` calls are not a double click: each round-trips through the
/// inspector, so they land hundreds of milliseconds apart and the row folds
/// there and back. Navigation that used single presses appeared to work only
/// when the surface happened to be open already, which is why checks failed
/// with "no visible, enabled, sized button" for controls one gesture away.
async fn open_named(client: &mut Client, want: &str) -> Result<()> {
    let (id, _) = locate_button(client, want).await?;
    if cli::trace() {
        println!("        opening {want:?} (id {id})");
    }
    client
        .agent(&AgentControlRequest::Act(AgentAction::DoubleClick {
            node_id: id,
        }))
        .await?;
    Ok(())
}

/// Send a coordinate-pointer press to the first visible match, when requested.
///
/// This is an explicit generic hit-testing diagnostic. Application suites use
/// the node-addressed default and opt into this only when pointer hit-testing
/// itself is the behavior under test.
async fn press_named(client: &mut Client, want: &str) -> Result<()> {
    /*
     * Any role, on screen - the same resolution `click` uses.
     *
     * This was buttons only, on the reasoning that a control and the thing it
     * opens can share an accessible name, so a name-only match might select
     * the output instead of the activator. That is a real hazard for
     * `open_named`, which is looking for an activator. It is the wrong rule
     * here: the point of this diagnostic is to compare the pointer path
     * against the node-addressed one on the *same* control, and a role filter
     * that `click` does not apply makes the two incomparable.
     *
     * Concretely, a menu item has role `menuitem`, so pressing one always
     * failed with "no visible, enabled, sized node" while clicking the
     * identical node worked. That read as a dismissal-on-pointerdown defect in
     * the overlay - it was recorded as a known gap in AgencyZero's pill menu
     * checks - and it was this filter the whole time. Selecting from a menu by
     * pointer, the gesture a person actually makes, had no coverage at all.
     */
    // `role:name`, as `painted_named` and the check subjects already accept.
    // Without it a bare name falls back to substring matching over every node:
    // pressing "low" in this application matched a Keychain warning containing
    // "allow" and moved the pointer to the top of the window. A check that
    // asserts a menu selection has to be able to say which node it means.
    let (role, name) = want.split_once(':').unwrap_or(("", want));
    let roles: &[&str] = if role.is_empty() { &[] } else { &[role] };
    let (id, b) = locate_control(client, name, roles).await?;
    let (x, y) = (b[0] + b[2] / 2.0, b[1] + b[3] / 2.0);
    if cli::trace() {
        println!("        pressing {want:?} (id {id}) at {x:.0},{y:.0}");
    }
    for phase in [PointerPhase::Move, PointerPhase::Down, PointerPhase::Up] {
        client
            .agent(&AgentControlRequest::Act(AgentAction::Input(
                InputCommand::Pointer {
                    phase,
                    x,
                    y,
                    button: 0,
                    modifiers: Modifiers::default(),
                },
            )))
            .await?;
    }
    Ok(())
}

/// `click_named` without the metrics report, for the QA runner's inner loop.
async fn click_named_quiet(client: &mut Client, want: &str) -> Result<u64> {
    // Resolve through the same painted, on-screen semantic path as navigation.
    // `visible` alone is insufficient: retained subtrees can expose an old
    // semantic node at 0x0, and activating that id reports a working control
    // dead while its current painted replacement remains untouched.
    let (target_id, _) = locate_control(client, want, &[]).await?;
    if cli::trace() {
        println!("        activating {want:?} (id {target_id})");
    }
    client
        .agent(&AgentControlRequest::Act(AgentAction::Click {
            node_id: target_id,
        }))
        .await?;
    Ok(target_id)
}

/// Drive one declared QA action and normalize its optional semantic node id.
///
/// Coordinate presses are an explicit generic harness diagnostic, so they do
/// not produce a semantic action id. The normal application path is a node-id
/// click and returns the exact node used for outcome attribution.
async fn drive_check_action(
    client: &mut Client,
    want: &str,
    coordinate_press: bool,
    prepared_node_id: Option<u64>,
) -> std::result::Result<Option<u64>, String> {
    if coordinate_press {
        press_named(client, want)
            .await
            .map(|()| None)
            .map_err(|error| format!("could not press {want:?}: {error}"))
    } else {
        let node_id = prepared_node_id
            .ok_or_else(|| format!("could not click {want:?}: target was not prepared"))?;
        if cli::trace() {
            println!("        activating {want:?} (id {node_id})");
        }
        client
            .agent(&AgentControlRequest::Act(AgentAction::Click { node_id }))
            .await
            .map(|_| Some(node_id))
            .map_err(|error| format!("could not click {want:?}: {error}"))
    }
}

async fn capture(
    client: &mut Client,
    want: &str,
    scale: f32,
    output: Option<&std::path::Path>,
) -> Result<()> {
    let node_id = if want.is_empty() {
        None
    } else {
        let (snapshot, _) = inspect(client).await?;
        let node = snapshot
            .nodes
            .iter()
            .filter(|node| selector_matches_node(node, want) && node.visible)
            .filter_map(|node| node.bounds.map(|bounds| (node, bounds)))
            .filter(|(_, bounds)| bounds[2] > 0.0 && bounds[3] > 0.0)
            .max_by(|a, b| {
                (a.1[2] * a.1[3])
                    .partial_cmp(&(b.1[2] * b.1[3]))
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
            .map(|(node, _)| node);
        let Some(node) = node else {
            bail!("no visible node with a box matching {want:?}");
        };
        println!(
            "capturing {} role={} name={}",
            node.id,
            node.role,
            report::py_repr(&node.name.chars().take(50).collect::<String>())
        );
        Some(node.id)
    };

    let answer = client
        .diagnostics(&DiagnosticsRequest::Capture(CaptureRequest {
            node_id,
            scale,
        }))
        .await?;
    let image = match answer.response {
        DebugResponse::Captured(image) => image,
        other => bail!("asked for a capture, got {other:?}"),
    };

    let ink = measure_ink(&image)?;
    let fingerprint = {
        use std::hash::{DefaultHasher, Hash as _, Hasher as _};
        let mut hasher = DefaultHasher::new();
        image.width.hash(&mut hasher);
        image.height.hash(&mut hasher);
        image.rgba_base64.hash(&mut hasher);
        hasher.finish()
    };
    println!(
        "{}x{} at {scale}x, background #{:02x}{:02x}{:02x}",
        image.width, image.height, ink.background.0, ink.background.1, ink.background.2
    );
    println!("rgba fingerprint: {fingerprint:016x}");
    println!(
        "visible ink: {} of {} pixels ({:.2}%)",
        ink.visible,
        ink.total,
        ink.fraction() * 100.0
    );
    if ink.visible == 0 {
        println!("nothing was drawn: every pixel is the background colour");
    }
    if let Some(output) = output {
        write_capture_ppm(&image, output)?;
    }
    Ok(())
}

/// Audit every button in the running application.
///
/// Reads the renderer's own paint output rather than capturing each control.
/// The paint snapshot reports, per node, the style the renderer resolved and
/// the box it drew into, which answers the same question a capture does and
/// answers it for the whole window in one call.
///
/// Capturing per button was tried first and was worse in both directions. It
/// took 19 seconds against well under one, and it reported false faults: a crop
/// taken from a full-document paint cannot see content a clipping scroller drew
/// into its own layer, so three `Edit` buttons were flagged that the paint
/// output proved were drawn, with colours identical to their working siblings.
async fn run_audit(client: &mut Client, family: Option<&str>) -> Result<usize> {
    use audit::{Audited, Verdict};

    let (snapshot, _) = inspect(client).await?;

    /*
     * The viewport, read from the tree rather than assumed.
     *
     * A control below the fold is clipped, not broken. Lower section headers
     * can sit outside a short window and draw perfectly once
     * scrolled to, so a hardcoded bound reported them as faults. Reading the
     * `main` box also keeps this right when the window is resized.
     */
    let viewport = snapshot
        .nodes
        .iter()
        .filter(|node| node.role == "main")
        .filter_map(|node| node.bounds)
        .map(|b| (b[1], b[1] + b[3]))
        .max_by(|a, b| {
            (a.1 - a.0)
                .partial_cmp(&(b.1 - b.0))
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or((0.0, f64::MAX));

    let painted = painted_nodes(client).await?;

    let mut rows: Vec<Audited> = Vec::new();
    for node in audit::buttons(&snapshot.nodes) {
        let family_name = audit::family_of(&node.name);
        if family.is_some_and(|want| family_name != want) {
            continue;
        }
        let (width, height) = node.bounds.map(|b| (b[2], b[3])).unwrap_or((0.0, 0.0));

        let verdict = if !node.visible {
            Verdict::Hidden
        } else if width <= 0.0 || height <= 0.0 {
            Verdict::NoBox
        } else if node
            .bounds
            .is_some_and(|b| b[1] + b[3] < viewport.0 || b[0] + b[2] < 0.0 || b[1] > viewport.1)
        {
            Verdict::Offscreen
        } else if painted.contains(&node.id) {
            Verdict::Drawn
        } else {
            Verdict::Blank
        };

        rows.push(Audited {
            name: node.name.clone(),
            family: family_name,
            width,
            height,
            verdict,
        });
    }

    if rows.is_empty() {
        bail!("no buttons matched {family:?}");
    }
    println!("auditing {} buttons in the running app\n", rows.len());

    let faults: Vec<&Audited> = rows.iter().filter(|row| row.verdict.is_fault()).collect();
    if faults.is_empty() {
        println!("no faults: every visible button was painted");
    } else {
        println!("{} button(s) nobody can see:\n", faults.len());
        for row in &faults {
            println!(
                "  {:<8} {:<52} {:.0}x{:.0}",
                row.verdict.label(),
                row.name.chars().take(52).collect::<String>(),
                row.width,
                row.height
            );
        }
        println!();
    }

    let mut families: Vec<_> = audit::by_family(&rows).into_iter().collect();
    families.sort_by_key(|(name, _)| *name);
    for (name, (passed, total)) in families {
        let mark = if passed == total { " " } else { "!" };
        println!("{mark} {name:<12} {passed}/{total}");
    }
    println!("\n{} audited, {} faults", rows.len(), faults.len());
    Ok(faults.len())
}

/// The nodes the renderer resolved and drew, from one paint snapshot.
///
/// A button absent from this was not painted, which is what "a person cannot
/// see it" means. Asked once for the whole window rather than per control.
async fn painted_nodes(client: &mut Client) -> Result<HashSet<u64>> {
    let answer = client
        .diagnostics(&DiagnosticsRequest::Snapshot(SnapshotRequest {
            include_dom: false,
            include_layout: false,
            include_computed_style: true,
            node_ids: Vec::new(),
        }))
        .await?;
    let DebugResponse::Snapshot(snapshot) = answer.response else {
        bail!("asked for a paint snapshot, got {:?}", answer.response);
    };
    Ok(snapshot
        .computed_style
        .as_ref()
        .and_then(|value| value.as_array())
        .map(|rows| {
            rows.iter()
                .filter_map(|row| row.get("nodeId")?.as_u64())
                .collect()
        })
        .unwrap_or_default())
}

/// Click every button and report the ones that did not act.
///
/// The tree is re-read after each click rather than once at the end, because a
/// click changes what is on screen and a stale node id is a click on nothing.
/// Buttons are addressed by name for the same reason: ids do not survive the
/// re-render that a working button causes.
async fn run_sweep(client: &mut Client, family: Option<&str>) -> Result<usize> {
    let (snapshot, _) = inspect(client).await?;
    let viewport = snapshot
        .nodes
        .iter()
        .filter(|node| node.role == "main")
        .filter_map(|node| node.bounds)
        .map(|b| (b[1], b[1] + b[3]))
        .max_by(|a, b| {
            (a.1 - a.0)
                .partial_cmp(&(b.1 - b.0))
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or((0.0, f64::MAX));
    let planned = sweep::cases(
        &snapshot.nodes,
        family,
        audit::family_of,
        reach::is_inert_control,
    );
    if planned.is_empty() {
        bail!("no clickable buttons matched {family:?}");
    }
    println!("clicking {} buttons\n", planned.len());

    let mut outcomes: Vec<sweep::Outcome> = Vec::new();
    for case in planned {
        let (before, _) = inspect(client).await?;

        /*
         * Re-resolved by id, freshly, every time.
         *
         * Clicking by name cannot work here: fifteen task-log rows are all
         * called "Show the whole command", so after the first click the lookup
         * is ambiguous and every later one reports a failure that is the
         * harness's, not the application's. That produced 24 false failures in
         * the first run and buried whatever was real.
         *
         * The id is re-checked against the current tree rather than trusted
         * from the plan, because a working button re-renders its own row and a
         * stale id is a click on nothing.
         */
        let Some(node) = before.nodes.iter().find(|node| node.id == case.id) else {
            // Gone since the plan was made, which a working button often
            // causes: closing one tab removes the close buttons of its
            // neighbours. Not a failure.
            continue;
        };
        if !node.visible || !node.enabled {
            continue;
        }
        /*
         * Off the viewport is not clickable, and clicking it anyway tests the
         * harness rather than the application. A transcript keeps hundreds of
         * controls at negative coordinates and the panel's lower sections sit
         * below the fold; both reported as failures until they were skipped.
         */
        if node
            .bounds
            .is_some_and(|b| b[1] + b[3] < viewport.0 || b[0] + b[2] < 0.0 || b[1] > viewport.1)
        {
            continue;
        }

        if let Err(error) = click_by_id(client, case.id).await {
            outcomes.push(sweep::Outcome {
                case,
                failure: Some(format!("could not be clicked: {error}")),
            });
            continue;
        }
        // Long enough for a synchronous handler and its re-render. A backend
        // round trip is slower, and a button that only fails under that delay
        // is reported rather than waited for: a person sees the same thing.
        tokio::time::sleep(Duration::from_millis(250)).await;

        let (after, _) = inspect(client).await?;
        let failure = sweep::judge(&case, &before.nodes, &after.nodes);
        outcomes.push(sweep::Outcome { case, failure });
    }

    let failures: Vec<&sweep::Outcome> = outcomes.iter().filter(|o| o.failure.is_some()).collect();
    if failures.is_empty() {
        println!("every button acted");
    } else {
        println!("{} button(s) did not act:\n", failures.len());
        for outcome in &failures {
            println!(
                "  {:<48} {}",
                outcome.case.name.chars().take(48).collect::<String>(),
                outcome.failure.as_deref().unwrap_or("")
            );
        }
        println!();
    }

    let mut by_family: HashMap<&'static str, (usize, usize)> = HashMap::new();
    for outcome in &outcomes {
        let entry = by_family.entry(outcome.case.family).or_insert((0, 0));
        entry.1 += 1;
        if outcome.failure.is_none() {
            entry.0 += 1;
        }
    }
    let mut families: Vec<_> = by_family.into_iter().collect();
    families.sort_by_key(|(name, _)| *name);
    for (name, (passed, total)) in families {
        let mark = if passed == total { " " } else { "!" };
        println!("{mark} {name:<12} {passed}/{total}");
    }
    println!(
        "\n{} clicked, {} did not act",
        outcomes.len(),
        failures.len()
    );
    Ok(failures.len())
}

/// Open every collapsed section on the current surface.
///
/// Repeated until nothing more opens, because expanding one section reveals
/// disclosure controls inside it: a collection may hold a row per record, each with
/// its own. A single pass stops one level short of the controls that matter.
async fn expand_everything(client: &mut Client, surface: &reach::Surface) -> Result<usize> {
    let mut opened = 0;
    // Bounded: a disclosure that reports "Expand" after being expanded would
    // otherwise spin here forever, and that is a bug worth finishing the run to
    // report rather than hanging on.
    for _ in 0..6 {
        let (tree, _) = inspect(client).await?;
        // This surface's disclosures only: a retained pane keeps its own, and
        // pressing one of those navigates out of the surface being planned.
        let mine: std::collections::HashSet<u64> = reach::on_surface_subtree(&tree.nodes, surface)
            .into_iter()
            .collect();
        let mut todo: Vec<String> =
            reach::expanders(&tree.nodes, &reach::profile().expand_prefixes)
                .into_iter()
                .filter(|(id, _)| mine.contains(id))
                .map(|(_, name)| name)
                .collect();
        // Retained panes can expose dozens of identical disclosure names. One
        // semantic activation on the active surface is the user action; driving
        // every retained node toggles unrelated panes and can leave the current
        // one exactly where it started.
        todo.sort();
        todo.dedup();
        if todo.is_empty() {
            break;
        }
        for name in todo {
            if click_named_quiet(client, &name).await.is_ok() {
                opened += 1;
                tokio::time::sleep(Duration::from_millis(80)).await;
            }
        }
    }
    Ok(opened)
}

/// Reveal lazily mounted content on the active surface without guessing a
/// coordinate or knowing an application's section names.
///
/// Some long settings pages render their section shells first and mount each
/// body only when scrolling approaches it. If a check names a control in a
/// deferred body, that control cannot be addressed yet. The deepest rendered
/// node is the semantic equivalent of dragging the page toward its end; after
/// each node-ID reveal the tree is inspected again and the requested control
/// wins as soon as it has a real box.
async fn reveal_deferred_content(
    client: &mut Client,
    surface: &reach::Surface,
    want: &str,
) -> Result<usize> {
    let materialized = materialize_deferred_content(client, surface, want).await?
        + materialize_paginated_content(client, surface).await?;
    if materialized > 0 {
        let (snapshot, _) = inspect(client).await?;
        if painted_named(&snapshot.nodes, want) {
            return Ok(materialized);
        }
    }
    for step in 0..8 {
        let (snapshot, _) = inspect(client).await?;
        if painted_named(&snapshot.nodes, want) {
            return Ok(step);
        }
        let scope: HashSet<u64> = reach::on_surface_subtree(&snapshot.nodes, surface)
            .into_iter()
            .collect();
        let Some(target) = snapshot
            .nodes
            .iter()
            .filter(|node| scope.contains(&node.id))
            .filter_map(|node| {
                node.bounds
                    .filter(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
                    .map(|bounds| (node.id, bounds[1] + bounds[3]))
            })
            .max_by(|left, right| {
                left.1
                    .partial_cmp(&right.1)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
        else {
            return Ok(step);
        };
        client
            .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                node_id: target.0,
            }))
            .await?;
        tokio::time::sleep(Duration::from_millis(75)).await;
    }
    Ok(8)
}

/// Ask an application-declared search field to mount the control this check
/// needs, then return the surface to its neutral unfiltered state when the
/// mounted control survives there.
async fn materialize_deferred_content(
    client: &mut Client,
    surface: &reach::Surface,
    want: &str,
) -> Result<usize> {
    let Some(field) = surface.reveal_with.as_deref() else {
        return Ok(0);
    };
    let query = want.split_once(':').map_or(want, |(_, name)| name);
    type_text(client, field, query).await?;
    if wait_for_arrival(client, None, want).await? {
        // The reveal field is a discovery mechanism, not part of the check's
        // authored state. Leaving it filled hides outcomes whose accessible
        // name changes (and poisons every later check on the surface). Lazy
        // settings catalogues normally retain a section once mounted, so clear
        // the filter and keep the neutral state when the target still paints.
        // A virtualized catalogue that truly requires its query gets it put
        // back rather than losing the control before the action.
        type_text(client, field, "").await?;
        if !wait_for_arrival(client, None, want).await? {
            type_text(client, field, query).await?;
            let _ = wait_for_arrival(client, None, want).await?;
        }
    } else {
        // Absence is itself a valid authored outcome (for example, a setup
        // action that must disappear after its work is complete). Discovery
        // still owns the temporary query: a failed lookup must not leave the
        // whole surface filtered and make the next independent check fail.
        type_text(client, field, "").await?;
    }
    Ok(1)
}

/// Traverse a virtualized surface until scrolling stops mounting controls.
///
/// This drives no application action: it only reveals the deepest existing
/// semantic node. Settings/catalog screens commonly keep section shells in the
/// tree and mount their interactive bodies as the reader approaches them, so
/// one snapshot from the opening viewport is not an inventory of the surface.
async fn materialize_scrolled_content(
    client: &mut Client,
    surface: &reach::Surface,
) -> Result<usize> {
    let mut previous_count = None;
    let mut stable_passes = 0usize;
    let mut scrolls = 0usize;

    // Start from a known edge. If a prior focused check left the surface at
    // its current bottom, revealing that same bottom again emits no scroll
    // event and a scroll-driven virtualizer never gets a chance to admit its
    // remaining sections.
    let (initial, _) = inspect(client).await?;
    let initial_scope: HashSet<u64> = reach::on_surface_subtree(&initial.nodes, surface)
        .into_iter()
        .collect();
    if let Some(top) = initial
        .nodes
        .iter()
        .filter(|node| initial_scope.contains(&node.id))
        .filter(|node| node.role == "heading" || reach::interactive(node))
        .filter_map(|node| {
            node.bounds
                .filter(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
                .map(|bounds| (node.id, bounds[1]))
        })
        .min_by(|left, right| left.1.total_cmp(&right.1))
    {
        client
            .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                node_id: top.0,
            }))
            .await?;
        scrolls += 1;
        tokio::time::sleep(Duration::from_millis(50)).await;
    }

    for _ in 0..16 {
        let (tree, _) = inspect(client).await?;
        let scope: HashSet<u64> = reach::on_surface_subtree(&tree.nodes, surface)
            .into_iter()
            .collect();
        let interactive = tree
            .nodes
            .iter()
            .filter(|node| scope.contains(&node.id) && reach::interactive(node))
            .count();
        if cli::trace() {
            println!(
                "        inventory materialize surface={} interactive={} stable={}",
                surface.name, interactive, stable_passes
            );
        }
        if previous_count == Some(interactive) {
            stable_passes += 1;
            if stable_passes >= 2 {
                return Ok(scrolls);
            }
        } else {
            previous_count = Some(interactive);
            stable_passes = 0;
        }

        let Some(target) = tree
            .nodes
            .iter()
            .filter(|node| scope.contains(&node.id))
            .filter_map(|node| {
                node.bounds
                    .filter(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
                    .map(|bounds| (node.id, bounds[1]))
            })
            .max_by(|left, right| left.1.total_cmp(&right.1))
        else {
            return Ok(scrolls);
        };
        if cli::trace() {
            println!(
                "        inventory reveal deepest node={} y={:.1}",
                target.0, target.1
            );
        }
        client
            .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                node_id: target.0,
            }))
            .await?;
        scrolls += 1;
        tokio::time::sleep(Duration::from_millis(50)).await;
    }
    Ok(scrolls)
}

/// Reveal every page the application explicitly identifies as pagination.
///
/// This is semantic node-id activation. Pager labels are application data, so
/// the profile supplies fragments such as ` more records`; a generic `Show`
/// heuristic would also activate unrelated disclosure controls.
fn is_pagination_control(node: &SemanticNode, scope: &HashSet<u64>, patterns: &[String]) -> bool {
    scope.contains(&node.id)
        && node.role == "button"
        && node.enabled
        && node.visible
        && node
            .bounds
            .is_some_and(|bounds| bounds[2] > 0.0 && bounds[3] > 0.0)
        && patterns
            .iter()
            .any(|pattern| name_matches(&node.name, pattern))
}

type SemanticShape = (String, String, Option<String>);

fn semantic_shapes(nodes: &[SemanticNode], scope: &HashSet<u64>) -> HashSet<SemanticShape> {
    nodes
        .iter()
        .filter(|node| scope.contains(&node.id))
        .map(|node| (node.role.clone(), node.name.clone(), node.value.clone()))
        .collect()
}

fn pagination_advanced(
    previous_shapes: &HashSet<SemanticShape>,
    previous_name: &str,
    current_shapes: &HashSet<SemanticShape>,
    current: &SemanticNode,
) -> bool {
    current.name != previous_name || current_shapes.len() > previous_shapes.len()
}

async fn materialize_paginated_content(
    client: &mut Client,
    surface: &reach::Surface,
) -> Result<usize> {
    let patterns = &reach::profile().pagination_controls;
    if patterns.is_empty() {
        return Ok(0);
    }
    let mut revealed = 0;
    let mut retired_pagers = HashSet::new();
    for _ in 0..32 {
        let (tree, _) = inspect(client).await?;
        let scope: HashSet<u64> = reach::on_surface_subtree(&tree.nodes, surface)
            .into_iter()
            .collect();
        let target = tree.nodes.iter().find(|node| {
            !retired_pagers.contains(&node.id) && is_pagination_control(node, &scope, patterns)
        });
        let Some(target) = target else {
            return Ok(revealed);
        };
        let node_id = target.id;
        let mut pager_name = target.name.clone();
        let mut pager_shapes = semantic_shapes(&tree.nodes, &scope);
        client
            .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                node_id,
            }))
            .await?;

        // A pager keeps its semantic identity while only its remaining count
        // changes. The protocol deliberately treats activation as a delivered
        // input even after the DOM node has gone away, so an error is not a
        // disappearance signal. Read the semantic tree after each activation
        // and stop as soon as this exact id is no longer an enabled, painted
        // pager. Without that check a one-page Home button is clicked 128 times
        // as a no-op and turns a two-second inventory into a multi-minute run.
        let mut removed = false;
        for _ in 0..128 {
            if click_by_id(client, node_id).await.is_err() {
                removed = true;
                break;
            }
            revealed += 1;
            tokio::time::sleep(Duration::from_millis(5)).await;
            let (after, _) = inspect(client).await?;
            let after_scope: HashSet<u64> = reach::on_surface_subtree(&after.nodes, surface)
                .into_iter()
                .collect();
            let after_shapes = semantic_shapes(&after.nodes, &after_scope);
            let still_present = after.nodes.iter().find(|node| {
                node.id == node_id && is_pagination_control(node, &after_scope, patterns)
            });
            match still_present {
                Some(current)
                    if pagination_advanced(&pager_shapes, &pager_name, &after_shapes, current) =>
                {
                    pager_name.clone_from(&current.name);
                    pager_shapes = after_shapes;
                }
                _ => {
                    // A reveal-more control must expose semantic progress.
                    // Blitz can retain the removed DOM node for one or more
                    // snapshots, including its old geometry and visible bit;
                    // repeatedly activating that unchanged identity is a no-op
                    // loop. Retire it and scan for the next real pager.
                    retired_pagers.insert(node_id);
                    removed = true;
                    break;
                }
            }
        }
        if !removed {
            bail!("pagination node {node_id} did not disappear after 128 activations");
        }
    }
    bail!("pagination controls did not terminate after 32 semantic identities")
}

/// Hover every row on the surface, so hover-revealed controls enter the tree.
///
/// The row controls users asked about - rename, delete, pin - do not exist
/// until `pointerenter`. Hovering is what puts them in the tree at all, so this
/// runs before the plan is made rather than per-click.
async fn hover_all_rows(client: &mut Client) -> Result<usize> {
    let (tree, _) = inspect(client).await?;
    // The window band, taken from the largest `main`, so rows scrolled far off
    // the top of a transcript are not hovered at negative coordinates.
    let window = tree
        .nodes
        .iter()
        .filter(|node| node.role == "main")
        .filter_map(|node| node.bounds)
        .map(|b| (b[1], b[1] + b[3]))
        .max_by(|a, b| {
            (a.1 - a.0)
                .partial_cmp(&(b.1 - b.0))
                .unwrap_or(std::cmp::Ordering::Equal)
        })
        .unwrap_or((0.0, 4000.0));
    let mut revealed = 0;
    for node_id in reach::hover_row_ids(&tree.nodes, "listitem", window) {
        if client
            .agent(&AgentControlRequest::Act(AgentAction::Hover { node_id }))
            .await
            .is_ok()
        {
            // The protocol reply is the synchronization point. Sleeping after
            // every row adds no evidence and turns a large paginated table into
            // minutes of idle time.
            revealed += 1;
        }
    }
    Ok(revealed)
}

/// Inventory semantic reachability across every configured application
/// surface without pressing the controls being counted.
///
/// `cover` answers a different and much more expensive question: it activates
/// every eligible button and performs multiple full-tree reads per button.
/// An agent asking which components are unreachable should not pay that cost or
/// mutate the profile merely to obtain counts. Navigation, disclosure expansion
/// and hover are still necessary preconditions, and all three are node-id
/// actions.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum InventoryClass {
    MissingId,
    UnstableId,
    DuplicateId,
    Manual,
    Isolated,
    Anonymous,
    Unreachable,
    Disabled,
    Reachable,
}

fn duplicate_dom_ids<'a>(
    nodes: impl IntoIterator<Item = &'a SemanticNode>,
) -> std::collections::HashSet<String> {
    let mut counts = std::collections::HashMap::<&str, usize>::new();
    for dom_id in nodes
        .into_iter()
        .filter_map(|node| node.dom_id.as_deref())
        .filter(|dom_id| !dom_id.trim().is_empty())
    {
        *counts.entry(dom_id).or_default() += 1;
    }
    counts
        .into_iter()
        .filter(|(_, count)| *count > 1)
        .map(|(dom_id, _)| dom_id.to_owned())
        .collect()
}

fn generated_dom_id(dom_id: &str) -> bool {
    let mut pieces = dom_id.split('-');
    match (pieces.next(), pieces.next()) {
        (Some("cl"), Some(instance)) => instance.parse::<u64>().is_ok(),
        (Some(slot), Some(instance)) => {
            slot.parse::<u64>().is_ok() && instance.parse::<u64>().is_ok()
        }
        _ => false,
    }
}

fn inventory_class(
    node: &SemanticNode,
    manual: bool,
    isolated: bool,
    duplicate_ids: &std::collections::HashSet<String>,
) -> InventoryClass {
    if node.dom_id.as_deref().is_none_or(|id| id.trim().is_empty()) {
        InventoryClass::MissingId
    } else if node.dom_id.as_deref().is_some_and(generated_dom_id) {
        InventoryClass::UnstableId
    } else if node
        .dom_id
        .as_ref()
        .is_some_and(|id| duplicate_ids.contains(id))
    {
        InventoryClass::DuplicateId
    } else if manual {
        InventoryClass::Manual
    } else if isolated {
        InventoryClass::Isolated
    } else if node.name.trim().is_empty() {
        InventoryClass::Anonymous
    } else if !reach::onscreen(node) {
        InventoryClass::Unreachable
    } else if !node.enabled {
        InventoryClass::Disabled
    } else {
        InventoryClass::Reachable
    }
}

/// Whether a selector from an outcome check addresses this exact semantic
/// control shape.
///
/// `role:name` is the precise spelling used by checks when a button and the
/// field it opens share a name. Everything else follows the same substring or
/// glob matching as the live driver, so coverage cannot claim a selector the
/// runner itself would never resolve.
/// The library part this selector names, if it names one.
///
/// `@inline-edit-field` addresses the slot rather than the text, which is what
/// separates a trigger from the thing it opens: those routinely share an
/// accessible name, so a selector written against the name reaches whichever
/// paints and never the other.
fn outcome_check_ids(node: &SemanticNode, checks: &[qa::Check]) -> Vec<String> {
    checks
        .iter()
        .filter(|check| {
            /*
             * Navigation is not coverage for a control on the destination.
             *
             * `open: "Settings"` used to participate in this match. Because
             * live selector semantics intentionally accept substrings, that
             * credited controls such as "Allow agents to update app settings"
             * for every check which merely navigated to Settings. The search
             * field was similarly credited by every check that used it only as
             * the surface's reveal mechanism. Neither control was driven by
             * those checks.
             *
             * Credit only explicit interaction fields. `prepare` belongs here:
             * opening a dropdown trigger is an indispensable driven step in a
             * menu-selection outcome, even though the measured action is the
             * option click. `covers` remains the deliberate escape hatch for a
             * repeated component family proven by one representative outcome.
             */
            let driven = [
                check.prepare.as_deref(),
                check.hover.as_ref().map(qa::Hover::target),
                check.after_prepare_hover.as_ref().map(qa::Hover::target),
                check.click.as_deref(),
                check.type_into.as_deref(),
                check.key_on.as_deref(),
                check.scroll_over.as_deref(),
            ]
            .into_iter()
            .flatten()
            .any(|selector| coverage_action_matches_node(node, selector));
            let family = check
                .covers
                .iter()
                .any(|selector| selector_matches_node(node, selector));
            let disabled_outcome = !node.enabled
                && matches!(check.expect, qa::Expect::Disabled)
                && coverage_action_matches_node(node, &check.subject);
            driven || family || disabled_outcome
        })
        .map(|check| check.id.clone())
        .collect()
}

/// Coverage attribution is deliberately stricter than interactive lookup.
///
/// The live driver accepts a bare substring as a convenience, then narrows to
/// an exact candidate when one exists in the complete tree. Inventory examines
/// one node at a time and cannot perform that global narrowing. Reusing the
/// broad predicate here credited `click: "Settings"` to every control whose
/// label happened to contain “settings”. Require an exact name/id/slot unless
/// the application explicitly writes a glob. Repeated families use `covers`,
/// whose whole purpose is deliberate broad attribution.
fn coverage_action_matches_node(node: &SemanticNode, selector: &str) -> bool {
    if selector.contains('*') {
        selector_matches_node(node, selector)
    } else {
        exact_selector_matches_node(node, selector)
    }
}

#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
struct SavedControl {
    surface: String,
    #[serde(default)]
    dom_id: Option<String>,
    #[serde(default)]
    slot: Option<String>,
    role: String,
    name: String,
    classification: String,
}

#[derive(serde::Deserialize)]
struct SavedInventory {
    controls: Vec<SavedControl>,
}

fn saved_controls(report: &str) -> Result<Vec<SavedControl>, String> {
    toon_format::decode_default::<SavedInventory>(report)
        .map(|inventory| inventory.controls)
        .map_err(|error| format!("inventory report is not valid TOON: {error}"))
}

fn saved_control_node(control: &SavedControl) -> SemanticNode {
    SemanticNode {
        dom_id: control.dom_id.clone(),
        id: 0,
        parent: None,
        role: control.role.clone(),
        name: control.name.clone(),
        value: None,
        enabled: !control.classification.contains("disabled"),
        visible: !control.classification.contains("unreachable"),
        selected: false,
        bounds: Some([0.0, 0.0, 1.0, 1.0]),
        slot: control.slot.clone(),
    }
}

fn reconcile_inventory(
    inventory: &std::path::Path,
    checks_dir: Option<&std::path::Path>,
) -> Result<usize> {
    #[derive(serde::Serialize)]
    struct MissingRow {
        surface: String,
        dom_id: Option<String>,
        slot: Option<String>,
        role: String,
        name: String,
        classification: String,
        checks: Vec<String>,
    }

    #[derive(serde::Serialize)]
    struct ReconcileReport {
        components: usize,
        outcome_declared: usize,
        excluded_manual: usize,
        failed_existing: usize,
        unverified: usize,
        controls: Vec<MissingRow>,
    }

    let input = std::fs::read_to_string(inventory)?;
    let controls = saved_controls(&input).map_err(eyre::Report::msg)?;
    let checks = qa::checks(checks_dir).map_err(eyre::Report::msg)?;
    let mut outcome_declared = 0;
    let mut excluded_manual = 0;
    let mut failed_existing = 0;
    let mut missing = Vec::new();

    for control in &controls {
        let node = saved_control_node(control);
        let matched = outcome_check_ids(&node, &checks);
        if control.classification == "excluded-manual" {
            excluded_manual += 1;
        } else if control.classification.starts_with("failed-") {
            failed_existing += 1;
            missing.push(MissingRow {
                surface: control.surface.clone(),
                dom_id: control.dom_id.clone(),
                slot: control.slot.clone(),
                role: control.role.clone(),
                name: control.name.clone(),
                classification: control.classification.clone(),
                checks: matched,
            });
        } else if control.classification.contains("isolated") || matched.is_empty() {
            missing.push(MissingRow {
                surface: control.surface.clone(),
                dom_id: control.dom_id.clone(),
                slot: control.slot.clone(),
                role: control.role.clone(),
                name: control.name.clone(),
                classification: if control.classification.contains("isolated") {
                    "isolated-unverified".into()
                } else if control.classification.contains("disabled") {
                    "state-disabled-unverified".into()
                } else {
                    "outcome-unverified".into()
                },
                checks: matched,
            });
        } else {
            outcome_declared += 1;
        }
    }

    let unverified = missing
        .iter()
        .filter(|row| !row.classification.starts_with("failed-"))
        .count();
    let report = ReconcileReport {
        components: controls.len(),
        outcome_declared,
        excluded_manual,
        failed_existing,
        unverified,
        controls: missing,
    };
    println!(
        "{}",
        toon_format::encode_default(&report).map_err(|error| eyre!(error.to_string()))?
    );
    // An offline report cannot execute controls that deliberately terminate
    // the shared process or its inspector. Keep them visible in `unverified`,
    // but let the application-owned isolated lifecycle gate decide them.
    // Otherwise a successful disposable-process check can never make the
    // combined workflow green.
    let blocking_unverified = report
        .controls
        .iter()
        .filter(|row| reconciliation_gap_blocks(&row.classification))
        .count();
    Ok(report.failed_existing + blocking_unverified)
}

fn reconciliation_gap_blocks(classification: &str) -> bool {
    !classification.starts_with("isolated-") && !classification.starts_with("failed-")
}

fn inventory_outcome_failures(unverified: usize, isolated: usize, required: bool) -> usize {
    if required {
        // Isolated controls are deliberately proven by a disposable-process
        // lifecycle gate after this shared sweep. Keep them visible in the
        // report, but do not make `--require-outcomes` impossible to satisfy.
        unverified.saturating_sub(isolated)
    } else {
        0
    }
}

fn validate_surface_filter_against(only: Option<&str>, surfaces: &[reach::Surface]) -> Result<()> {
    let Some(want) = only else {
        return Ok(());
    };
    if surfaces
        .iter()
        .any(|surface| surface.name.eq_ignore_ascii_case(want))
    {
        return Ok(());
    }
    let available = surfaces
        .iter()
        .map(|surface| surface.name.as_str())
        .collect::<Vec<_>>()
        .join(", ");
    bail!("unknown surface {want:?}; choose one of: {available}")
}

fn validate_surface_filter(only: Option<&str>) -> Result<()> {
    validate_surface_filter_against(only, reach::surfaces())
}

fn surface_selected(surface: &reach::Surface, only: Option<&str>) -> bool {
    only.is_none_or(|want| surface.name.eq_ignore_ascii_case(want))
}

async fn run_inventory(
    client: &mut Client,
    only: Option<&str>,
    require_outcomes: bool,
    checks_path: Option<&std::path::Path>,
) -> Result<usize> {
    validate_surface_filter(only)?;
    #[derive(serde::Serialize)]
    struct SurfaceRow {
        surface: String,
        opened: bool,
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<String>,
        components: usize,
        reachable: usize,
        unreachable: usize,
        state_hidden: usize,
        anonymous: usize,
        missing_id: usize,
        unstable_id: usize,
        duplicate_id: usize,
        disabled: usize,
        manual: usize,
        isolated: usize,
        outcome_declared: usize,
        unverified: usize,
        sections_opened: usize,
        rows_hovered: usize,
    }

    #[derive(serde::Serialize)]
    struct ControlRow {
        surface: String,
        id: u64,
        dom_id: Option<String>,
        slot: Option<String>,
        role: String,
        name: String,
        classification: String,
        reason: String,
        checks: Vec<String>,
    }

    #[derive(serde::Serialize)]
    struct RoleRow {
        role: String,
        components: usize,
        reachable: usize,
        unreachable: usize,
        state_hidden: usize,
        anonymous: usize,
        missing_id: usize,
        unstable_id: usize,
        duplicate_id: usize,
        disabled: usize,
        manual: usize,
        isolated: usize,
        outcome_declared: usize,
        unverified: usize,
    }

    #[derive(serde::Serialize)]
    struct InventoryReport {
        components: usize,
        reachable: usize,
        unreachable: usize,
        state_hidden: usize,
        anonymous: usize,
        missing_id: usize,
        unstable_id: usize,
        duplicate_id: usize,
        disabled: usize,
        manual: usize,
        isolated: usize,
        outcome_declared: usize,
        unverified: usize,
        surfaces: Vec<SurfaceRow>,
        roles: Vec<RoleRow>,
        controls: Vec<ControlRow>,
    }

    let default_checks_exist = qa::default_checks_path().is_dir();
    let checks = if checks_path.is_some() || default_checks_exist || require_outcomes {
        qa::checks(checks_path).map_err(eyre::Report::msg)?
    } else {
        eprintln!(
            "warning: no --checks directory and {} does not exist; outcome coverage will be reported as zero",
            qa::default_checks_path().display()
        );
        Vec::new()
    };
    let mut rows = Vec::new();
    let mut controls = Vec::new();
    let mut surface_failures = 0_usize;
    let mut role_counts: std::collections::BTreeMap<String, [usize; 13]> =
        std::collections::BTreeMap::new();
    for surface in reach::surfaces() {
        if !surface_selected(surface, only) {
            continue;
        }
        if !open_surface(client, surface).await? {
            rows.push(SurfaceRow {
                surface: surface.name.clone(),
                opened: false,
                error: None,
                components: 0,
                reachable: 0,
                unreachable: 0,
                state_hidden: 0,
                anonymous: 0,
                missing_id: 0,
                unstable_id: 0,
                duplicate_id: 0,
                disabled: 0,
                manual: 0,
                isolated: 0,
                outcome_declared: 0,
                unverified: 0,
                sections_opened: 0,
                rows_hovered: 0,
            });
            continue;
        }

        let sections_opened = expand_everything(client, surface).await?;
        if !open_surface(client, surface).await? {
            rows.push(SurfaceRow {
                surface: surface.name.clone(),
                opened: false,
                error: None,
                components: 0,
                reachable: 0,
                unreachable: 0,
                state_hidden: 0,
                anonymous: 0,
                missing_id: 0,
                unstable_id: 0,
                duplicate_id: 0,
                disabled: 0,
                manual: 0,
                isolated: 0,
                outcome_declared: 0,
                unverified: 0,
                sections_opened,
                rows_hovered: 0,
            });
            continue;
        }
        // Inventory needs the whole surface, not whichever filtered slice a
        // preceding focused check left behind. Hold the application-declared
        // reveal field empty until after the snapshot; the ordinary
        // materializer restores immediately because a single check only needs
        // one target, which is exactly the wrong lifetime for an inventory.
        let held_filter = if let Some(field) = surface.reveal_with.as_deref() {
            let (tree, _) = inspect(client).await?;
            let previous = tree
                .nodes
                .iter()
                .find(|node| selector_matches_node(node, field))
                .and_then(|node| node.value.clone())
                .unwrap_or_default();
            if !previous.is_empty() {
                type_text(client, field, "").await?;
                tokio::time::sleep(Duration::from_millis(25)).await;
            }
            Some((field.to_owned(), previous))
        } else {
            None
        };
        let inspected = async {
            materialize_scrolled_content(client, surface).await?;
            materialize_paginated_content(client, surface).await?;
            let rows_hovered = hover_all_rows(client).await?;
            let (tree, _) = inspect(client).await?;
            Ok::<_, eyre::Report>((rows_hovered, tree))
        }
        .await;
        if let Some((field, previous)) = &held_filter
            && !previous.is_empty()
        {
            type_text(client, field, previous).await?;
        }
        let (rows_hovered, tree) = match inspected {
            Ok(inspected) => inspected,
            Err(error) => {
                rows.push(SurfaceRow {
                    surface: surface.name.clone(),
                    opened: true,
                    error: Some(error.to_string()),
                    components: 0,
                    reachable: 0,
                    unreachable: 0,
                    state_hidden: 0,
                    anonymous: 0,
                    missing_id: 0,
                    unstable_id: 0,
                    duplicate_id: 0,
                    disabled: 0,
                    manual: 0,
                    isolated: 0,
                    outcome_declared: 0,
                    unverified: 0,
                    sections_opened,
                    rows_hovered: 0,
                });
                surface_failures += 1;
                continue;
            }
        };
        let mine: std::collections::HashSet<u64> = reach::on_surface_subtree(&tree.nodes, surface)
            .into_iter()
            .collect();
        let components: Vec<_> = tree
            .nodes
            .iter()
            .filter(|node| reach::interactive(node) && mine.contains(&node.id))
            .collect();
        let duplicate_ids =
            duplicate_dom_ids(tree.nodes.iter().filter(|node| mine.contains(&node.id)));
        let classes: Vec<_> = components
            .iter()
            .map(|node| {
                inventory_class(
                    node,
                    reach::requires_manual_release_check(&node.name),
                    reach::requires_isolated_outcome(&node.name),
                    &duplicate_ids,
                )
            })
            .collect();
        let declared: Vec<Vec<String>> = components
            .iter()
            .map(|node| outcome_check_ids(node, &checks))
            .collect();
        let count = |class| classes.iter().filter(|found| **found == class).count();
        let reachable = count(InventoryClass::Reachable);
        // A component can own a real semantic field that is intentionally
        // hidden until its trigger opens it. A named check which reveals and
        // judges that field is proof; an equally hidden node with no such
        // check remains a reachability failure.
        let unreachable = classes
            .iter()
            .zip(&declared)
            .filter(|(class, matches)| **class == InventoryClass::Unreachable && matches.is_empty())
            .count();
        let state_hidden = classes
            .iter()
            .zip(&declared)
            .filter(|(class, matches)| {
                **class == InventoryClass::Unreachable && !matches.is_empty()
            })
            .count();
        let anonymous = count(InventoryClass::Anonymous);
        let missing_id = count(InventoryClass::MissingId);
        let unstable_id = count(InventoryClass::UnstableId);
        let duplicate_id = count(InventoryClass::DuplicateId);
        let disabled = count(InventoryClass::Disabled);
        let manual = count(InventoryClass::Manual);
        let isolated = count(InventoryClass::Isolated);
        let outcome_declared = classes
            .iter()
            .zip(&declared)
            .filter(|(class, matches)| {
                matches!(
                    class,
                    InventoryClass::Reachable
                        | InventoryClass::Disabled
                        | InventoryClass::Unreachable
                ) && !matches.is_empty()
            })
            .count();
        let unverified = classes
            .iter()
            .zip(&declared)
            .filter(|(class, matches)| match class {
                InventoryClass::Reachable | InventoryClass::Disabled => matches.is_empty(),
                // These must run in disposable processes; declaration in the
                // shared suite cannot turn them green.
                InventoryClass::Isolated => true,
                InventoryClass::Manual
                | InventoryClass::MissingId
                | InventoryClass::UnstableId
                | InventoryClass::DuplicateId
                | InventoryClass::Anonymous
                | InventoryClass::Unreachable => false,
            })
            .count();
        for (node, matched_checks) in components.iter().zip(&declared) {
            let manual = reach::requires_manual_release_check(&node.name);
            let isolated = reach::requires_isolated_outcome(&node.name);
            let class = inventory_class(node, manual, isolated, &duplicate_ids);
            let counts = role_counts.entry(node.role.clone()).or_default();
            counts[0] += 1;
            match class {
                InventoryClass::Reachable => counts[1] += 1,
                InventoryClass::Unreachable if matched_checks.is_empty() => counts[2] += 1,
                InventoryClass::Unreachable => counts[12] += 1,
                InventoryClass::Anonymous => counts[3] += 1,
                InventoryClass::MissingId => counts[4] += 1,
                InventoryClass::UnstableId => counts[5] += 1,
                InventoryClass::DuplicateId => counts[6] += 1,
                InventoryClass::Disabled => counts[7] += 1,
                InventoryClass::Manual => counts[8] += 1,
                InventoryClass::Isolated => counts[9] += 1,
            }
            if !matched_checks.is_empty() {
                counts[10] += 1;
            }
            let is_unverified = match class {
                InventoryClass::Reachable | InventoryClass::Disabled => matched_checks.is_empty(),
                InventoryClass::Isolated => true,
                InventoryClass::Manual
                | InventoryClass::MissingId
                | InventoryClass::UnstableId
                | InventoryClass::DuplicateId
                | InventoryClass::Anonymous
                | InventoryClass::Unreachable => false,
            };
            if is_unverified {
                counts[11] += 1;
            }
            let (classification, reason) = match class {
                InventoryClass::MissingId => ("failed-missing-id", "no stable DOM id"),
                InventoryClass::UnstableId => (
                    "failed-unstable-id",
                    "framework-generated creation-order DOM id",
                ),
                InventoryClass::DuplicateId => ("failed-duplicate-id", "DOM id is not unique"),
                InventoryClass::Manual => ("excluded-manual", "native-dialog-or-external"),
                InventoryClass::Isolated => (
                    "isolated-unverified",
                    "requires disposable-process outcome check",
                ),
                InventoryClass::Anonymous => ("failed-anonymous", "no accessible name"),
                InventoryClass::Unreachable if !matched_checks.is_empty() => (
                    "outcome-declared-hidden",
                    "matched named reveal/outcome check",
                ),
                InventoryClass::Unreachable if !node.visible => ("failed-reachability", "hidden"),
                InventoryClass::Unreachable => ("failed-reachability", "no-box"),
                InventoryClass::Disabled if matched_checks.is_empty() => {
                    ("state-disabled-unverified", "no outcome check matched")
                }
                InventoryClass::Disabled => {
                    ("outcome-declared-disabled", "matched named outcome check")
                }
                InventoryClass::Reachable if matched_checks.is_empty() => {
                    ("reachable-unverified", "no outcome check matched")
                }
                InventoryClass::Reachable => ("outcome-declared", "matched named outcome check"),
            };
            controls.push(ControlRow {
                surface: surface.name.clone(),
                id: node.id,
                dom_id: node.dom_id.clone(),
                slot: node.slot.clone(),
                role: node.role.clone(),
                name: node.name.clone(),
                classification: classification.to_owned(),
                reason: reason.to_owned(),
                checks: matched_checks.clone(),
            });
        }
        rows.push(SurfaceRow {
            surface: surface.name.clone(),
            opened: true,
            error: None,
            components: components.len(),
            reachable,
            unreachable,
            state_hidden,
            anonymous,
            missing_id,
            unstable_id,
            duplicate_id,
            disabled,
            manual,
            isolated,
            outcome_declared,
            unverified,
            sections_opened,
            rows_hovered,
        });
    }

    let report = InventoryReport {
        components: rows.iter().map(|row| row.components).sum(),
        reachable: rows.iter().map(|row| row.reachable).sum(),
        unreachable: rows.iter().map(|row| row.unreachable).sum(),
        state_hidden: rows.iter().map(|row| row.state_hidden).sum(),
        anonymous: rows.iter().map(|row| row.anonymous).sum(),
        missing_id: rows.iter().map(|row| row.missing_id).sum(),
        unstable_id: rows.iter().map(|row| row.unstable_id).sum(),
        duplicate_id: rows.iter().map(|row| row.duplicate_id).sum(),
        disabled: rows.iter().map(|row| row.disabled).sum(),
        manual: rows.iter().map(|row| row.manual).sum(),
        isolated: rows.iter().map(|row| row.isolated).sum(),
        outcome_declared: rows.iter().map(|row| row.outcome_declared).sum(),
        unverified: rows.iter().map(|row| row.unverified).sum(),
        surfaces: rows,
        roles: role_counts
            .into_iter()
            .map(|(role, counts)| RoleRow {
                role,
                components: counts[0],
                reachable: counts[1],
                unreachable: counts[2],
                state_hidden: counts[12],
                anonymous: counts[3],
                missing_id: counts[4],
                unstable_id: counts[5],
                duplicate_id: counts[6],
                disabled: counts[7],
                manual: counts[8],
                isolated: counts[9],
                outcome_declared: counts[10],
                unverified: counts[11],
            })
            .collect(),
        controls,
    };
    let failures = report.unreachable
        + report.anonymous
        + report.missing_id
        + report.unstable_id
        + report.duplicate_id
        + inventory_outcome_failures(report.unverified, report.isolated, require_outcomes)
        + surface_failures;
    println!(
        "{}",
        toon_format::encode_default(&report).map_err(|error| eyre!(error.to_string()))?
    );
    Ok(failures)
}

/// Navigate to a surface, and say whether it opened.
async fn open_surface(client: &mut Client, surface: &reach::Surface) -> Result<bool> {
    if surface.opener.is_empty() {
        return Ok(true);
    }
    // Do not activate the current tab again. Inventory intentionally calls
    // this before and after expanding a surface; re-clicking the same opener
    // remounts expensive application trees and adds no evidence. The marker is
    // the same destination proof used after a real navigation.
    let (current, _) = inspect(client).await?;
    if reach::on_surface(&current.nodes, surface) {
        return Ok(true);
    }
    // A dynamic document surface has no fixed name to aim at: the profile may be scrubbed,
    // so the tab is found by shape (a tab is the button whose `Close` twin the
    // strip renders beside it) rather than by a string that would differ per
    // profile.
    let opener = if surface.opener == reach::DYNAMIC_DOCUMENT {
        /*
         * Via the configured root surface, because that is where a dynamic
         * document can be opened from on a fresh profile.
         *
         * The strip holds no project tab until one has been opened, and the
         * sweep may reach the document while standing on another surface, where there is
         * no row to press either. Looking from where we happen to be found
         * nothing every time and the pane went unswept on exactly the runs that
         * matter. Cheap when a tab already exists: the lookup prefers it.
         */
        let (here, _) = inspect(client).await?;
        if reach::document_opener(&here.nodes).is_none() {
            if let Some(home) = reach::profile().home_opener.as_deref() {
                let _ = click_named_quiet(client, home).await;
            }
            tokio::time::sleep(Duration::from_millis(600)).await;
        }
        let (tree, _) = inspect(client).await?;
        match reach::document_opener(&tree.nodes) {
            Some(name) => name,
            None => return Ok(false),
        }
    } else {
        surface.opener.to_owned()
    };
    /*
     * Confirmed by looking, not assumed from the click succeeding.
     *
     * A dispatched click is not proof of navigation: a control can acknowledge
     * activation while the current surface remains unchanged. Always confirm
     * the destination marker before attributing controls to that surface.
     */
    /*
     * A dynamic document row uses the profile contract's double-click gesture;
     * a fixed surface opener uses an ordinary semantic click.
     */
    if surface.opener == reach::DYNAMIC_DOCUMENT {
        /*
         * Scrolled into view before it is aimed at.
         *
         * A box is not a position on screen. The first row this picked sat at
         * y=1152 in a 900px window - laid out, `visible`, and below the fold -
         * so the gesture went to a point with nothing under it and the project
         * surface stayed unreachable while the report said only "could not be
         * opened".
         */
        let (tree, _) = inspect(client).await?;
        let Some(id) = tree
            .nodes
            .iter()
            .find(|n| n.name == opener && reach::onscreen(n))
            .map(|n| n.id)
        else {
            return Ok(false);
        };
        client
            .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                node_id: id,
            }))
            .await?;
        tokio::time::sleep(Duration::from_millis(400)).await;

        let (tree, _) = inspect(client).await?;
        if !tree.nodes.iter().any(|n| n.id == id && reach::onscreen(n)) {
            return Ok(false);
        }
        client
            .agent(&AgentControlRequest::Act(AgentAction::DoubleClick {
                node_id: id,
            }))
            .await?;
    } else if click_named_quiet(client, &opener).await.is_err() {
        return Ok(false);
    }
    if settle_on(client, surface).await? {
        return Ok(true);
    }
    // One retry through the configured root, which can recover when
    // a modal on the current one is swallowing the direct hop.
    // Not for the project surface: its opener is a gesture, and repeating it as
    // a single click would fold the row rather than open it.
    if surface.opener == reach::DYNAMIC_DOCUMENT {
        return Ok(false);
    }
    if let Some(home) = reach::profile().home_opener.as_deref() {
        let _ = click_named_quiet(client, home).await;
    }
    tokio::time::sleep(Duration::from_millis(400)).await;
    if click_named_quiet(client, &opener).await.is_err() {
        return Ok(false);
    }
    settle_on(client, surface).await
}

/// Sweep the controls inside an open modal, then prove it can be dismissed.
///
/// Returns `true` when the dialog would not close by any means a person has:
/// its own dismiss controls, then Escape. That is a trap rather than a failed
/// button - every control behind it is unreachable while it is up - so the
/// caller stops rather than reporting hundreds of downstream failures that are
/// really one bug.
///
/// The dialog's own controls are pressed *before* the dismiss is tried, because
/// a `Cancel` that works would take them all off screen and they would never be
/// tested. Destructive-sounding ones are pressed last for the same reason.
async fn sweep_modal(
    client: &mut Client,
    opener: &str,
    here: &mut reach::Coverage,
    failures: &mut Vec<(String, String, String)>,
    surface: &str,
) -> Result<bool> {
    let (tree, _) = inspect(client).await?;
    let dismiss_ids: Vec<u64> = reach::dismissers(&tree.nodes)
        .into_iter()
        .map(|(id, _)| id)
        .collect();

    /*
     * The dialog's own controls, not the window's.
     *
     * A modal leaves the surface behind it in the tree, still `visible` and
     * still sized, exactly as a retained pane does. Sweeping everything on
     * screen can press retained-surface controls that are not in the dialog,
     * including a native-panel opener. The subtree that holds the dismiss
     * control is the dialog.
     */
    let scope = dismiss_ids
        .first()
        .map(|id| reach::enclosing_dialog(&tree.nodes, *id))
        .unwrap_or_default();
    if cli::trace() {
        for node in tree.nodes.iter().filter(|node| {
            scope.contains(&node.id)
                && (reach::profile()
                    .deferred_controls
                    .iter()
                    .any(|name| node.name.eq_ignore_ascii_case(name))
                    || reach::requires_isolated_outcome(&node.name))
        }) {
            println!(
                "      [modal] deferred to an outcome check: {:?}",
                node.name
            );
        }
    }
    let inner: Vec<(u64, String)> = tree
        .nodes
        .iter()
        .filter(|n| n.role == "button" && reach::onscreen(n) && n.enabled)
        .filter(|n| !n.name.trim().is_empty())
        .filter(|n| !dismiss_ids.contains(&n.id))
        .filter(|n| scope.contains(&n.id))
        .filter(|n| !reach::requires_manual_release_check(&n.name))
        .filter(|n| !reach::requires_isolated_outcome(&n.name))
        .filter(|n| {
            !reach::profile()
                .deferred_controls
                .iter()
                .any(|name| n.name.eq_ignore_ascii_case(name))
        })
        .map(|n| (n.id, n.name.clone()))
        .collect();

    for (id, name) in inner {
        let (before, _) = inspect(client).await?;
        if !before
            .nodes
            .iter()
            .any(|n| n.id == id && reach::onscreen(n))
        {
            continue;
        }
        if click_by_id(client, id).await.is_err() {
            continue;
        }
        // `revealed`, not `swept`: this control did not exist when the surface's
        // buttons were counted, so charging it to `swept` pushes the buckets
        // past the total and turns the consistency check negative.
        here.revealed += 1;
        if cli::trace() {
            println!("      [modal] clicked: {name:?}");
        }
        tokio::time::sleep(Duration::from_millis(180)).await;
        let (after, _) = inspect(client).await?;
        let case = sweep::Case {
            id,
            name: name.clone(),
            family: audit::family_of(&name),
            expect: sweep::expectation_for(&name, reach::is_inert_control(&name)),
        };
        if let Some(why) = sweep::judge(&case, &before.nodes, &after.nodes) {
            failures.push((
                surface.to_owned(),
                format!("{name} (in {opener} dialog)"),
                why,
            ));
        }
        // A control inside the dialog may itself have closed it.
        let (now, _) = inspect(client).await?;
        if !reach::modal_open(&now.nodes) {
            return Ok(false);
        }
    }

    // Every way out, in the order a person would reach for them.
    let (tree, _) = inspect(client).await?;
    for (id, name) in reach::dismissers(&tree.nodes) {
        if click_by_id(client, id).await.is_err() {
            continue;
        }
        // A dismisser belongs to the dialog, not to the surface underneath it.
        here.revealed += 1;
        tokio::time::sleep(Duration::from_millis(250)).await;
        let (after, _) = inspect(client).await?;
        if !reach::modal_open(&after.nodes) {
            return Ok(false);
        }
        failures.push((
            surface.to_owned(),
            format!("{name} (in {opener} dialog)"),
            "the dialog is still open; it did not dismiss".to_owned(),
        ));
    }

    // Escape, which `AppModal` binds and which is the last thing a person has.
    let _ = press_key(client, "escape", 1, "", false).await;
    tokio::time::sleep(Duration::from_millis(300)).await;
    let (after, _) = inspect(client).await?;
    if !reach::modal_open(&after.nodes) {
        return Ok(false);
    }
    failures.push((
        surface.to_owned(),
        format!("{opener} dialog"),
        "TRAPPED: no dismiss control and no Escape closes it".to_owned(),
    ));
    Ok(true)
}

/// Wait until the surface is actually showing, up to a few seconds.
///
/// Polled rather than slept: Analytics takes longer to build than the others
/// and a fixed 500ms wait declared it unopened while it was still on its way,
/// which sent the whole sweep down the retry path and then swept the wrong
/// surface twice. Polling costs nothing when the pane is already up.
async fn settle_on(client: &mut Client, surface: &reach::Surface) -> Result<bool> {
    for _ in 0..12 {
        tokio::time::sleep(Duration::from_millis(400)).await;
        let (tree, _) = inspect(client).await?;
        if reach::on_surface(&tree.nodes, surface) {
            return Ok(true);
        }
    }
    Ok(false)
}

/// Sweep every surface, and account for every button in the tree.
///
/// The difference from `sweep`: it visits more than the screen the app opened
/// on, it opens what is closed and hovers what reveals on hover before planning,
/// and it reports what it could not reach instead of dropping it. A run that
/// covers a fifth of the window now says so.
///
/// `SWEEP_TRACE=1` names every control as it is pressed and every one that goes
/// missing, with the surface state at that moment. Every coverage bug found so
/// far looked identical from the summary - a large `vanished` count - and was
/// only separable from this: a stale id after a re-sort, a tab click walking off
/// the surface, and a collapse hiding its own neighbours all read the same until
/// you can see which click preceded them.
async fn run_cover(
    client: &mut Client,
    only: Option<&str>,
    unmapped_only: bool,
    checks_dir: Option<&std::path::Path>,
) -> Result<usize> {
    validate_surface_filter(only)?;
    let mut total = reach::Coverage::default();
    let mut failures: Vec<(String, String, String)> = Vec::new();
    // Named, so the manual worklist at the end is what this run actually met.
    let mut skipped_manual: Vec<String> = Vec::new();
    // Named separately: these remain automated work, but need a disposable app.
    let mut skipped_isolated: Vec<String> = Vec::new();
    let checks = if unmapped_only {
        qa::checks(checks_dir).map_err(eyre::Report::msg)?
    } else {
        Vec::new()
    };

    for surface in reach::surfaces() {
        if !surface_selected(surface, only) {
            continue;
        }
        if !open_surface(client, surface).await? {
            println!("- {:<10} could not be opened, skipping\n", surface.name);
            continue;
        }

        /*
         * Expanded within this surface only, and the surface re-checked after.
         *
         * `expand_everything` pressed every `Expand *` in the window, including
         * ones belonging to retained panes behind this one. Twelve such presses
         * can run before the current surface's plan is built, navigate away,
         * and leave that surface reporting zero buttons in a full run.
         */
        let opened = expand_everything(client, surface).await?;
        if !open_surface(client, surface).await? {
            println!("- {:<10} left during expansion, skipping\n", surface.name);
            continue;
        }
        materialize_deferred_content(client, surface, "").await?;
        if let Err(error) = materialize_paginated_content(client, surface).await {
            failures.push((
                surface.name.clone(),
                "pagination".to_owned(),
                error.to_string(),
            ));
            continue;
        }
        let hovered = hover_all_rows(client).await?;

        /*
         * This surface's buttons, not the whole window's.
         *
         * A retained pane keeps its entire subtree alive and merely hidden, so
         * standing on one surface the tree can still hold every button from a
         * retained peer. Counting those here charges each surface for controls it was
         * not looking at: four surfaces reported 1106 buttons between them for
         * a window that has nowhere near that many, with 900 of them "hidden"
         * and the real coverage number buried.
         *
         * The subject is what is on screen now. A control retained from another
         * surface is that surface's to sweep, and it is swept when we stand
         * there.
         */
        let (tree, _) = inspect(client).await?;
        /*
         * Scoped by ancestry to the pane in front.
         *
         * A retained surface can keep real, `visible`, correctly-sized boxes behind an
         * open document pane, in the same horizontal band, so
         * neither position nor visibility separates them. Sweeping the union
         * means another surface's row controls are pressed under the current
         * surface's name while its own controls are crowded out of the plan.
         */
        let mine: std::collections::HashSet<u64> = reach::on_surface_subtree(&tree.nodes, surface)
            .into_iter()
            .collect();
        let buttons: Vec<&blitz_control_protocol::SemanticNode> = tree
            .nodes
            .iter()
            .filter(|n| n.role == "button" && !n.name.trim().is_empty())
            .filter(|n| n.visible)
            .filter(|n| mine.contains(&n.id))
            .collect();

        // Retained from other surfaces, reported so the difference between the
        // window's button count and this surface's is never silent.
        let retained = tree
            .nodes
            .iter()
            .filter(|n| n.role == "button" && !n.name.trim().is_empty() && !n.visible)
            .count();
        let mut here = reach::Coverage {
            in_tree: buttons.len(),
            ..Default::default()
        };
        /*
         * Counted in a plain loop, not inside a `filter` closure.
         *
         * Written as a lazy filter that incremented the tallies, the counts were
         * still zero when the surface line printed them and only filled in as
         * the plan was consumed: the first run reported "0 swept, 0 unreachable,
         * UNACCOUNTED 106" for a surface it went on to sweep. A report that
         * undercounts itself is the exact failure this mode exists to remove.
         */
        let mut plan: Vec<(u64, String)> = Vec::new();
        let mut collapsers: Vec<(u64, String)> = Vec::new();
        let mut closers: Vec<(u64, String)> = Vec::new();
        for node in &buttons {
            if !reach::onscreen(node) {
                here.unreachable += 1;
            } else if reach::requires_isolated_outcome(&node.name) {
                here.isolated += 1;
                skipped_isolated.push(node.name.clone());
            } else if reach::requires_manual_release_check(&node.name) {
                // Never pressed unattended: a native chooser takes the user's
                // screen and cannot be dismissed from here.
                here.manual += 1;
                skipped_manual.push(node.name.clone());
            } else if unmapped_only && !outcome_check_ids(node, &checks).is_empty() {
                here.outcome_declared += 1;
            } else if reach::profile()
                .fold_prefixes
                .iter()
                .any(|p| node.name.to_lowercase().starts_with(&p.to_lowercase()))
                || reach::profile()
                    .deferred_controls
                    .iter()
                    .any(|c| node.name.eq_ignore_ascii_case(c))
                || reach::folds_a_section(&node.name)
            {
                /*
                 * Swept, but last.
                 *
                 * A collapse closes the section its neighbours live in, and
                 * every control underneath goes to `visible=false` at the
                 * section's own origin. Pressing `Collapse Recent` first took
                 * most controls on the surface off screen and the run charged
                 * them all as vanished, which read as the app losing its
                 * buttons rather than the sweep hiding them.
                 *
                 * A configured document-creation control belongs here for the
                 * opposite reason: it opens what it creates, so pressing it
                 * early walks the sweep off its surface. It is still pressed after
                 * the rest of the surface is done.
                 *
                 * A configured fold control can hide an entire side panel and
                 * every row action beneath it. Deferring fold controls keeps
                 * those descendants in the sweep plan.
                 */
                collapsers.push((node.id, node.name.clone()));
            } else if reach::navigates(&node.name)
                || reach::opens_document_row(&tree.nodes, node.id)
            {
                // Swept as the opener of its own surface, not here: pressing it
                // mid-plan navigates away and every later button on this
                // surface reads as vanished.
                here.navigation += 1;
            } else if reach::closes_a_surface(&node.name) {
                /*
                 * Swept, but after everything that stands on the tab it
                 * removes.
                 *
                 * Closing a tab can fall back to the root and retire a pane
                 * later surfaces are reached through. It is deferred rather
                 * than skipped, so the control is still pressed.
                 */
                closers.push((node.id, node.name.clone()));
            } else {
                plan.push((node.id, node.name.clone()));
            }
        }
        /*
         * Order within the plan: harmless first, then destructive, then the
         * disclosures that would hide either.
         *
         * A `Delete` removes its own row and shifts every row under it, so
         * running deletes early costs the sweep the controls it had not reached
         * yet. Sorting is stable, so controls otherwise keep tree order.
         */
        plan.sort_by_key(|(_, name)| {
            let lower = name.to_lowercase();
            u8::from(
                lower.starts_with("delete ")
                    || lower.starts_with("close ")
                    || lower.starts_with("remove ")
                    || lower.starts_with("retire "),
            )
        });
        plan.extend(collapsers);
        // Last of all: these retire the pane everything above stands on.
        plan.extend(closers);

        /*
         * Swept by name, and the surface is restored only when it has actually
         * been left.
         *
         * Re-navigating before every click looked safer and was much worse: the
         * re-render invalidated the very plan it was protecting, and the run
         * reported 98 of 125 controls vanished. Checking first costs one tree
         * read and leaves a working surface alone.
         */
        let mut done: HashMap<String, usize> = HashMap::new();
        let planned_total = plan.len();
        for (index, (planned_id, name)) in plan.into_iter().enumerate() {
            // What would be left if this control traps the window.
            let remaining = planned_total.saturating_sub(index + 1);
            let (mut before, _) = inspect(client).await?;
            if !reach::on_surface(&before.nodes, surface) {
                if !open_surface(client, surface).await? {
                    here.vanished += 1;
                    if cli::trace() {
                        println!("    left surface, could not return: {name:?}");
                    }
                    continue;
                }
                let (fresh, _) = inspect(client).await?;
                before = fresh;
            }

            /*
             * By id while it is still on screen, otherwise by name.
             *
             * Ids do not survive a re-render, and re-renders are ordinary here:
             * A sort control can reorder the list and every row can return with
             * a fresh id, the old ones retained as hidden 0x0 nodes at the
             * container's origin. Trusting the planned id after that pressed
             * nothing and charge the remaining controls as "vanished"
             * while all of them were on screen the whole time.
             *
             * Names are not unique - 161 on-screen buttons share 81 names, with
             * one label alone appearing thirty times - so the name path
             * takes the nth still-unpressed match rather than the first, which
             * is what stops one row absorbing every click aimed at its
             * neighbours.
             */
            let seen = done.entry(name.clone()).or_insert(0);
            let found = before
                .nodes
                .iter()
                .find(|n| n.id == planned_id && n.name == name && reach::onscreen(n))
                .or_else(|| {
                    before
                        .nodes
                        .iter()
                        .filter(|n| n.role == "button" && n.name == name && reach::onscreen(n))
                        .nth(*seen)
                });
            let Some(node) = found else {
                here.vanished += 1;
                if cli::trace() {
                    println!("    vanished: {name:?} (id {planned_id})");
                }
                continue;
            };
            *seen += 1;
            let id = node.id;
            if !reach::onscreen(node) || !node.enabled {
                here.vanished += 1;
                if cli::trace() {
                    let visible_buttons = before
                        .nodes
                        .iter()
                        .filter(|n| n.role == "button" && reach::onscreen(n))
                        .count();
                    println!(
                        "    offscreen/disabled: {name:?} visible={} bounds={:?} \
                         [on_surface={}, {visible_buttons} buttons on screen]",
                        node.visible,
                        node.bounds,
                        reach::on_surface(&before.nodes, surface),
                    );
                }
                continue;
            }
            let case = sweep::Case {
                id,
                name: name.clone(),
                family: audit::family_of(&name),
                expect: sweep::expectation_for(&name, reach::is_inert_control(&name)),
            };
            /*
             * Stop on a failed dispatch.
             *
             * This id came from the snapshot immediately above and names an
             * enabled, on-screen control. If the inspector cannot activate it,
             * continuing is not broader coverage: a native modal or halted UI
             * loop can leave the socket open without answering, making every
             * later control pay the full 60-second transport timeout. One run
             * then sat here for eighteen minutes after the ordinary sweep had
             * previously completed in two and a half. Preserve the exact
             * control in the error and stop before a transport failure is
             * multiplied by the rest of the plan.
             */
            let activation = tokio::time::timeout(check_timeout(900), click_by_id(client, id))
                .await
                .map_err(|_| {
                    eyre!(
                        "activation exceeded {}ms for {name:?} (id {id}) on {:?}",
                        check_timeout(900).as_millis(),
                        surface.name
                    )
                })?;
            if let Err(error) = activation {
                bail!(
                    "could not activate {name:?} (id {id}) on {:?}; stopping the sweep: {error}",
                    surface.name
                );
            }
            here.swept += 1;
            if cli::trace() {
                println!("    clicked: {name:?}");
            }
            tokio::time::sleep(Duration::from_millis(200)).await;

            /*
             * If that opened a modal, sweep it and then prove it closes.
             *
             * Judging each button against its own name cannot prove the
             * foreground dialog can be dismissed. The relevant outcome is
             * whether the application can return to the covered surface.
             *
             * A dialog that will not dismiss is reported and the run continues
             * from a restart rather than grinding on against a window nobody
             * can use.
             */
            let (after_click, _) = inspect(client).await?;
            let after = if reach::modal_open(&after_click.nodes) {
                let trapped =
                    sweep_modal(client, &name, &mut here, &mut failures, &surface.name).await?;
                if trapped {
                    /*
                     * Everything still in the plan is unreachable behind the
                     * trap, and saying so is the point: a bucket that silently
                     * loses 64 controls is how this audit missed the fork
                     * dialog in the first place.
                     */
                    println!(
                        "  ! {:?} opened a dialog that will not dismiss - \
                         the rest of this surface is unreachable behind it",
                        name
                    );
                    here.blocked += remaining;
                    break;
                }
                inspect(client).await?.0
            } else {
                after_click
            };
            if sweep::judge(&case, &before.nodes, &after.nodes).is_some() {
                // Backend-backed controls can acknowledge immediately and
                // update the semantic tree on the next task. Retry only a
                // would-be failure, so fast controls do not all pay for the
                // slowest one.
                tokio::time::sleep(Duration::from_millis(800)).await;
                let (settled, _) = inspect(client).await?;
                if let Some(why) = sweep::judge(&case, &before.nodes, &settled.nodes) {
                    failures.push((surface.name.to_owned(), name, why));
                }
            }
        }

        // Printed after the sweep, because `swept` is not known until then and
        // a coverage line that reports zero for work it is about to do is worse
        // than no line at all.
        println!(
            "= {:<10} {} ({} sections opened, {} rows hovered, {} retained elsewhere)",
            surface.name,
            here.line(),
            opened,
            hovered,
            retained
        );

        total.in_tree += here.in_tree;
        total.swept += here.swept;
        total.outcome_declared += here.outcome_declared;
        total.unreachable += here.unreachable;
        total.vanished += here.vanished;
        total.navigation += here.navigation;
        total.manual += here.manual;
        total.isolated += here.isolated;
        // `blocked` and `revealed` were missing here, so a control trapped
        // behind an undismissable dialog counted on its surface line and then
        // disappeared from the run total - the one line most likely to be
        // quoted as the coverage number.
        total.blocked += here.blocked;
        total.revealed += here.revealed;
    }

    println!("\n{}", total.line());
    /*
     * The exceptions, named, every run.
     *
     * A skipped control that is only a number in a bucket is a control nobody
     * remembers to test. Native dialogs that cannot be closed and controls
     * that open external destinations need a person, so the report says so
     * rather than implying the automated run covered them.
     */
    if total.manual > 0 {
        println!(
            "\n{} control(s) need the manual release pass:",
            total.manual
        );
        // Only the ones this run actually met, so the list is a worklist rather
        // than a catalogue of everything that could theoretically be skipped.
        let mut seen: Vec<&str> = skipped_manual.iter().map(String::as_str).collect();
        seen.sort_unstable();
        seen.dedup();
        for label in seen {
            let command = reach::profile()
                .manual_controls
                .iter()
                .find(|exception| label.starts_with(exception.label.as_str()))
                .map(|exception| exception.command.as_str())
                .unwrap_or("(unmapped manual control)");
            println!("  {label:<38} {command}");
        }
    }
    if total.isolated > 0 {
        println!(
            "\n{} control(s) require an isolated outcome check:",
            total.isolated
        );
        skipped_isolated.sort_unstable();
        skipped_isolated.dedup();
        for label in skipped_isolated {
            println!("  {label}");
        }
    }
    if failures.is_empty() {
        if total.isolated > 0 {
            println!("every broadly swept button acted; isolated controls remain listed above");
        } else {
            println!("every reached button acted");
        }
    } else {
        println!("\n{} did not act:\n", failures.len());
        for (surface, name, why) in &failures {
            println!(
                "  [{surface}] {:<40} {why}",
                name.chars().take(40).collect::<String>()
            );
        }
    }
    Ok(failures.len())
}

pub async fn run() -> Result<()> {
    let cli = <cli::Cli as clap::Parser>::parse();
    cli::set_trace(cli.trace);
    cli::set_pace(cli.pace);
    cli::set_timeout_scale(cli.timeout_scale);
    cli::set_capture_options(
        cli.trace_capture,
        cli.require_paint_events,
        cli.pixel_artifact_dir.clone(),
    );
    cli::set_app_profile(cli.app.clone());

    // The inventory reads the check list, not the application, so it answers
    // "what is covered" with nothing running. Before the descriptor lookup for
    // that reason: requiring a live instance to list the checks is what kept
    // the coverage question unanswerable.
    if let cli::Command::List { checks } = &cli.command {
        print!(
            "{}",
            qa::manifest(checks.as_deref()).map_err(|error| eyre!(error))?
        );
        return Ok(());
    }
    if let cli::Command::Reconcile { inventory, checks } = &cli.command {
        let failures = reconcile_inventory(inventory, checks.as_deref())?;
        if failures > 0 {
            std::process::exit(1);
        }
        return Ok(());
    }

    // Validate product-owned navigation and safety rules before any command
    // can reach the cached profile. Component sweeps launch their own hosts and
    // therefore dispatch before descriptor discovery, but they still use the
    // profile to classify controls. Validating after that early dispatch made
    // a missing profile panic from `reach` instead of returning a CLI error.
    if cli.command.requires_app_profile() {
        app::AppProfile::load(cli.app.as_deref()).map_err(|error| eyre!(error))?;
    }

    // A component sweep launches its own hosts, so it attaches to something
    // different for every component and cannot use the descriptor discovered
    // once up front. Dispatched here, before that lookup, for the same reason
    // the offline commands above are: requiring a running application would
    // defeat the point.
    if let cli::Command::SweepComponents {
        ids,
        host,
        dists,
        checks,
        startup_timeout,
        mode,
    } = &cli.command
    {
        let failures = sweep_components(
            ids,
            host,
            dists,
            checks.as_deref(),
            std::time::Duration::from_secs(*startup_timeout),
            *mode,
        )
        .await?;
        if failures > 0 {
            std::process::exit(1);
        }
        return Ok(());
    }

    // A hosted QA run owns one temporary renderer process. It uses the same
    // descriptor announcement and deadline as component sweeps, so callers do
    // not need to poll a file or guess how long first paint takes.
    if let cli::Command::QaHosted {
        selector,
        host,
        page,
        checks,
        startup_timeout,
    } = &cli.command
    {
        let (child, descriptor_path) =
            start_host(host, page, std::time::Duration::from_secs(*startup_timeout))
                .map_err(|error| eyre!(error))?;
        let result = run_component(&descriptor_path, selector.as_deref(), checks.as_deref()).await;
        drop(child);
        let failures = result?;
        if failures > 0 {
            std::process::exit(1);
        }
        return Ok(());
    }

    let descriptor = inspector::discover(cli.descriptor.as_deref().and_then(|p| p.to_str()))?;
    descriptor.warn_if_stale();

    let verbose = cli.command.is_dump();
    if verbose {
        println!("descriptor: {}", descriptor.path.display());
        println!("{}", report::dump(&descriptor.raw, usize::MAX));
    }

    let mut client = Client::connect(&descriptor.socket_path()).await?;
    let initialize = client.initialize().await?;
    if verbose {
        println!("\n== initialize ==");
        println!("{}", report::dump(&initialize, 800));
        println!("\n== tools ==");
        let tools = client.tools_list().await?;
        println!("{}", report::dump(&tools, 1200));
    }

    match cli.command {
        cli::Command::Metrics => {
            println!("\n== metrics ==");
            let envelope = client
                .diagnostics_envelope(&DiagnosticsRequest::Metrics)
                .await?;
            println!("{}", report::dump(&envelope, 2000));
        }
        cli::Command::Watch { seconds } => {
            println!("\n== observing paint/metrics/console/runtimeErrors for {seconds}s ==");
            // Tolerates a protocol error on purpose: the server answers
            // `streamingUnavailable` because `observe` is not implemented, and
            // reporting that is more useful than exiting on it.
            let answer = client
                .diagnostics_envelope(&DiagnosticsRequest::Observe {
                    streams: vec![
                        DebugStream::Paint,
                        DebugStream::Metrics,
                        DebugStream::Console,
                        DebugStream::RuntimeErrors,
                    ],
                })
                .await?;
            println!("{}", report::dump(&answer, 400));
            for message in client.drain(seconds).await? {
                println!("{}", report::dump(&message, 400));
            }
        }
        cli::Command::Frames => report::show_frames(&metrics(&mut client).await?),
        cli::Command::Tree => {
            println!("\n== semantic tree ==");
            // The Python sent `maxDepth` here, which the server rejects: fields
            // inside protocol variants are snake_case. Encoding from the shared
            // type is what makes that unrepresentable rather than a silent
            // error nobody read.
            let envelope = client
                .agent_envelope(&AgentControlRequest::Inspect {
                    root: None,
                    max_depth: 3,
                })
                .await?;
            println!("{}", report::dump(&envelope, 3000));
        }
        cli::Command::Find {
            pattern,
            role,
            visible,
            hidden,
            painted,
            offscreen,
            disabled,
            count,
            limit,
        } => {
            find(
                &mut client,
                &pattern,
                &role,
                visible,
                hidden,
                painted,
                offscreen,
                disabled,
                count,
                limit,
            )
            .await?;
        }
        cli::Command::Layout { name } => {
            layout(&mut client, &name).await?;
        }
        cli::Command::Transcript => transcript(&mut client).await?,
        cli::Command::Paint { name, min_area } => {
            paint_audit::report(&mut client, &name, min_area).await?;
        }
        cli::Command::Contrast {
            name,
            text_ratio,
            control_ratio,
        } => {
            paint_audit::contrast(&mut client, &name, text_ratio, control_ratio).await?;
        }
        cli::Command::Nodes => {
            nodes(&mut client).await?;
        }
        cli::Command::Panes => panes(&mut client).await?,
        cli::Command::Dom { name, depth } => {
            dom(&mut client, &name, depth).await?;
        }
        cli::Command::Spill { axis, tolerance } => {
            spill(&mut client, &axis, tolerance).await?;
        }
        cli::Command::Idle => report::show("idle", &metrics(&mut client).await?),
        // Every counter the app publishes is cumulative since launch, and a
        // mount costs thousands of DOM writes. Reading them once and calling
        // the total a rate is how "3,698 attribute writes" got recorded as 230
        // a second when it was actually the startup mount, counted once.
        // Two reads and a subtraction is the only honest way to ask what an
        // idle app is still doing.
        cli::Command::Drift { seconds } => {
            let before = metrics(&mut client).await?;
            println!("== holding still for {seconds}s, nothing driven ==");
            tokio::time::sleep(Duration::from_secs_f64(seconds)).await;
            let after = metrics(&mut client).await?;
            let frames_of =
                |m: &RendererMetrics| m.frame_window.as_ref().map(|w| w.frames_total).unwrap_or(0);
            let frames = frames_of(&after).saturating_sub(frames_of(&before));
            println!(
                "frames={frames} over {seconds}s = {:.1}fps with no input",
                frames as f64 / seconds
            );
            report::show_delta(&before, &after, 0);
        }
        /*
         * The owner's blinking-rectangle repro, asserted rather than described.
         *
         * The repro is a project with 0 items and the item list expanded, which
         * is the state this reads. It exists because the fault was reported
         * four times and twice called fixed from a reading that did not
         * actually cover it: an idle window is not quiet here, and saying so
         * once in prose has not been enough.
         *
         * What it asserts, and why each is the honest form of the question:
         *
         * - `missed_refreshes` over the sample window. A blink is a frame that
         *   did not land, so this is the number that has to be zero. It is a
         *   count over a fixed 256-frame window, not a rate, so it is
         *   comparable between runs.
         * - the worst frame interval against the display's own period. A single
         *   72ms gap on a 60Hz display is four dropped refreshes and is visible
         *   as a flash; a mean of 13ms is not. The mean is what a naive reading
         *   reports and it hides exactly this.
         *
         * Both are read from one metrics response so they describe the same
         * window. Exits non-zero when the fault is present, so it can gate a
         * fix instead of being read by eye.
         *
         * Deliberately not asserted: fps. It averages over the window and a
         * blink does not move it enough to fail on, which is how "the window is
         * quiet" was concluded from a sample that contained a 477ms stall.
         */
        /*
         * Controls that are meant to be hidden and still take up space.
         *
         * The class of fault this catches has now shipped twice, and neither
         * time did a component test see it, because both are about geometry in
         * the real renderer rather than behaviour in a DOM stub. A field hidden
         * by styling the input alone leaves the library's wrapper in the
         * layout: measured beside every project name, a 101x46 box painting as
         * a black rectangle and squeezing the name next to it down to a few
         * characters.
         *
         * The rule is narrow on purpose. A node whose accessible name says it
         * belongs to an inactive control - a rename editor with no editor open
         * - must not own a painted box. Anything genuinely displayed is
         * expected to have one, so this reports only boxes that are both
         * sizeable and attached to something the tree calls hidden.
         */
        cli::Command::Ghost { min_area, max } => {
            // Second argument so `ghost 64 0` can still demand a perfectly clean
            // tree when a caller wants that, without editing this default.
            let answer = client
                .diagnostics(&DiagnosticsRequest::Snapshot(SnapshotRequest {
                    include_dom: true,
                    include_layout: true,
                    include_computed_style: false,
                    node_ids: Vec::new(),
                }))
                .await?;
            let DebugResponse::Snapshot(snapshot) = answer.response else {
                bail!("asked for a layout snapshot, got {:?}", answer.response);
            };

            let mut boxes: HashMap<u64, (f64, f64, f64, f64)> = HashMap::new();
            if let Some(rows) = snapshot.layout {
                for row in rows {
                    boxes.insert(
                        row.node_id,
                        (
                            row.bounds.x,
                            row.bounds.y,
                            row.bounds.width,
                            row.bounds.height,
                        ),
                    );
                }
            }

            let nodes = snapshot
                .dom
                .as_ref()
                .and_then(|v| v.as_array())
                .cloned()
                .unwrap_or_default();

            let mut ghosts = Vec::new();
            for node in &nodes {
                // The snapshot spells this as `visible`, which is what `dom`
                // mode prints as HIDDEN. Reading a `hidden` key instead found
                // nothing and reported a clean run, which is the failure mode a
                // check like this must not have.
                let visible = node
                    .get("visible")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(true);
                if visible {
                    continue;
                }
                let Some(id) = node.get("id").and_then(|v| v.as_u64()) else {
                    continue;
                };
                let Some(&(x, y, w, h)) = boxes.get(&id) else {
                    continue;
                };
                if w * h >= min_area {
                    let name = node
                        .get("name")
                        .and_then(|v| v.as_str())
                        .unwrap_or("")
                        .to_string();
                    ghosts.push((id, name, x, y, w, h));
                }
            }
            ghosts.sort_by(|a, b| (b.4 * b.5).total_cmp(&(a.4 * a.5)));

            println!(
                "{} nodes inspected, reporting hidden boxes of {min_area}px2 or more",
                nodes.len()
            );
            for (id, name, x, y, w, h) in &ghosts {
                println!("  {id:>10}  {w:>7.1}x{h:<7.1} at {x:.0},{y:.0}  {name}");
            }
            if ghosts.is_empty() {
                println!("\nno ghosts: nothing hidden is holding a painted box");
            } else {
                println!(
                    "\nGHOSTS PRESENT: {} hidden node(s) still occupy layout",
                    ghosts.len()
                );
                // Retention is deliberate, so some ghosts are the design rather
                // than a leak: an application may deliberately retain a bounded
                // number of mounted-but-hidden panes. Failing on any ghost at
                // all therefore rejects valid retention policies.
                //
                // What a leak looks like: the 2026-08-20 window that painted one
                // flat colour and took no clicks measured 2,404 ghosts on a
                // comparable tree (5,527 nodes vs 5,098), a 41x rise. The budget
                // sits between the two, far enough above the healthy figure that
                // ordinary drift in the retained panes does not trip it.
                if ghosts.len() > max {
                    println!(
                        "over budget: {} ghosts, limit {max}. Hidden subtrees are not \
                         being unmounted.",
                        ghosts.len()
                    );
                    std::process::exit(1);
                }
                println!("within budget: limit {max}");
            }
        }
        cli::Command::Blink { allowed_missed } => {
            let reading = metrics(&mut client).await?;
            report::show("blink", &reading);

            let Some(window) = reading.frame_window.as_ref() else {
                eyre::bail!(
                    "the app published no frame window, so there is nothing to assert; \
                     launch it with --blitz-deep-profiling"
                );
            };

            // The refresh period the app itself reports, so this stays right on
            // a 120Hz panel rather than assuming 60. Unknown falls back to 60,
            // which is the more forgiving of the two.
            let period_ms = 1000.0
                / window
                    .display_refresh_hz
                    .filter(|hz| *hz > 0.0)
                    .unwrap_or(60.0);
            // Two periods: one late frame is a hiccup, two is a gap a person
            // sees. Anything under this is not the reported fault.
            let interval_budget = period_ms * 2.0;
            let worst_interval = window.interval.max_ms;

            println!();
            println!("== the reported repro: a project with 0 items, item list expanded ==");
            println!(
                "  missed refreshes : {} over {} frames (allowed {allowed_missed})",
                window.missed_refreshes, window.window_frames
            );
            println!(
                "  worst interval   : {worst_interval:.1}ms against a {period_ms:.1}ms refresh \
                 (budget {interval_budget:.1}ms)"
            );

            let mut faults = Vec::new();
            if window.missed_refreshes > allowed_missed {
                faults.push(format!(
                    "{} missed refreshes over {} frames",
                    window.missed_refreshes, window.window_frames
                ));
            }
            if worst_interval > interval_budget {
                faults.push(format!(
                    "a {worst_interval:.1}ms frame interval, {:.1}x the refresh period",
                    worst_interval / period_ms
                ));
            }

            if faults.is_empty() {
                println!("\nno blink: the window is quiet by both measures");
            } else {
                println!("\nBLINK PRESENT: {}", faults.join(", "));
                std::process::exit(1);
            }
        }
        cli::Command::Click { name, id } => {
            nodes(&mut client).await?;
            match (name, id) {
                (Some(name), None) => click_named(&mut client, &name).await?,
                (None, Some(node_id)) => {
                    click_by_id(&mut client, node_id).await?;
                    tokio::time::sleep(Duration::from_millis(400)).await;
                    println!("activated node {node_id}");
                }
                _ => unreachable!("clap requires exactly one click selector"),
            }
        }
        cli::Command::Capture {
            name,
            scale,
            output,
        } => {
            capture(&mut client, &name, scale as f32, output.as_deref()).await?;
        }
        cli::Command::Audit { family } => {
            let faults = run_audit(&mut client, family.as_deref()).await?;
            if faults > 0 {
                std::process::exit(1);
            }
        }
        cli::Command::Sweep { family } => {
            let failures = run_sweep(&mut client, family.as_deref()).await?;
            if failures > 0 {
                std::process::exit(1);
            }
        }
        /*
         * A real pointer press, as opposed to a synthesised click.
         *
         * `click` dispatches an `AgentAction::Click` at a node id, which is not
         * the path a person's mouse takes. The owner reports controls working
         * that the sweep calls dead, so the two have to be separable: if a
         * control acts under `press` and not under `click`, the finding is the
         * harness's, and every result that rests on `click` needs re-reading.
         */
        cli::Command::Press { name } => {
            let (snapshot, _) = inspect(&mut client).await?;
            // `role:name`, the form `find` and every check subject accept. A
            // bare name still matches by substring, which is ambiguous in a
            // real application: "low" also matches a Keychain warning
            // containing "allow", and the pointer went there instead.
            let (role, bare) = name.split_once(':').unwrap_or(("", name.as_str()));
            let wanted = bare.to_lowercase();
            let Some(node) = snapshot
                .nodes
                .iter()
                .filter(|n| role.is_empty() || n.role.eq_ignore_ascii_case(role))
                .filter(|n| n.name.to_lowercase().contains(&wanted))
                .filter(|n| n.visible && n.enabled)
                .find(|n| n.bounds.is_some_and(|b| b[2] > 0.0 && b[3] > 0.0))
            else {
                bail!("no visible, enabled, sized node matching {name:?}");
            };
            let b = node.bounds.unwrap();
            let (x, y) = (b[0] + b[2] / 2.0, b[1] + b[3] / 2.0);
            println!("pressing {:?} at {x:.0},{y:.0}", node.name);
            // Move first: a press at a point the document never saw hovered is
            // not what a mouse does, and hover state gates some controls.
            for phase in [PointerPhase::Move, PointerPhase::Down, PointerPhase::Up] {
                client
                    .agent(&AgentControlRequest::Act(AgentAction::Input(
                        InputCommand::Pointer {
                            phase,
                            x,
                            y,
                            button: 0,
                            modifiers: Modifiers::default(),
                        },
                    )))
                    .await?;
            }
            tokio::time::sleep(Duration::from_millis(400)).await;
            println!("pressed");
        }
        cli::Command::Cover {
            surface,
            unmapped_only,
            checks,
            max_seconds,
        } => {
            let result = tokio::time::timeout(
                Duration::from_secs(max_seconds),
                run_cover(
                    &mut client,
                    surface.as_deref(),
                    unmapped_only,
                    checks.as_deref(),
                ),
            )
            .await
            .map_err(|_| eyre!("coverage sweep exceeded {max_seconds}s"))?;
            let failures = result?;
            if failures > 0 {
                std::process::exit(1);
            }
        }
        cli::Command::Inventory {
            surface,
            require_outcomes,
            checks,
        } => {
            let failures = run_inventory(
                &mut client,
                surface.as_deref(),
                require_outcomes,
                checks.as_deref(),
            )
            .await?;
            if failures > 0 {
                std::process::exit(1);
            }
        }
        cli::Command::Qa { selector, checks } => {
            let failed = run_qa(&mut client, selector.as_deref(), checks.as_deref()).await?;
            if failed > 0 {
                std::process::exit(1);
            }
        }
        cli::Command::Reveal { name } => {
            let (snapshot, _) = inspect(&mut client).await?;
            let Some(target) = snapshot
                .nodes
                .iter()
                .find(|node| node.name.contains(&name) && node.bounds.is_some())
            else {
                bail!("no node named {name:?}");
            };
            let before = target.bounds.unwrap();
            let id = target.id;
            println!("{id} {:?} y={:.1}", target.role, before[1]);
            client
                .agent(&AgentControlRequest::Act(AgentAction::ScrollIntoView {
                    node_id: id,
                }))
                .await?;
            tokio::time::sleep(Duration::from_millis(400)).await;
            let (after_snapshot, _) = inspect(&mut client).await?;
            let after = after_snapshot
                .nodes
                .iter()
                .find(|node| node.id == id)
                .and_then(|node| node.bounds);
            match after {
                Some(b) => println!("after: y={:.1} (moved {:.1})", b[1], b[1] - before[1]),
                None => println!("after: the node is gone from the tree"),
            }
        }
        cli::Command::Key { name, count, over } => {
            // A profile may name the application's default scroller, but a
            // bare key command is also a useful protocol diagnostic. Without
            // a profile, leave the target empty and send to current focus
            // instead of panicking before the command reaches the app.
            let fallback = if over.is_empty() {
                app::AppProfile::load(None)
                    .ok()
                    .and_then(|profile| profile.transcript_region)
                    .unwrap_or_default()
            } else {
                String::new()
            };
            let over = if over.is_empty() { &fallback } else { &over };
            press_key(&mut client, &name, count as usize, over, false).await?;
        }
        cli::Command::Type { count, name } => {
            nodes(&mut client).await?;
            type_keys(&mut client, count as usize, &name).await?;
        }
        // Wheel events go to whatever the document last saw hovered, which an
        // injected pointer move does not reliably set, so they scroll nothing.
        // This asks the node's own scroll container to move, which is what
        // `scroll` should have been able to do all along.
        cli::Command::Drag { name, dy, steps } => {
            let fallback = reach::profile()
                .transcript_region
                .clone()
                .unwrap_or_default();
            let name = if name.is_empty() { &fallback } else { &name };
            let times = steps as usize;
            let (snapshot, _) = inspect(&mut client).await?;
            let Some(target) = snapshot
                .nodes
                .iter()
                .filter(|node| node.visible && node.name.contains(name))
                .filter_map(|node| node.bounds.map(|b| (node, b)))
                .max_by(|a, b| {
                    (a.1[2] * a.1[3])
                        .partial_cmp(&(b.1[2] * b.1[3]))
                        .unwrap_or(std::cmp::Ordering::Equal)
                })
                .map(|(node, _)| node.id)
            else {
                bail!("no visible node named {name:?}");
            };
            println!("scrolling node {target} by {dy} x{times}");
            for _ in 0..times {
                client
                    .agent(&AgentControlRequest::Act(AgentAction::ScrollBy {
                        node_id: target,
                        delta_x: 0.0,
                        delta_y: dy,
                    }))
                    .await?;
                sleep_pace().await;
            }
            tokio::time::sleep(Duration::from_millis(300)).await;
        }
        cli::Command::Scroll { ticks, delta, over } => {
            let fallback = reach::profile()
                .transcript_region
                .clone()
                .unwrap_or_default();
            let over = if over.is_empty() { &fallback } else { &over };
            let count = nodes(&mut client).await?;
            hover_over(&mut client, over).await?;
            report::show("before", &metrics(&mut client).await?);
            scroll(&mut client, ticks as usize, delta).await?;
            report::show("after", &metrics(&mut client).await?);
            println!("tree size during run: {count} nodes");
        }
        // No catch-all: the parser rejects an unknown command, with the list of
        // real ones, before any of this runs.
        // Dispatched before the descriptor lookup, because they launch their
        // own hosts or read only files. Listed here so the match stays
        // exhaustive and a new command cannot be forgotten.
        cli::Command::QaHosted { .. }
        | cli::Command::SweepComponents { .. }
        | cli::Command::List { .. }
        | cli::Command::Reconcile { .. } => {
            unreachable!("handled before the client connects")
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{
        InventoryClass, OutcomeStability, accumulated_hover_signatures, arrival_sample_matches,
        arrived_without_navigation, capture_node_id, declared_outcome_timeout, duplicate_dom_ids,
        generated_dom_id, hover_signature_counts, inventory_class, is_pagination_control,
        measure_ink, name_matches, named_document_is_active,
        named_document_is_active_with_permanent, named_document_opener_for, outcome_check_ids,
        outcome_verdict, pagination_advanced, painted_bounds, painted_named, pixels_change,
        pixels_hold, require_transparent_window_tint, resolved_action_target, rgb_pixels_hold,
        saved_control_node, saved_controls, selector_matches_node, stable_arrival,
        subject_belongs_to_scope, validate_surface_filter_against,
    };
    use crate::app::{AppProfile, SurfaceSpec};
    use crate::interaction::parse_key_chord;
    use crate::qa::{Check, Expect};
    use crate::target::{exact_selector_matches_node, retain_exact_candidates, viewport_for_node};
    use blitz_control_protocol::{AgentSnapshot, CapturedImage, SemanticNode, WindowComposition};
    use std::collections::HashSet;
    use std::time::Duration;

    #[test]
    fn outcome_stability_restarts_when_late_content_changes_the_document() {
        let start = tokio::time::Instant::now();
        let required = Duration::from_millis(150);
        let mut stability = OutcomeStability::default();

        assert!(!stability.observe(start, 7, true, required));
        assert!(!stability.observe(start + Duration::from_millis(100), 7, true, required));
        assert!(!stability.observe(start + Duration::from_millis(125), 8, true, required));
        assert!(!stability.observe(start + Duration::from_millis(250), 8, true, required));
        assert!(stability.observe(start + Duration::from_millis(275), 8, true, required));
    }

    #[test]
    fn failed_outcome_clears_a_partial_stability_window() {
        let start = tokio::time::Instant::now();
        let required = Duration::from_millis(100);
        let mut stability = OutcomeStability::default();

        assert!(!stability.observe(start, 3, true, required));
        assert!(!stability.observe(start + Duration::from_millis(75), 3, false, required));
        assert!(!stability.observe(start + Duration::from_millis(100), 3, true, required));
        assert!(stability.observe(start + Duration::from_millis(200), 3, true, required));
    }

    #[test]
    fn outcome_stability_waits_only_for_the_unproven_part_of_its_window() {
        let start = tokio::time::Instant::now();
        let required = Duration::from_millis(100);
        let mut stability = OutcomeStability::default();

        assert!(!stability.observe(start, 3, true, required));
        assert_eq!(stability.remaining(start, required), required);
        assert_eq!(
            stability.remaining(start + Duration::from_millis(75), required),
            Duration::from_millis(25)
        );
        assert_eq!(
            stability.remaining(start + Duration::from_millis(150), required),
            Duration::ZERO
        );
    }

    #[test]
    fn a_new_surface_owns_its_declared_outcome_but_not_a_portal() {
        let mut heading = component("Outcome per dollar", true, true);
        heading.id = 20;
        heading.role = "heading".into();
        let mut dialog = component("Welcome", true, true);
        dialog.id = 30;
        dialog.role = "dialog".into();
        let nodes = [heading, dialog];
        let analytics = HashSet::from([20]);

        assert!(subject_belongs_to_scope(
            &nodes,
            "heading:Outcome per dollar",
            &analytics
        ));
        assert!(!subject_belongs_to_scope(
            &nodes,
            "dialog:Welcome",
            &analytics
        ));
        assert!(!subject_belongs_to_scope(
            &nodes,
            "generic:Already vanished",
            &analytics
        ));
    }

    fn component(name: &str, enabled: bool, visible: bool) -> SemanticNode {
        SemanticNode {
            dom_id: Some(if name.is_empty() {
                "anonymous-component".into()
            } else {
                name.to_lowercase().replace(' ', "-")
            }),
            id: 1,
            parent: None,
            role: "button".into(),
            name: name.into(),
            value: None,
            enabled,
            visible,
            selected: false,
            bounds: Some([0.0, 0.0, 20.0, 20.0]),
            slot: None,
        }
    }

    #[test]
    fn surface_content_uses_main_viewport_while_chrome_uses_the_window() {
        let mut main = component("", true, true);
        main.id = 10;
        main.role = "main".into();
        main.bounds = Some([0.0, 58.0, 1344.0, 842.0]);

        let mut content = component("Row action", true, true);
        content.id = 11;
        content.parent = Some(main.id);
        content.bounds = Some([962.0, -3.0, 28.0, 28.0]);

        let mut chrome = component("Project tab", true, true);
        chrome.id = 12;
        chrome.bounds = Some([20.0, 15.0, 120.0, 35.0]);

        let snapshot = AgentSnapshot {
            nodes: vec![main, content, chrome],
            ..AgentSnapshot::default()
        };
        assert_eq!(viewport_for_node(&snapshot, 11), (58.0, 900.0));
        assert_eq!(viewport_for_node(&snapshot, 12), (0.0, 900.0));
    }

    #[test]
    fn pixel_stability_reports_a_changed_rendered_pixel() {
        use base64::Engine as _;

        let capture = |rgba: &[u8]| CapturedImage {
            width: 1,
            height: 1,
            rgba_base64: base64::engine::general_purpose::STANDARD.encode(rgba),
            node_id: Some(7),
        };
        let before = capture(&[20, 20, 20, 255]);
        assert!(pixels_hold(&before, &before).is_ok());
        assert_eq!(
            pixels_change(&before, &before).unwrap_err(),
            "hover left every rendered pixel unchanged"
        );

        let jitter = capture(&[19, 20, 20, 255]);
        assert!(pixels_hold(&before, &jitter).is_ok());
        assert_eq!(
            pixels_change(&before, &jitter).unwrap_err(),
            "hover left every rendered pixel unchanged"
        );

        let after = capture(&[16, 20, 20, 255]);
        assert_eq!(
            pixels_hold(&before, &after).unwrap_err(),
            "1 rendered pixel(s) changed after the pointer returned to the same state"
        );
        assert!(pixels_change(&before, &after).is_ok());

        let resized = CapturedImage {
            width: 2,
            height: 1,
            rgba_base64: base64::engine::general_purpose::STANDARD
                .encode([20, 20, 20, 255, 20, 20, 20, 255]),
            node_id: Some(7),
        };
        assert!(pixels_change(&before, &resized).is_ok());

        let transparent = capture(&[0, 0, 0, 0]);
        let resized_transparent = CapturedImage {
            width: 2,
            height: 1,
            rgba_base64: base64::engine::general_purpose::STANDARD.encode([0, 0, 0, 0, 0, 0, 0, 0]),
            node_id: Some(7),
        };
        assert_eq!(
            pixels_change(&transparent, &resized_transparent).unwrap_err(),
            "hover left every rendered pixel unchanged"
        );

        let alpha_only = capture(&[20, 20, 20, 80]);
        assert!(rgb_pixels_hold(&before, &alpha_only).is_ok());
        let visible_colour = capture(&[29, 20, 20, 255]);
        assert_eq!(
            rgb_pixels_hold(&before, &visible_colour).unwrap_err(),
            "1 visibly coloured pixel(s) changed after the first hover"
        );
    }

    #[test]
    fn raster_ink_rejects_an_empty_box_and_accepts_a_visible_mark() {
        use base64::Engine as _;

        let capture = |rgba: &[u8]| CapturedImage {
            width: 2,
            height: 2,
            rgba_base64: base64::engine::general_purpose::STANDARD.encode(rgba),
            node_id: Some(7),
        };
        let background = [20, 20, 20, 255];
        let empty = capture(&background.repeat(4));
        assert_eq!(measure_ink(&empty).unwrap().visible, 0);

        let mut marked = background.repeat(4);
        marked[0..4].copy_from_slice(&[240, 240, 240, 255]);
        assert_eq!(measure_ink(&capture(&marked)).unwrap().visible, 1);

        let transparent = capture(&[255, 255, 255, 0].repeat(4));
        assert_eq!(measure_ink(&transparent).unwrap().visible, 0);
    }

    #[test]
    fn zero_opacity_requires_the_applied_native_tint_to_be_clear() {
        let clear = WindowComposition {
            supported: true,
            surface_transparent: true,
            glass_enabled: true,
            glass_backend: Some("nativeGlass".into()),
            tint_rgba: Some([174, 50, 112, 0]),
            radius: Some(12.0),
        };
        assert!(require_transparent_window_tint(&clear).is_ok());

        let accent_sheet = WindowComposition {
            tint_rgba: Some([174, 50, 112, 255]),
            ..clear.clone()
        };
        assert!(
            require_transparent_window_tint(&accent_sheet)
                .unwrap_err()
                .contains("retains tint")
        );

        let opaque_window = WindowComposition {
            surface_transparent: false,
            ..clear
        };
        assert!(
            require_transparent_window_tint(&opaque_window)
                .unwrap_err()
                .contains("surface is opaque")
        );
    }

    #[test]
    fn capture_accepts_only_explicitly_requested_decorative_art() {
        let mut icon = component("", true, false);
        icon.id = 17;
        icon.role = "presentation".into();
        icon.bounds = Some([10.0, 10.0, 16.0, 16.0]);

        assert!(capture_node_id(&[icon.clone()], "*").is_err());
        assert_eq!(capture_node_id(&[icon], "presentation:*").unwrap(), 17);
    }

    #[test]
    fn arrival_requires_three_consecutive_painted_snapshots() {
        let mut streak = 0;
        assert!(!stable_arrival(&mut streak, true));
        assert!(!stable_arrival(&mut streak, false));
        assert!(!stable_arrival(&mut streak, true));
        assert!(!stable_arrival(&mut streak, true));
        assert!(stable_arrival(&mut streak, true));
    }

    #[test]
    fn scoped_arrival_needs_only_its_painted_marker() {
        let marker = component("Search settings", true, true);
        let settings = SurfaceSpec {
            name: "settings".into(),
            opener: "Settings".into(),
            marker: Some("Search settings".into()),
            reveal_with: Some("Search settings".into()),
        };

        assert!(arrival_sample_matches(
            &[marker],
            Some(&settings),
            "Glass opacity",
            true
        ));
    }

    #[test]
    fn key_chords_preserve_dom_key_code_and_modifiers() {
        let (key, code, modifiers) = parse_key_chord("Cmd+2").unwrap();
        assert_eq!(key, "2");
        assert_eq!(code, "Digit2");
        assert!(modifiers.meta);
        assert!(!modifiers.control);

        let (key, code, modifiers) = parse_key_chord("Ctrl+Shift+Tab").unwrap();
        assert_eq!(key, "Tab");
        assert_eq!(code, "Tab");
        assert!(modifiers.control);
        assert!(modifiers.shift);
        assert!(!modifiers.meta);
    }

    #[test]
    fn inventory_categories_are_mutually_exclusive() {
        let duplicates = HashSet::new();
        assert_eq!(
            inventory_class(
                &component("Import data", true, true),
                true,
                false,
                &duplicates
            ),
            InventoryClass::Manual
        );
        assert_eq!(
            inventory_class(
                &component("Restart application", true, true),
                false,
                true,
                &duplicates
            ),
            InventoryClass::Isolated
        );
        assert_eq!(
            inventory_class(&component("", false, false), false, false, &duplicates),
            InventoryClass::Anonymous
        );
        assert_eq!(
            inventory_class(&component("Save", false, true), false, false, &duplicates),
            InventoryClass::Disabled
        );
        assert_eq!(
            inventory_class(&component("Hidden", true, false), false, false, &duplicates),
            InventoryClass::Unreachable
        );
        assert_eq!(
            inventory_class(
                &component("Synchronize", true, true),
                false,
                false,
                &duplicates
            ),
            InventoryClass::Reachable
        );
    }

    #[test]
    fn inventory_rejects_missing_and_duplicate_dom_ids_before_exclusions() {
        let mut missing = component("Import data", true, true);
        missing.dom_id = None;
        assert_eq!(
            inventory_class(&missing, true, false, &HashSet::new()),
            InventoryClass::MissingId
        );

        let duplicate = component("Save", true, true);
        let duplicates = HashSet::from([duplicate.dom_id.clone().unwrap()]);
        assert_eq!(
            inventory_class(&duplicate, false, false, &duplicates),
            InventoryClass::DuplicateId
        );
    }

    #[test]
    fn inventory_rejects_framework_creation_order_ids() {
        assert!(generated_dom_id("cl-0-trigger"));
        assert!(generated_dom_id("7-31"));
        assert!(generated_dom_id("7-31-trigger"));
        assert!(!generated_dom_id("composer-effort-trigger"));

        let mut generated = component("Save", true, true);
        generated.dom_id = Some("cl-22-trigger".into());
        assert_eq!(
            inventory_class(&generated, false, false, &HashSet::new()),
            InventoryClass::UnstableId
        );
    }

    #[test]
    fn duplicate_dom_ids_are_counted_from_the_live_tree() {
        let first = component("Save", true, true);
        let mut second = component("Discard", true, true);
        second.dom_id = first.dom_id.clone();
        assert_eq!(
            duplicate_dom_ids(&[first.clone(), second]),
            HashSet::from([first.dom_id.unwrap()])
        );
    }

    #[test]
    fn duplicate_dom_ids_are_scoped_to_the_active_surface() {
        let first = component("Save", true, true);
        let mut retained = component("Save retained", true, true);
        retained.id = first.id + 1;
        retained.dom_id.clone_from(&first.dom_id);
        let mine = HashSet::from([first.id]);

        assert!(
            duplicate_dom_ids(
                [&first, &retained]
                    .into_iter()
                    .filter(|node| mine.contains(&node.id))
            )
            .is_empty()
        );
    }

    #[test]
    fn hover_accumulation_ignores_one_new_identity_but_rejects_extra_copies() {
        let existing = component("Hover action", true, true);
        let baseline = hover_signature_counts(std::slice::from_ref(&existing));

        let mut legitimate = component("Status mounted later", true, true);
        legitimate.id = existing.id + 1;
        let after_unique = hover_signature_counts(&[existing.clone(), legitimate]);
        assert!(accumulated_hover_signatures(&baseline, &after_unique).is_empty());

        let mut leaked = existing.clone();
        leaked.id = existing.id + 2;
        let after_leak = hover_signature_counts(&[existing, leaked]);
        assert_eq!(
            accumulated_hover_signatures(&baseline, &after_leak).len(),
            1
        );
    }

    #[test]
    fn a_retained_hidden_pager_is_not_activated() {
        let scope = HashSet::from([1]);
        let patterns = vec![" more projects".to_owned()];
        assert!(is_pagination_control(
            &component("Show 5 more projects", true, true),
            &scope,
            &patterns
        ));
        assert!(!is_pagination_control(
            &component("Show 5 more projects", true, false),
            &scope,
            &patterns
        ));
    }

    #[test]
    fn an_unchanged_pager_requires_real_tree_progress() {
        let before = HashSet::from([
            ("button".to_owned(), "Show 5 more projects".to_owned(), None),
            ("button".to_owned(), "Open project one".to_owned(), None),
        ]);
        assert!(!pagination_advanced(
            &before,
            "Show 5 more projects",
            &before,
            &component("Show 5 more projects", true, true)
        ));
        assert!(pagination_advanced(
            &before,
            "Show 5 more projects",
            &HashSet::from([
                ("button".to_owned(), "Show 5 more projects".to_owned(), None),
                ("button".to_owned(), "Open project one".to_owned(), None),
                ("button".to_owned(), "Open project two".to_owned(), None),
            ]),
            &component("Show 5 more projects", true, true)
        ));
        assert!(!pagination_advanced(
            &before,
            "Show 5 more projects",
            &HashSet::from([
                ("button".to_owned(), "Show 5 more projects".to_owned(), None),
                (
                    "button".to_owned(),
                    "Open project replacement".to_owned(),
                    None
                ),
            ]),
            &component("Show 5 more projects", true, true)
        ));
        assert!(pagination_advanced(
            &before,
            "Show 5 more projects",
            &before,
            &component("Show 3 more projects", true, true)
        ));
    }

    fn check(id: &str, click: Option<&str>, subject: &str) -> Check {
        Check {
            id: id.into(),
            group: "coverage".into(),
            what: "a rendered outcome".into(),
            open: None,
            prepare: None,
            prepare_unless: None,
            prepare_press: false,
            prepare_key: None,
            hover: None,
            hover_unless: None,
            after_prepare_hover: None,
            reveal_before_capture: None,
            setup_type_into: None,
            setup_text: None,
            click: click.map(str::to_owned),
            type_into: None,
            text: None,
            key: None,
            key_on: None,
            scroll_over: None,
            scroll_ticks: 0,
            scroll_delta: 0.0,
            compare: None,
            expect_size: None,
            expect_count: None,
            covers: Vec::new(),
            press: false,
            settle_after_ms: 0,
            outcome_timeout_ms: 0,
            stable_for_ms: 0,
            destructive: false,
            subject: subject.into(),
            expect: Expect::Paints,
        }
    }

    #[test]
    fn every_outcome_layer_uses_the_check_deadline() {
        let mut check = check("deadline", Some("Save"), "Saved");
        assert_eq!(declared_outcome_timeout(&check), Duration::from_millis(900));
        check.outcome_timeout_ms = 1_700;
        assert_eq!(
            declared_outcome_timeout(&check),
            Duration::from_millis(1_700)
        );
    }

    #[test]
    fn a_surface_filter_is_case_insensitive_and_never_succeeds_empty() {
        let surfaces = [SurfaceSpec {
            name: "settings".into(),
            opener: "Settings".into(),
            marker: Some("Search settings".into()),
            reveal_with: None,
        }];
        assert!(validate_surface_filter_against(Some("Settings"), &surfaces).is_ok());
        let error = validate_surface_filter_against(Some("missing"), &surfaces)
            .expect_err("an unknown surface must not produce a zero-row success");
        assert!(error.to_string().contains("unknown surface \"missing\""));
        assert!(error.to_string().contains("settings"));
    }

    #[test]
    fn role_qualified_coverage_does_not_credit_a_same_named_wrong_role() {
        let button = component("Rename project", true, true);
        assert!(!selector_matches_node(&button, "textbox:Rename project"));

        let mut textbox = button.clone();
        textbox.role = "textbox".into();
        assert!(selector_matches_node(&textbox, "textbox:Rename project"));
    }

    #[test]
    fn exact_name_priority_does_not_choose_a_longer_substring() {
        let restart = component("Restart", false, true);
        let proxy = component("Restart AgencyProxy", true, true);

        assert!(exact_selector_matches_node(&restart, "Restart"));
        assert!(!exact_selector_matches_node(&proxy, "Restart"));
        assert!(exact_selector_matches_node(&restart, "button:Restart"));
        assert!(!exact_selector_matches_node(&restart, "switch:Restart"));

        let mut candidates = vec![
            (&proxy, [0.0, 0.0, 20.0, 20.0]),
            (&restart, [0.0, 900.0, 20.0, 20.0]),
        ];
        retain_exact_candidates(&mut candidates, "button:Restart");
        assert_eq!(candidates.len(), 1);
        assert_eq!(candidates[0].0.name, "Restart");
        assert!(!candidates[0].0.enabled);
    }

    #[test]
    fn check_preconditions_require_a_painted_matching_role() {
        let button = component("Rename project", true, true);
        assert!(painted_named(std::slice::from_ref(&button), "Rename"));
        assert!(!painted_named(
            std::slice::from_ref(&button),
            "textbox:Rename project"
        ));

        let mut textbox = button;
        textbox.role = "textbox".into();
        assert!(painted_named(
            std::slice::from_ref(&textbox),
            "textbox:Rename project"
        ));
        textbox.bounds = Some([0.0, 0.0, 0.0, 0.0]);
        assert!(!painted_named(
            std::slice::from_ref(&textbox),
            "textbox:Rename project"
        ));
    }

    #[test]
    fn actionability_rejects_hidden_retained_menu_items_with_stale_boxes() {
        let mut retained_menu_item = component("Opus", true, false);
        assert_eq!(
            painted_bounds(&retained_menu_item),
            retained_menu_item.bounds
        );
        assert_eq!(
            resolved_action_target(std::slice::from_ref(&retained_menu_item), "menuitem:Opus"),
            None,
            "the fixture role has not yet been made a menuitem",
        );

        retained_menu_item.role = "menuitem".into();
        assert_eq!(
            resolved_action_target(std::slice::from_ref(&retained_menu_item), "menuitem:Opus"),
            None,
            "a stale box does not make a hidden retained menu item actionable",
        );

        let mut mounted_menu_item = retained_menu_item.clone();
        mounted_menu_item.visible = true;
        assert_eq!(
            resolved_action_target(std::slice::from_ref(&mounted_menu_item), "menuitem:Opus"),
            Some("Opus".into()),
        );

        mounted_menu_item.bounds = Some([0.0, 0.0, 0.0, 0.0]);
        assert!(painted_bounds(&mounted_menu_item).is_none());
    }

    #[test]
    fn only_profile_declared_documents_require_exact_activation() {
        let profile = AppProfile {
            document_openers: vec!["Fixture project".into()],
            ..AppProfile::default()
        };

        assert!(named_document_opener_for(&profile, "fixture PROJECT"));
        assert!(!named_document_opener_for(&profile, "Settings"));
    }

    #[test]
    fn a_generic_document_marker_never_skips_named_document_activation() {
        let project = SurfaceSpec {
            name: "project".into(),
            opener: crate::reach::DYNAMIC_DOCUMENT.into(),
            marker: Some("Send".into()),
            reveal_with: None,
        };
        let nodes = [component("Send", true, true)];

        assert!(!arrived_without_navigation(
            &nodes,
            Some(&project),
            "fixture row",
            true,
            false,
        ));
        assert!(arrived_without_navigation(
            &nodes,
            Some(&project),
            "fixture row",
            true,
            true,
        ));
        assert!(arrived_without_navigation(
            &nodes,
            Some(&project),
            "fixture row",
            false,
            false,
        ));
    }

    #[test]
    fn a_named_document_is_active_only_when_its_exact_tab_is_selected() {
        let mut tab = component("Fixture projectFixture project", true, true);
        assert!(!named_document_is_active(&[tab.clone()], "Fixture project"));
        tab.selected = true;
        assert!(named_document_is_active(&[tab.clone()], "Fixture project"));

        let permanent_name = "Settings".to_owned();
        let mut permanent = component(&permanent_name, true, true);
        permanent.selected = true;
        assert!(
            !named_document_is_active_with_permanent(
                &[tab, permanent],
                "Fixture project",
                &[permanent_name],
            ),
            "a selected retained document is not in front of a selected permanent surface"
        );
    }

    #[test]
    fn target_paints_resolves_a_role_qualified_click_selector() {
        let status = component("Change the status of fixture item", true, true);

        assert_eq!(
            resolved_action_target(&[status], "button:Change the status of fixture item"),
            Some("Change the status of fixture item".into()),
        );
    }

    #[test]
    fn outcome_coverage_names_only_checks_that_drive_an_enabled_control() {
        let checks = [
            check(
                "rename",
                Some("button:Rename project"),
                "textbox:Rename project",
            ),
            check("save", Some("Save"), "Saved"),
        ];
        assert_eq!(
            outcome_check_ids(&component("Rename project", true, true), &checks),
            vec!["rename"]
        );
        assert!(outcome_check_ids(&component("Delete project", true, true), &checks).is_empty());
        let mut editor = component("Rename project", true, true);
        editor.role = "textbox".into();
        assert!(outcome_check_ids(&editor, &checks).is_empty());
    }

    #[test]
    fn navigation_never_credits_a_destination_control_but_prepare_does() {
        let mut navigation = check("visit-settings", None, "heading:Settings");
        navigation.open = Some("Settings".into());
        assert!(
            outcome_check_ids(
                &component("Allow agents to update app settings", true, true),
                &[navigation]
            )
            .is_empty(),
            "opening Settings is not an outcome for an unrelated Settings control",
        );

        let mut selection = check(
            "select-permission",
            Some("menuitem:Edit"),
            "Default permission",
        );
        selection.prepare = Some("button:Default permission: Auto".into());
        assert_eq!(
            outcome_check_ids(
                &component("Default permission: Auto", true, true),
                &[selection]
            ),
            vec!["select-permission"],
            "a dropdown trigger is genuinely driven by the check that selects one of its options",
        );

        let broad = check("click-settings", Some("Settings"), "heading:Settings");
        assert!(
            outcome_check_ids(
                &component("Allow agents to update app settings", true, true),
                &[broad]
            )
            .is_empty(),
            "a convenient live substring must not become broad coverage credit",
        );
    }

    #[test]
    fn observing_disabled_is_complete_coverage_without_activation() {
        let mut disabled = component("Use the default", false, true);
        disabled.role = "button".into();
        let mut observed = check("disabled-default", None, "Use the default");
        observed.expect = Expect::Disabled;
        assert_eq!(
            outcome_check_ids(&disabled, &[observed]),
            vec!["disabled-default"]
        );
    }

    #[test]
    fn an_explicit_family_selector_credits_repeated_component_rows() {
        let mut check = check("offer-model", Some("Offer Default"), "Offer Default");
        check.covers.push("checkbox:Offer ".into());
        let mut sibling = component("Offer Sonnet", true, true);
        sibling.role = "checkbox".into();
        assert_eq!(outcome_check_ids(&sibling, &[check]), vec!["offer-model"]);
    }

    #[test]
    fn outcome_waiting_rejects_an_unchanged_refresh_indicator() {
        let mut check = check("refresh", Some("Refresh"), "Refresh generation");
        check.expect = Expect::NameChanges;
        let before = component("Refresh generation 1", true, true);
        let after = before.clone();
        assert!(outcome_verdict(&check, &[before], &[after], None, None).is_err());
    }

    #[test]
    fn outcome_waiting_accepts_the_completed_refresh_indicator() {
        let mut check = check("refresh", Some("Refresh"), "Refresh generation");
        check.expect = Expect::NameChanges;
        let before = component("Refresh generation 1", true, true);
        let after = component("Refresh generation 2", true, true);
        assert!(outcome_verdict(&check, &[before], &[after], None, None).is_ok());
    }

    #[test]
    fn value_outcome_can_belong_to_a_different_node_than_the_clicked_action() {
        let mut check = check("reset-opacity", Some("Reset to default"), "Glass opacity");
        check.expect = Expect::ValueChanges;

        let reset = component("Reset to default", true, true);
        let mut before_slider = component("Glass opacity", true, true);
        before_slider.id = 2;
        before_slider.role = "slider".into();
        before_slider.value = Some("100".into());
        let mut after_slider = before_slider.clone();
        after_slider.value = Some("55".into());

        assert!(
            outcome_verdict(
                &check,
                &[reset.clone(), before_slider],
                &[reset, after_slider],
                Some("Reset to default"),
                Some(1),
            )
            .is_ok()
        );
    }

    #[test]
    fn saved_inventory_rows_keep_quoted_control_names_with_commas() {
        let rows = saved_controls(
            "controls[1]{surface,id,role,name,classification,reason}:\n  \
             home,7,button,\"Delete alpha, beta\",reachable-unverified,none",
        )
        .expect("controls");
        let row = &rows[0];
        assert_eq!(row.surface, "home");
        assert_eq!(row.role, "button");
        assert_eq!(row.name, "Delete alpha, beta");
        assert_eq!(row.classification, "reachable-unverified");
    }

    #[test]
    fn a_saved_report_must_have_an_inventory_table() {
        assert!(saved_controls("components: 3").is_err());
        assert_eq!(
            saved_controls(
                "controls[1]{surface,id,role,name,classification,reason}:\n  home,7,button,Save,reachable-unverified,none"
            )
            .expect("controls")
            .len(),
            1
        );
    }

    #[test]
    fn nested_inventory_rows_round_trip_through_the_toon_decoder() {
        let rows = saved_controls(
            "components: 1\ncontrols[1]:\n  - surface: settings\n    id: 7\n    \
             role: switch\n    name: Enable inspection\n    \
             classification: \"isolated-unverified\"\n    reason: separate process\n    \
             checks[0]:",
        )
        .expect("nested controls");
        assert_eq!(rows.len(), 1);
        assert_eq!(rows[0].surface, "settings");
        assert_eq!(rows[0].role, "switch");
        assert_eq!(rows[0].name, "Enable inspection");
        assert_eq!(rows[0].classification, "isolated-unverified");
    }

    #[test]
    fn offline_inventory_keeps_slot_selector_credit() {
        let rows = saved_controls(
            "controls[1]{surface,id,dom_id,slot,role,name,classification,reason}:\n  \
             settings,7,theme-accent,complex-color-wheel,button,Accent,outcome-declared,matched",
        )
        .expect("controls");
        let mut check = check("accent-wheel", None, "@complex-color-wheel");
        check.covers.push("@complex-color-wheel".into());

        assert_eq!(rows[0].slot.as_deref(), Some("complex-color-wheel"));
        assert_eq!(
            outcome_check_ids(&saved_control_node(&rows[0]), &[check]),
            vec!["accent-wheel"]
        );
    }

    #[test]
    fn isolated_inventory_rows_remain_reported_without_blocking_reconciliation() {
        assert!(!super::reconciliation_gap_blocks("isolated-unverified"));
        assert!(super::reconciliation_gap_blocks("outcome-unverified"));
        assert_eq!(super::inventory_outcome_failures(1, 1, true), 0);
        assert_eq!(super::inventory_outcome_failures(3, 1, true), 2);
        assert_eq!(super::inventory_outcome_failures(3, 1, false), 0);
    }

    /// A bare word is a substring, because that is how a control is recalled.
    #[test]
    fn a_bare_pattern_is_a_substring() {
        assert!(name_matches("Rename project", "rename"));
        assert!(name_matches("Rename project", "project"));
        assert!(!name_matches("Rename project", "delete"));
    }

    #[test]
    fn a_trailing_star_anchors_the_front() {
        assert!(name_matches("chat with agent", "chat*"));
        assert!(!name_matches("open chat", "chat*"));
    }

    #[test]
    fn a_leading_star_anchors_the_end() {
        assert!(name_matches("open chat", "*chat"));
        assert!(!name_matches("chat with agent", "*chat"));
    }

    #[test]
    fn stars_at_both_ends_match_anywhere() {
        assert!(name_matches("the chat panel", "*chat*"));
        assert!(!name_matches("Rename project", "*chat*"));
    }

    /// Matching is case insensitive: a name is remembered by its words, not by
    /// the capitalisation a designer chose.
    #[test]
    fn matching_ignores_case() {
        assert!(name_matches("Rename Project", "rename project"));
        assert!(name_matches("CHAT", "chat*"));
    }

    #[test]
    fn a_lone_star_matches_everything() {
        assert!(name_matches("anything at all", "*"));
        assert!(name_matches("", "*"));
    }
}