mahbot 0.10.3

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! macOS [`Backend`] for the Computer tool: AX accessibility (observe/act),
//! CGEvent raw input, and ScreenCaptureKit capture. Non-`Send` platform objects
//! are created and dropped inside the blocking closure of the call that uses them
//! ([`with_platform`]) — never in struct state or across an await. The one path
//! outside such a closure is the grant diagnosis ([`permission_error`]), which
//! resolves the responsible application's name synchronously.
//!
//! # Foreign failures
//!
//! An Objective-C exception is not a Rust panic, so Rust cannot contain it: an
//! uncaught unwind ends the process and the panic guard aborts on it. Every async
//! [`Backend`] entry therefore runs behind [`with_platform`] — the blocking body off
//! the async worker, behind [`catching_foreign`], inside an autorelease pool — which
//! turns such an exception into a `framework-failed` failure of the call. The pool is
//! not decoration: these calls run on tokio worker threads that have none, so without
//! it every autoreleased object survives until the thread does. The AX C functions are
//! not messages, so the bindings offer no per-site wrapper: the call boundary is the
//! widest point an exception can still be caught at.
//!
//! What runs outside that boundary is guarded where it runs, and a failure there has
//! no call left to fail, so it is logged and dropped: the grant prompt thread, the
//! grant-name lookup of [`permission_error`], the main-queue exchange of
//! [`on_ax_thread`] and the completion handlers the system invokes ([`contained`]).
//!
//! Answers are checked before they are used: AX arrays are filtered to the member type
//! they are read as ([`typed_members`]), AX strings are cut at the product's cap by
//! length before a character is copied ([`attribute_text`]), and a capture size is
//! validated before it reaches the framework. Every frame copy and composite is
//! charged to the call's budget ([`core::CAPTURE_BUDGET_PIXELS`]).
//!
//! # A session that cannot receive the call
//!
//! Every API below creates input for a locked screen and reports it as delivered, and
//! a still of one is a still of the lock screen. The state is read from the system's
//! own session record before any call that needs the desktop
//! ([`desktop_unavailable_blocking`]). A running screensaver is deliberately not
//! inferred: a false refusal on a working session would cost more than the call's own failure.
//!
//! # Deadlines
//!
//! One AX exchange is bounded by the process-wide messaging timeout this backend sets
//! on the system-wide element before its first one ([`install_messaging_timeout`],
//! [`core::EXCHANGE_DEADLINE`], not shorter than the default applications rely on).
//! One [`core::Budget`] per call bounds the whole of it; the walk checks the budget
//! between exchanges because it runs inside a blocking frame no timer can interrupt.
//!
//! # Surfaces and identity
//!
//! A window target carries the identity this backend gave it when it was enumerated —
//! a retained AX window element ([`HELD_WINDOWS`]) — so a stored id resolves to that
//! very window, live; a closed or replaced one fails as `surface-gone` instead of
//! becoming another window of the same application. An app target names no window: it
//! is the application's own focused window, re-resolved per call.
//!
//! Stills are matched to ScreenCaptureKit's list by owning process and frame
//! (`find_sc_window`), never by title alone or by position, and a minimized window is
//! refused wherever its frame would be reported or used. The `screen` target is
//! composited at the densest attached display's scale.
//!
//! Input pinned to a window is raised and then verified to be the window the server
//! would deliver to ([`ensure_window_receives`]); when it could not be brought forward
//! the call fails with nothing sent.
//!
//! # What is in front, and what lies under a point
//!
//! *Which window is in front* comes from the compositor's on-screen list
//! ([`compositor_windows`]); a listing attributes that order to the windows it read and
//! counts those with no entry as unplaced. *What lies under a point* comes from the
//! system's hit test ([`window_at_point`]), not from comparing frames: the Dock's window
//! spans the whole display while its bar is only part of it. Every window the hit test
//! resolves is in the way, since a refusal the caller can retry beats a click that
//! lands somewhere unexpected. The addressed window is recognised by its frame
//! ([`core::same_frame`]), never by its title.
//!
//! # Availability
//!
//! macOS 14 is the product's floor and the ScreenCaptureKit still API is exactly that
//! old, so [`sck_available`] guards every use of it: below the floor capture degrades to
//! an honest error while observe/act keep working. Messaging a class or selector the
//! running system lacks aborts the process, so nothing newer than the floor may be
//! called unguarded.
//!
//! # Privacy grants
//!
//! A bare binary has no privacy identity: macOS attributes every grant to the
//! RESPONSIBLE PROCESS, which for this product is the terminal the daemon was started
//! from — a detached daemon keeps it. The owner grants Accessibility, input sending and
//! Screen Recording to that terminal once, and the grants survive rebuilds and
//! self-updates. Accepted consequence: every process started from the same terminal
//! shares them, and a daemon started another way has none until that thing is granted
//! too. A missing grant is requested and, when still missing, reported by
//! [`permission_error`].
//!
//! # Our own windows
//!
//! An accessibility request addressed to mahbot's own window is answered inside this
//! process, on its main thread. From a worker thread it is not a clean failure: raising
//! the window or acting on an element traps the process with SIGTRAP, while writing a
//! value waits forever. Every AX exchange aimed at our own process therefore runs on the
//! main queue and is awaited for a bounded time ([`on_ax_thread`]).

#![cfg(target_os = "macos")]
// The casts and raw-pointer borrows are inherent to the C ABI/geometry types the FFI
// exposes (u32 display ids, usize pixel dims, CGFloat floats).
#![allow(
    clippy::borrow_as_ptr,
    clippy::cast_lossless,
    clippy::cast_possible_truncation,
    clippy::cast_possible_wrap,
    clippy::cast_precision_loss,
    clippy::cast_sign_loss,
    clippy::ptr_as_ptr,
    clippy::ref_as_ptr,
    clippy::semicolon_if_nothing_returned
)]

use super::core::{
    self, AppInfo, AppListing, Backend, Capture, CaptureBudget, ElementAct, FocusedElement, Impact,
    Locator, Modifier, MouseButton, Observation, RawInput, ScrollDirection, SurfaceGeometry,
    TargetSpec, Truncation, UiNode, UnreadWindows, WindowInfo, WindowKey, WindowListing,
};
use crate::util::{UnwrapPoison, with_block_in_place};
use anyhow::anyhow;
use block2::RcBlock;
use dispatch2::{DispatchRetained, DispatchSemaphore, DispatchTime};
use objc2::AnyThread;
use objc2::rc::Retained;
use objc2_app_kit::{NSApplicationActivationPolicy, NSRunningApplication, NSWorkspace};
use objc2_application_services::{
    self, AXError, AXIsProcessTrusted, AXIsProcessTrustedWithOptions, AXUIElement, AXValue,
    AXValueType, kAXTrustedCheckOptionPrompt,
};
use objc2_core_foundation::{
    CFArray, CFBoolean, CFDictionary, CFNumber, CFRange, CFRetained, CFString, CFType, CFURL,
    CGPoint, CGRect, CGSize, ConcreteType, Type,
};
use objc2_core_graphics::{
    CGBitmapContextCreate, CGBitmapContextGetData, CGColorSpace, CGContext, CGDirectDisplayID,
    CGDisplayBounds, CGError, CGEvent, CGEventField, CGEventFlags, CGEventSource,
    CGEventSourceStateID, CGEventTapLocation, CGEventType, CGGetActiveDisplayList, CGImage,
    CGImageAlphaInfo, CGImageByteOrderInfo, CGMouseButton, CGPreflightPostEventAccess,
    CGPreflightScreenCaptureAccess, CGRectMakeWithDictionaryRepresentation,
    CGRequestPostEventAccess, CGRequestScreenCaptureAccess, CGScrollEventUnit,
    CGWindowListCopyWindowInfo, CGWindowListOption, kCGNullWindowID, kCGWindowBounds,
    kCGWindowOwnerPID,
};
use objc2_foundation::{NSArray, NSError, NSString, NSURL};
use objc2_screen_capture_kit::{
    SCContentFilter, SCScreenshotManager, SCShareableContent, SCStreamConfiguration,
    SCStreamErrorCode, SCWindow,
};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, LazyLock, Mutex, Once};
use std::time::Duration;

pub(crate) static MACOS_BACKEND: MacOsBackend = MacOsBackend;

pub(crate) struct MacOsBackend;

/// Set the AX messaging timeout, once per process, on the system-wide element: Apple
/// honours it there only, and this backend exchanges through fresh per-application
/// elements. Installed from [`with_platform`], not from the grant check.
fn install_messaging_timeout() {
    static INSTALLED: Once = Once::new();
    INSTALLED.call_once(|| {
        // SAFETY: both calls only configure this process's own accessibility client —
        // creating the system-wide element allocates it, and the timeout is a positive
        // number of seconds; no pointer outlives the statement and no other process is contacted.
        let err = unsafe {
            AXUIElement::new_system_wide()
                .set_messaging_timeout(core::EXCHANGE_DEADLINE.as_secs_f32())
        };
        if err != AXError::Success {
            tracing::warn!(
                limit_secs = core::EXCHANGE_DEADLINE.as_secs(),
                "computer use: could not set the AX messaging timeout ({err:?}) — an \
                 exchange that never answers is then unbounded"
            );
        }
    });
}

/// Run a `Result`-returning body behind Objective-C's exception handler; a Rust panic
/// passes through untouched. [`contained`] owns the order where both guards are wanted.
fn catching_foreign<T>(
    what: &str,
    f: impl FnOnce() -> Result<T, anyhow::Error>,
) -> Result<T, anyhow::Error> {
    objc2::exception::catch(std::panic::AssertUnwindSafe(f))
        .map_err(|exc| {
            let detail = exc
                .as_ref()
                .map_or_else(|| "an unnamed exception".to_string(), ToString::to_string);
            core::framework_failed(what, format!("the system raised an exception: {detail}"))
        })
        .and_then(std::convert::identity)
}

/// Both guards in the one order that works — the exception firewall inside the panic
/// guard, because a foreign exception reaching that guard aborts the process.
fn contained<T>(
    what: &str,
    body: impl FnOnce() -> Result<T, anyhow::Error>,
) -> Result<T, anyhow::Error> {
    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
        catching_foreign(what, body)
    }))
    .unwrap_or_else(|payload| {
        Err(anyhow!(
            "{what} panicked: {}",
            crate::util::panic_message(payload.as_ref())
        ))
    })
}

/// One entry into the system from the async side: the blocking body off the async worker,
/// behind the Objective-C firewall, inside an autorelease pool. See the module header.
fn with_platform<T>(
    what: &str,
    f: impl FnOnce() -> Result<T, anyhow::Error>,
) -> Result<T, anyhow::Error> {
    with_block_in_place(|| {
        objc2::rc::autoreleasepool(|_pool| {
            catching_foreign(what, || {
                install_messaging_timeout();
                f()
            })
        })
    })
}

// The objc2 bindings do not ship the kAX* string constants. `CFString::from_static_str`
// reuses the static buffer, so the fresh retain per call is cheap.

const AX_ROLE: &str = "AXRole";
const AX_TITLE: &str = "AXTitle";
const AX_VALUE: &str = "AXValue";
const AX_SUBROLE: &str = "AXSubrole";
const AX_POSITION: &str = "AXPosition";
const AX_SIZE: &str = "AXSize";
const AX_CHILDREN: &str = "AXChildren";
const AX_WINDOWS: &str = "AXWindows";
const AX_WINDOW: &str = "AXWindow";
const AX_FOCUSED_WINDOW: &str = "AXFocusedWindow";
const AX_FOCUSED: &str = "AXFocused";
/// The application's focused element — the one input reaches. Never the system-wide one.
const AX_FOCUSED_ELEMENT: &str = "AXFocusedUIElement";
const AX_PRESS: &str = "AXPress";
const AX_OPEN: &str = "AXOpen";
const AX_URL: &str = "AXURL";
const AX_RAISE: &str = "AXRaise";
const AX_MINIMIZED: &str = "AXMinimized";

#[inline]
fn axc(s: &'static str) -> CFRetained<CFString> {
    CFString::from_static_str(s)
}

// Each grant is probed cheaply, requested at most once per process (a retry loop must not
// re-open the system dialog), and reported through one actionable error naming the
// terminal macOS holds the grant against. See the module docs.

#[derive(Clone, Copy)]
enum Grant {
    Accessibility,
    Input,
    ScreenRecording,
}

impl Grant {
    /// What the grant enables, as the error and the log name it.
    fn what(self) -> &'static str {
        match self {
            Self::Accessibility => "Accessibility",
            Self::Input => "permission to send input (clicks, typing and key chords)",
            Self::ScreenRecording => "Screen Recording",
        }
    }

    /// The privacy pane the owner grants it in.
    fn pane(self) -> &'static str {
        match self {
            // macOS files synthesized input under the same grant that lets an application control others.
            Self::Accessibility | Self::Input => "Accessibility",
            Self::ScreenRecording => "Screen Recording",
        }
    }

    /// Cheap, prompt-free check of this process's own grant.
    fn held(self) -> bool {
        // SAFETY: each call only reads this process's own privacy state.
        unsafe {
            match self {
                Self::Accessibility => AXIsProcessTrusted(),
                Self::Input => CGPreflightPostEventAccess(),
                Self::ScreenRecording => CGPreflightScreenCaptureAccess(),
            }
        }
    }

    fn asked(self) -> &'static AtomicBool {
        match self {
            Self::Accessibility => &ACCESSIBILITY_ASKED,
            Self::Input => &INPUT_ASKED,
            Self::ScreenRecording => &SCREEN_RECORDING_ASKED,
        }
    }

    /// Ask the system to show its grant dialog, attributed to the responsible process (the
    /// terminal). The answer arrives outside the call — the caller re-probes — and the two CG
    /// requests wait for the owner, so the prompt runs on its own thread.
    fn request(self) {
        let (done, wait) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            // Outside the caller's firewall nothing there can fail the call: the answer is read by the
            // caller's re-probe, so a failure is logged and dropped.
            if let Err(e) = contained("ask for the grant", || {
                self.prompt();
                Ok(())
            }) {
                tracing::warn!("computer use: {e:#}");
            }
            let _ = done.send(());
        });
        let _ = wait.recv_timeout(PROMPT_WAIT);
    }

    /// The blocking half of [`Grant::request`]; the answer is read by the caller's re-probe.
    fn prompt(self) {
        // SAFETY: each call only asks the system to prompt; nothing is granted
        // behind the owner's back and no pointer outlives the call.
        unsafe {
            match self {
                Self::Accessibility => {
                    // `kAXTrustedCheckOptionPrompt: true` is what makes the call
                    // show the system's grant dialog instead of only answering.
                    let options = CFDictionary::<CFString, CFBoolean>::from_slices(
                        &[kAXTrustedCheckOptionPrompt],
                        &[CFBoolean::new(true)],
                    );
                    let _ = AXIsProcessTrustedWithOptions(Some(options.as_opaque()));
                }
                Self::Input => {
                    let _ = CGRequestPostEventAccess();
                }
                Self::ScreenRecording => {
                    let _ = CGRequestScreenCaptureAccess();
                }
            }
        }
    }
}

/// How long an unanswered grant dialog may hold the action that asked for it before the
/// call reports the grant as missing; the dialog's late answer still applies to the next call.
const PROMPT_WAIT: Duration = Duration::from_secs(20);

/// Set once this process has asked, so the owner answers each dialog once, not once per retry.
static ACCESSIBILITY_ASKED: AtomicBool = AtomicBool::new(false);
static INPUT_ASKED: AtomicBool = AtomicBool::new(false);
static SCREEN_RECORDING_ASKED: AtomicBool = AtomicBool::new(false);

/// Require `grant`, asking the system to prompt when this process has not asked yet. The
/// error is the actionable diagnosis — never a silent fallback, never a retry behind the owner.
fn ensure(grant: Grant) -> anyhow::Result<()> {
    if grant.held() {
        return Ok(());
    }
    if !grant.asked().swap(true, Ordering::Relaxed) {
        // The log carries the same facts as the error: the restart for Screen Recording included.
        tracing::warn!(
            "computer use: asking the system to prompt — {}",
            permission_error(grant)
        );
        grant.request();
    }
    if grant.held() {
        return Ok(());
    }
    Err(permission_error(grant))
}

/// The actionable diagnosis for a grant this process does not hold: what is unavailable,
/// which application to authorize, where, and what the grant needs before it applies.
fn permission_error(grant: Grant) -> anyhow::Error {
    let app = responsible_app();
    let consequence = match grant {
        Grant::Accessibility => {
            "Nothing was observed or acted on. The grant covers every process started from that \
             terminal, this daemon's own shell commands included."
        }
        Grant::Input => {
            "Clicks, typing and key chords stay unavailable; reading the accessibility tree does \
             not need this grant."
        }
        Grant::ScreenRecording => {
            "Restart mahbot before it applies — macOS gives this grant only to a newly started \
             process. Stills stay unavailable meanwhile; observe and act keep working. macOS asks \
             for this grant again periodically by design — grant it again the same way. Every \
             process started from that terminal shares it."
        }
    };
    core::permission_denied(format!(
        "{} is not granted to {app}. macOS attributes privacy grants to the terminal this \
         daemon was started from, not to the binary itself — open System Settings → Privacy & \
         Security → {} and enable {app}. {consequence}",
        grant.what(),
        grant.pane(),
    ))
}

/// The application macOS holds this daemon's grants against: the terminal it was started
/// from. The process tree no longer reaches it once the daemon detaches, but the inherited
/// environment names it (`__CFBundleIdentifier`, `TERM_PROGRAM`).
fn responsible_app() -> String {
    let non_empty = |key: &str| {
        std::env::var(key)
            .ok()
            .map(|value| value.trim().to_string())
            .filter(|value| !value.is_empty())
    };
    if let Some(bundle_id) = non_empty("__CFBundleIdentifier") {
        // The running application's localized name is what System Settings shows.
        let resolved = objc2::rc::autoreleasepool(|_pool| {
            let id = NSString::from_str(&bundle_id);
            catching_foreign("resolve the responsible application", || {
                Ok(
                    NSRunningApplication::runningApplicationsWithBundleIdentifier(&id)
                        .iter()
                        .find_map(|app| {
                            app.localizedName()
                                .map(|name| name.to_string())
                                .filter(|name| !name.is_empty())
                        }),
                )
            })
        })
        .inspect_err(|e| tracing::warn!("computer use: {e:#}"))
        .ok()
        .flatten();
        return resolved.unwrap_or(bundle_id);
    }
    non_empty("TERM_PROGRAM").unwrap_or_else(|| "the terminal you started mahbot from".to_string())
}

/// ScreenCaptureKit stills need macOS 14. Below it no SCK symbol is touched: capture reports
/// [`screen_capture_needs_14`] and the AX channel stays fully usable.
fn sck_available() -> bool {
    objc2::available!(macos = 14.0, ..)
}

fn screen_capture_needs_14() -> anyhow::Error {
    core::taxonomy_error(
        core::ERR_UNSUPPORTED,
        "screen capture needs macOS 14 or newer; observing and acting through the accessibility \
         tree keep working",
    )
}

// The thread decision (see the module header) is taken where the target process becomes
// known, never earlier from NSWorkspace state. Target-addressed exchanges raise
// [`NeedsAxThread`] from [`resolve_window`]; [`with_target`] turns it into a main-queue re-run.

const SELF_AX_WAIT: Duration = Duration::from_secs(5);

/// Marker for "this exchange resolved to mahbot itself while off the main thread";
/// [`with_target`] catches it and re-runs on the main queue. Never reaches the caller.
#[derive(Debug)]
struct NeedsAxThread;

impl std::fmt::Display for NeedsAxThread {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("mahbot's own window is answered on the main thread")
    }
}

impl std::error::Error for NeedsAxThread {}

/// Whether `err` is the main-thread marker (robust to a `.context()` layer).
fn is_ax_thread(err: &anyhow::Error) -> bool {
    err.downcast_ref::<NeedsAxThread>().is_some()
}

/// Raise [`NeedsAxThread`] when `pid` is our own process and this is not the main thread.
/// `pid` must come from the resolved target — a local getter, not an AX exchange.
fn ensure_ax_thread(pid: u32) -> Result<(), anyhow::Error> {
    if pid == std::process::id() && objc2::MainThreadMarker::new().is_none() {
        return Err(anyhow::Error::new(NeedsAxThread));
    }
    Ok(())
}

/// The wait for mahbot's own main thread ran out: an actuating call reports the possibly
/// applied request as applied-but-unconfirmed, a read as `degraded` (nothing was read).
#[derive(Debug)]
struct AxBusy(u64);

impl std::fmt::Display for AxBusy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "mahbot's own window did not answer within {}s — its main thread is busy, so the call \
             gave up instead of hanging",
            self.0
        )
    }
}

impl std::error::Error for AxBusy {}

/// A read's rendering of [`AxBusy`]: the retryable failure (an element action converts the
/// same marker into the middle outcome instead — see [`Backend::act_on_element`]).
fn degraded_read(e: anyhow::Error) -> anyhow::Error {
    match e.downcast_ref::<AxBusy>() {
        Some(busy) => core::taxonomy_error(core::ERR_DEGRADED, format!("{busy}; retry the read")),
        None => e,
    }
}

/// Run one accessibility exchange on the main thread when `pid` is mahbot itself, on the
/// calling thread otherwise; a busy main thread gives up as [`AxBusy`] after [`SELF_AX_WAIT`].
fn on_ax_thread<T: Send + 'static>(
    pid: u32,
    f: impl FnOnce() -> Result<T, anyhow::Error> + Send + 'static,
) -> Result<T, anyhow::Error> {
    if pid != std::process::id() || objc2::MainThreadMarker::new().is_some() {
        return f();
    }
    let (tx, rx) = std::sync::mpsc::sync_channel(1);
    dispatch2::DispatchQueue::main().exec_async(move || {
        let result = contained("access to mahbot's own window", f);
        let _ = tx.send(result);
    });
    match rx.recv_timeout(SELF_AX_WAIT) {
        Ok(result) => result,
        Err(_) => Err(anyhow::Error::new(AxBusy(SELF_AX_WAIT.as_secs()))),
    }
}

/// Run an exchange aimed at `target`, on the main thread when it resolves to mahbot's own
/// process. The exchange raises [`NeedsAxThread`] before it does anything.
fn with_target<T: Send + 'static>(
    target: &TargetSpec,
    f: impl Fn(&TargetSpec) -> Result<T, anyhow::Error> + Send + 'static,
) -> Result<T, anyhow::Error> {
    match f(target) {
        Err(e) if is_ax_thread(&e) => {
            let owned = target.clone();
            on_ax_thread(std::process::id(), move || f(&owned))
        }
        other => other,
    }
}

fn attribute_value(el: &AXUIElement, attr: &CFString) -> Result<CFRetained<CFType>, AXError> {
    let mut value: *const CFType = std::ptr::null();
    // SAFETY: `value` points to valid storage the binding fills on success.
    let err = unsafe {
        el.copy_attribute_value(
            attr,
            std::ptr::NonNull::new(&mut value as *mut *const CFType).unwrap(),
        )
    };
    if err != AXError::Success {
        return Err(err);
    }
    // SAFETY: AXUIElementCopyAttributeValue returns a +1 retained pointer (Create
    // rule); null indicates a missing value.
    match std::ptr::NonNull::new(value.cast_mut()) {
        Some(p) => Ok(unsafe { CFRetained::from_raw(p) }),
        None => Err(AXError::NoValue),
    }
}

/// Read an AX string attribute, copying at most `max` characters of it. The framework has
/// already materialised the whole value, so the cap is on what this copies and keeps: the
/// length decides before a single unit is read out.
fn attribute_text(el: &AXUIElement, attr: &CFString, max: usize) -> Option<String> {
    let val = attribute_value(el, attr).ok()?;
    let string = val.downcast_ref::<CFString>()?;
    let length = string.length();
    if length <= 0 {
        return Some(String::new());
    }
    // Two UTF-16 units per character at worst, plus one character past the cap so a
    // string that is merely longer still reads as cut.
    let wanted = length.min(2 * (max as isize + 2));
    let mut units = vec![0u16; wanted as usize];
    // SAFETY: `units` holds exactly `wanted` UTF-16 units, the number of units asked
    // for, and `wanted` is at most the string's own length.
    unsafe {
        string.characters(CFRange::new(0, wanted), units.as_mut_ptr());
    }
    Some(String::from_utf16_lossy(&units))
}

/// A string used as a label rather than content — a role, a name — kept to
/// [`core::MAX_NAME_CHARS`] with an ellipsis ([`core::cap_label`]). Windows match on frames.
fn attribute_name(el: &AXUIElement, attr: &CFString) -> Option<String> {
    attribute_text(el, attr, core::MAX_NAME_CHARS).map(|text| core::cap_label(&text))
}

fn attribute_point(el: &AXUIElement, attr: &CFString) -> Option<CGPoint> {
    let val = attribute_value(el, attr).ok()?;
    let axval = val.downcast_ref::<AXValue>()?;
    let mut p = CGPoint::new(0.0, 0.0);
    // SAFETY: `axval` is an AXValue; the destination matches AXValueType::CGPoint.
    let ok = unsafe {
        axval.value(
            AXValueType::CGPoint,
            std::ptr::NonNull::new(&mut p as *mut _ as *mut _).unwrap(),
        )
    };
    ok.then_some(p)
}

fn attribute_size(el: &AXUIElement, attr: &CFString) -> Option<CGSize> {
    let val = attribute_value(el, attr).ok()?;
    let axval = val.downcast_ref::<AXValue>()?;
    let mut s = CGSize::new(0.0, 0.0);
    // SAFETY: `axval` is an AXValue; the destination matches AXValueType::CGSize.
    let ok = unsafe {
        axval.value(
            AXValueType::CGSize,
            std::ptr::NonNull::new(&mut s as *mut _ as *mut _).unwrap(),
        )
    };
    ok.then_some(s)
}

fn attribute_bool(el: &AXUIElement, attr: &CFString) -> Option<bool> {
    let val = attribute_value(el, attr).ok()?;
    Some(val.downcast_ref::<CFBoolean>()?.value())
}

/// The members of `array` that really are `T`: each member is checked against the type it is
/// used as, and one of another type is skipped rather than read as a `T`.
fn typed_members<T: ConcreteType>(array: &CFArray) -> Vec<CFRetained<T>> {
    // SAFETY: an array's members are Core Foundation objects, and `CFType` is the
    // root of them all — the cast makes no claim about a member's own type, which
    // is what `downcast` below checks.
    let members: CFRetained<CFArray<CFType>> =
        unsafe { CFRetained::cast_unchecked(array.retain()) };
    members
        .iter()
        .filter_map(|member| member.downcast::<T>().ok())
        .collect()
}

/// Raw (AX-prefixed) action names. The AX error is the caller's to report — a tree walk
/// degrades to no actions, while acting must not turn a failed read into "no press action".
/// `Ok(None)` is the third answer: the system replied with something that is not a list of
/// names, so the caller knows it learned nothing.
fn raw_action_names(el: &AXUIElement) -> Result<Option<Vec<String>>, AXError> {
    let mut names: *const CFArray = std::ptr::null();
    // SAFETY: `names` points to valid storage the binding fills on success.
    let err = unsafe {
        el.copy_action_names(std::ptr::NonNull::new(&mut names as *mut *const CFArray).unwrap())
    };
    if err != AXError::Success {
        return Err(err);
    }
    // SAFETY: AXUIElementCopyActionNames returns a +1 retained Core Foundation
    // object (Create rule); "Core Foundation object" is all this claims — the
    // `downcast` below checks which kind it really is. Null indicates an element
    // with no actions.
    let Some(raw) = std::ptr::NonNull::new(names.cast_mut()) else {
        return Ok(Some(Vec::new()));
    };
    // SAFETY: as above — `from_raw` takes over the +1 reference, `cast_unchecked`
    // only widens it to the root type, and the type check follows.
    let object: CFRetained<CFType> =
        unsafe { CFRetained::cast_unchecked(CFRetained::from_raw(raw)) };
    // Not an array is not a list of names: it taught us nothing, like an array with no usable member.
    let Ok(array) = object.downcast::<CFArray>() else {
        return Ok(None);
    };
    let names: Vec<String> = typed_members::<CFString>(&array)
        .iter()
        .map(ToString::to_string)
        .collect();
    // An empty array really is "no actions"; a non-empty one with nothing usable taught us nothing.
    if names.is_empty() && !array.is_empty() {
        return Ok(None);
    }
    Ok(Some(names))
}

fn attribute_children(el: &AXUIElement) -> Vec<CFRetained<AXUIElement>> {
    let Ok(val) = attribute_value(el, &axc(AX_CHILDREN)) else {
        return Vec::new();
    };
    let Ok(array) = val.downcast::<CFArray>() else {
        return Vec::new();
    };
    typed_members::<AXUIElement>(&array)
}

fn normalize_action_name(name: &str) -> String {
    name.strip_prefix("AX").unwrap_or(name).to_lowercase()
}

/// Arms shared by [`ax_error`] and [`ax_window_error`]; `None` falls through to the caller.
fn ax_error_shared(err: AXError, ctx: impl std::fmt::Display) -> Option<anyhow::Error> {
    match err {
        AXError::CannotComplete => Some(core::taxonomy_error(
            core::ERR_DEGRADED,
            format!("transient AX failure, retry: {ctx}"),
        )),
        AXError::InvalidUIElement => Some(core::taxonomy_error(
            core::ERR_STALE_ELEMENT,
            format!("window closed or changed — re-enumerate: {ctx}"),
        )),
        AXError::APIDisabled => Some(permission_error(Grant::Accessibility)),
        _ => None,
    }
}

fn ax_error(err: AXError, ctx: impl std::fmt::Display) -> anyhow::Error {
    if let Some(mapped) = ax_error_shared(err, &ctx) {
        return mapped;
    }
    match err {
        AXError::AttributeUnsupported
        | AXError::ActionUnsupported
        | AXError::NoValue
        | AXError::NotImplemented
        | AXError::ParameterizedAttributeUnsupported => core::taxonomy_error(
            core::ERR_UNSUPPORTED,
            format!(
                "unsupported accessibility operation: {ctx} — act on it by coordinates or use \
                 another element"
            ),
        ),
        // Plain (non-taxonomy) errors — not actionable by the model.
        _ => anyhow!("AX error {err:?}: {ctx}"),
    }
}

/// Window-level error mapping (CannotComplete/InvalidUIElement are fatal).
fn ax_window_error(err: AXError, ctx: impl std::fmt::Display) -> anyhow::Error {
    ax_error_shared(err, &ctx).unwrap_or_else(|| {
        core::taxonomy_error(
            core::ERR_NOT_MATCHED,
            format!("no windows enumerated — re-enumerate: {ctx}"),
        )
    })
}

/// True when the element is a secure (e.g. password) field. macOS reports the marker in
/// either AXRole or AXSubrole, so both are checked — one predicate keeps the value-masking
/// in [`walk_element`] and the SetValue refusal in [`set_element_value`] in agreement.
fn is_secure_field(role: &str, subrole: Option<&str>) -> bool {
    role.to_lowercase().contains("secure")
        || subrole.is_some_and(|s| s.to_lowercase().contains("secure"))
}

/// One node and its subtree, read within `budget`. `Ok(None)` is a node not read because the
/// node ceiling was reached; `Err` is the call's budget spent — the only failure a walk raises.
fn walk_element(
    element: &AXUIElement,
    origin: (f64, f64),
    depth: usize,
    handles: &mut Vec<CFRetained<AXUIElement>>,
    nodes: &mut usize,
    truncation: &mut Truncation,
    budget: &core::Budget,
) -> anyhow::Result<Option<UiNode>> {
    budget.check()?;
    if *nodes >= core::MAX_TREE_NODES {
        truncation.hit_node_ceiling(core::MAX_TREE_NODES);
        return Ok(None);
    }
    *nodes += 1;
    handles.push(element.retain());

    // Each group below is one or two AX exchanges and the budget is re-checked between them, so
    // a target that stalls across a node's own reads cannot spend the whole walk's budget there.
    budget.check()?;
    let role = attribute_name(element, &axc(AX_ROLE)).unwrap_or_else(|| "unknown".to_string());
    // Never read a value out of a secure element: check the subrole (or role) for "secure"
    // before pulling the value.
    let subrole = attribute_name(element, &axc(AX_SUBROLE));
    budget.check()?;
    let value = if is_secure_field(&role, subrole.as_deref()) {
        None
    } else {
        attribute_text(element, &axc(AX_VALUE), core::MAX_VALUE_CHARS)
            .map(|value| truncation.keep_value(&value))
    };
    budget.check()?;
    let frame = match (
        attribute_point(element, &axc(AX_POSITION)),
        attribute_size(element, &axc(AX_SIZE)),
    ) {
        (Some(p), Some(s)) => Some((p.x - origin.0, p.y - origin.1, s.width, s.height)),
        _ => None,
    };
    budget.check()?;
    // A failed read only leaves the node's actions absent: the walk degrades, acting on it must not.
    let actions = raw_action_names(element)
        .ok()
        .flatten()
        .unwrap_or_default()
        .iter()
        .map(|a| normalize_action_name(a))
        .collect();
    budget.check()?;
    let focused = attribute_bool(element, &axc(AX_FOCUSED)).unwrap_or(false);

    let mut children = Vec::new();
    if depth < core::MAX_TREE_DEPTH {
        budget.check()?;
        for child in attribute_children(element) {
            if let Some(child_node) = walk_element(
                &child,
                origin,
                depth + 1,
                handles,
                nodes,
                truncation,
                budget,
            )? {
                children.push(child_node);
            }
        }
    } else if !attribute_children(element).is_empty() {
        // Only a node that has a subtree is a cut, so a leaf at the ceiling is not a truncation.
        truncation.cut_depth(core::MAX_TREE_DEPTH);
    }
    Ok(Some(UiNode {
        role,
        name: attribute_text(element, &axc(AX_TITLE), core::MAX_NAME_CHARS)
            .map(|name| truncation.keep_name(&name)),
        value,
        frame,
        actions,
        focused,
        children,
    }))
}

/// Build the accessibility tree: the root node, a pre-order-aligned `Vec` of platform handles
/// (used by `act_on_element`) and the ceilings the walk hit.
fn build_tree(
    root: &AXUIElement,
    origin: (f64, f64),
    budget: &core::Budget,
) -> anyhow::Result<(UiNode, Vec<CFRetained<AXUIElement>>, Truncation)> {
    let mut handles = Vec::new();
    let mut nodes = 0usize;
    let mut truncation = Truncation::default();
    let node = walk_element(
        root,
        origin,
        0,
        &mut handles,
        &mut nodes,
        &mut truncation,
        budget,
    )?
    .ok_or_else(|| {
        // The root is first, so only its own reads can leave it unread; an empty tree reads as no content.
        core::taxonomy_error(
            core::ERR_DEGRADED,
            format!(
                "{} did not answer for its accessibility root, so nothing was read — {}",
                budget.target(),
                core::unanswered_next_step()
            ),
        )
    })?;
    Ok((node, handles, truncation))
}

/// The application a target points at: the name it carries, else the resolved application's own.
fn resolved_app_name(target: &TargetSpec, app: &AXUIElement) -> Result<String, anyhow::Error> {
    match target.app() {
        Some((_, name)) => Ok(name.to_string()),
        None => Ok(app_display_name(app_pid(app)?, app)),
    }
}

/// The label of the surface a call resolved, for the failures that follow the reads naming
/// it. The title is passed in, so a caller that already read it does not read it again.
fn resolved_surface_label(
    target: &TargetSpec,
    app: &AXUIElement,
    title: Option<&str>,
) -> Result<String, anyhow::Error> {
    Ok(core::surface_label(&resolved_app_name(target, app)?, title))
}

fn observe_blocking(target: &TargetSpec) -> Result<Observation, anyhow::Error> {
    // One clock for the whole call, resolution and the reads that name the surface included.
    let mut budget = core::Budget::new(core::OBSERVE_BUDGET, "observation", target.describe());
    let (window, app) = resolve_window(target, &budget)?;
    budget.check()?;
    // The identity is read before the reads that can go unanswered: a failure has to name the window.
    let app_name = resolved_app_name(target, &app)?;
    // The header title is a name, not a label: read past the cap so a cut is counted.
    let title = attribute_text(&window, &axc(AX_TITLE), core::MAX_NAME_CHARS);
    let label = core::name_surface(&mut budget, &app_name, title.as_deref());
    // A minimized window's frame is the one it had before it was minimized: refuse rather than
    // describe a surface that is not on screen.
    refuse_minimized(&window)?;
    budget.check()?;
    let origin =
        window_origin(&window).map_err(|_| core::unanswered(&label, "for its position"))?;
    let surface =
        window_frame(&window, &budget).map_err(|_| core::unanswered(&label, "for its frame"))?;
    budget.check()?;
    let (root, _handles, mut truncation) = build_tree(&window, origin, &budget)?;
    // The title is a name like any node's, so a cut one is counted in the same header ceiling.
    let title = title.map(|title| truncation.keep_name(&title));
    Ok(Observation {
        truncation,
        app_name,
        window_title: title,
        surface,
        root,
    })
}

/// A retained AX window element, addressed by the token that names it in the target registry.
/// The element itself is the identity — it answers with the window's live title, frame and
/// process. The owner is the agent that enumerated it, so a session drops its own handles only.
struct HeldWindow {
    element: CFRetained<AXUIElement>,
    owner: String,
}

// SAFETY: an AX exchange is not thread-safe, so an element is only ever used on
// the thread that owns it — the tool serializes every call through one action
// lock, and exchanges aimed at our own windows run on the main queue under a
// bounded wait. The wrapper makes the map a static; it does not make concurrent
// AX calls safe, and none are performed.
unsafe impl Send for HeldWindow {}

static HELD_WINDOWS: LazyLock<Mutex<HashMap<u64, HeldWindow>>> =
    LazyLock::new(|| Mutex::new(HashMap::new()));

static NEXT_WINDOW_TOKEN: AtomicU64 = AtomicU64::new(1);

/// The identity of `window`: the token it already holds, else a fresh one. `CFEqual` compares
/// elements by the object they address, so the same window is recognised across enumerations.
/// Tokens are per agent, so a session's reset can never drop a handle another session's id
/// resolves through; a handle is dropped when a call confirms its window gone, or with the
/// session. `owner` is read by the caller — never inside a main-queue exchange.
fn window_key(window: &AXUIElement, owner: &str) -> WindowKey {
    let mut held = HELD_WINDOWS.lock().unwrap_poison();
    let known = held
        .iter()
        .find(|(_, existing)| existing.owner == owner && &*existing.element == window)
        .map(|(token, _)| *token);
    let token = known.unwrap_or_else(|| {
        let token = NEXT_WINDOW_TOKEN.fetch_add(1, Ordering::Relaxed);
        held.insert(
            token,
            HeldWindow {
                element: window.retain(),
                owner: owner.to_string(),
            },
        );
        token
    });
    WindowKey::new(format!("ax:{token}"))
}

/// The window a stored key names, refusing rather than substituting another one. A token that
/// no longer resolves, or an element whose window is gone, is `surface-gone`; a handle whose
/// window is confirmed gone is dropped here.
fn window_by_key(
    key: &WindowKey,
    app_name: &str,
) -> Result<CFRetained<AXUIElement>, anyhow::Error> {
    let token = key
        .as_str()
        .strip_prefix("ax:")
        .and_then(|raw| raw.parse::<u64>().ok())
        .ok_or_else(|| core::surface_gone(app_name))?;
    let window = {
        let held = HELD_WINDOWS.lock().unwrap_poison();
        held.get(&token)
            .map(|held| held.element.retain())
            .ok_or_else(|| core::surface_gone(app_name))?
    };
    // A retained element outlives its window: reading it tells the two apart. Only the framework's
    // own "no longer an element" answer is a gone window — a timeout is a live window that stalled.
    match attribute_value(&window, &axc(AX_ROLE)) {
        Ok(_) => Ok(window),
        Err(AXError::InvalidUIElement) => {
            HELD_WINDOWS.lock().unwrap_poison().remove(&token);
            Err(core::surface_gone(app_name))
        }
        Err(_) => Err(core::unanswered(
            &core::surface_label(app_name, None),
            "for its role",
        )),
    }
}

/// Drop every window `agent` holds: its session ended, and so did the ids it resolves.
pub(crate) fn forget_agent_windows(agent: &str) {
    let mut held = HELD_WINDOWS.lock().unwrap_poison();
    held.retain(|_, entry| entry.owner != agent);
}

/// Refuse a minimized window: it has no visible pixels, and its frame is its pre-minimized one.
fn refuse_minimized(window: &AXUIElement) -> Result<(), anyhow::Error> {
    if !attribute_bool(window, &axc(AX_MINIMIZED)).unwrap_or(false) {
        return Ok(());
    }
    Err(core::minimized_window(
        &window_title(window).unwrap_or_default(),
    ))
}

// The two questions the module header names, each answered by the system that can answer it:
// the order by the compositor's on-screen list, what lies under a point by the hit test.

fn compositor_number(dict: &CFDictionary<CFString, CFType>, key: &CFString) -> Option<i64> {
    dict.get(key)?.downcast_ref::<CFNumber>()?.as_i64()
}

fn compositor_frame(
    dict: &CFDictionary<CFString, CFType>,
    key: &CFString,
) -> Option<SurfaceGeometry> {
    let bounds = dict.get(key)?;
    let bounds = bounds.downcast_ref::<CFDictionary>()?;
    let mut rect = CGRect::ZERO;
    // SAFETY: `bounds` is a CFDictionary of the kind CGRectMakeWithDictionaryRepresentation
    // documents, and `rect` is a valid out-pointer.
    let ok = unsafe { CGRectMakeWithDictionaryRepresentation(Some(bounds), &raw mut rect) };
    ok.then_some(SurfaceGeometry {
        x: rect.origin.x,
        y: rect.origin.y,
        width: rect.size.width,
        height: rect.size.height,
    })
}

/// The windows the window server has on screen, front to back, as the process that owns each and
/// its frame. `None` when the list itself cannot be read: a listing then says it could not
/// attribute an order instead of inventing one. Every level is kept, since a popover, menu or
/// floating panel sits above the normal level; an entry with no readable process or bounds is
/// dropped.
fn compositor_windows() -> Option<Vec<(u32, SurfaceGeometry)>> {
    // SAFETY: both statics are plain CFString constants the framework owns.
    let (owner, bounds) = unsafe { (kCGWindowOwnerPID, kCGWindowBounds) };
    let list = CGWindowListCopyWindowInfo(
        CGWindowListOption::OptionOnScreenOnly | CGWindowListOption::ExcludeDesktopElements,
        kCGNullWindowID,
    )?;
    let mut out = Vec::new();
    // SAFETY: an array's members are Core Foundation objects and `CFType` is the root of
    // them all — the cast makes no claim about a member's own type, which the `downcast`
    // below checks.
    let members: CFRetained<CFArray<CFType>> = unsafe { CFRetained::cast_unchecked(list) };
    for entry in members.iter() {
        let Ok(dict) = entry.downcast::<CFDictionary>() else {
            continue;
        };
        // SAFETY: a dictionary's generic parameters are a phantom type over one layout,
        // and the compositor's documented keys are CFStrings whose values are CFTypes —
        // exactly what the handle is told to expect before it is read.
        let dict: CFRetained<CFDictionary<CFString, CFType>> =
            unsafe { CFRetained::cast_unchecked(dict) };
        let pid = compositor_number(&dict, owner).and_then(|pid| u32::try_from(pid).ok());
        if let (Some(pid), Some(frame)) = (pid, compositor_frame(&dict, bounds)) {
            out.push((pid, frame));
        }
    }
    Some(out)
}

/// Attribute the compositor's front-to-back order to the windows a listing just read: a listed
/// window matches the first compositor entry with its process and frame, and its rank is that
/// window's place among the windows that found one. A window with no entry — minimized, on
/// another space — is counted as unplaced rather than declaring the whole order unknown. The
/// comparison is a frame one, within [`core::POSITION_TOLERANCE`].
fn attribute_order(windows: &mut [WindowInfo]) -> core::WindowOrder {
    let Some(compositor) = compositor_windows() else {
        // The list could not be read this time: nothing was ranked, and the answer says the read
        // failed — never that no window has a place.
        return core::WindowOrder::Unread;
    };
    // (compositor position, index among the listed windows) for every listed window.
    let mut matched = Vec::with_capacity(windows.len());
    let mut taken = vec![false; compositor.len()];
    for (index, window) in windows.iter().enumerate() {
        let Some(pid) = window.app_pid else {
            continue;
        };
        // Each compositor entry stands for at most one window, so equal titles and frames still rank.
        let Some(position) =
            compositor
                .iter()
                .enumerate()
                .position(|(index, (entry_pid, frame))| {
                    !taken[index] && *entry_pid == pid && core::same_frame(frame, &window.surface)
                })
        else {
            continue;
        };
        taken[position] = true;
        matched.push((position, index));
    }
    // Ranks are places among the windows this listing read, not indices into the whole compositor
    // list: a frontmost listed window is #1 even when unlisted windows sit ahead of it.
    matched.sort_unstable();
    for (rank, (_, index)) in matched.iter().enumerate() {
        windows[*index].rank = Some(rank + 1);
    }
    if matched.len() == windows.len() {
        core::WindowOrder::All
    } else {
        core::WindowOrder::Partial
    }
}

/// The window a screen point lies over, from the system's own hit test, and through it the
/// application and window it belongs to. `None` when the hit test cannot answer, so the click
/// goes and its answer says the point could not be checked; the window server's backstop
/// surface is not an accessibility element and never answers here. The frame is read from the
/// element's `AXWindow`, so the two are compared in one coordinate system.
fn window_at_point(point: (f64, f64), budget: &core::Budget) -> Option<core::WindowAtPoint> {
    budget.check().ok()?;
    let mut element: *const AXUIElement = std::ptr::null();
    // SAFETY: the system-wide element is this process's own accessibility client, the point
    // is passed by value, and `element` is a live local the call fills with a +1 retained
    // object on success.
    let err = unsafe {
        AXUIElement::new_system_wide().copy_element_at_position(
            point.0 as f32,
            point.1 as f32,
            std::ptr::NonNull::new(&mut element as *mut *const AXUIElement).unwrap(),
        )
    };
    if err != AXError::Success {
        return None;
    }
    // SAFETY: a successful copy returns a +1 retained element (Create rule).
    let element = unsafe { CFRetained::from_raw(std::ptr::NonNull::new(element.cast_mut())?) };
    let pid = app_pid(&element).ok()?;
    let app_name = app_name_for_pid(pid);
    let window = attribute_value(&element, &axc(AX_WINDOW))
        .ok()
        .and_then(|value| value.downcast::<AXUIElement>().ok());
    let (title, frame) = match window {
        Some(window) => (
            window_title(&window).unwrap_or_default(),
            window_frame(&window, budget).ok(),
        ),
        None => (String::new(), None),
    };
    Some(core::WindowAtPoint {
        app_pid: Some(pid),
        app_name,
        title,
        frame,
    })
}

/// The application name a pid belongs to, as every other answer spells it.
fn app_name_for_pid(pid: u32) -> String {
    NSWorkspace::sharedWorkspace()
        .runningApplications()
        .iter()
        .find(|app| app.processIdentifier() == pid as i32)
        .and_then(|app| app.localizedName().map(|name| name.to_string()))
        .filter(|name| !name.is_empty())
        // The list can name a process CoreGraphics reports without a running application (a helper, a
        // system surface): the pid is what the caller can match against, so it is never guessed at.
        .unwrap_or_else(|| format!("pid {pid}"))
}

/// The frontmost application's AX element, resolved through `NSWorkspace`. The system-wide
/// element's own focus attributes are deliberately not used: a process holding its grant
/// through the terminal gets `kAXErrorCannotComplete` from them.
fn frontmost_app() -> Result<CFRetained<AXUIElement>, anyhow::Error> {
    let app = NSWorkspace::sharedWorkspace()
        .frontmostApplication()
        .ok_or_else(|| {
            core::taxonomy_error(
                core::ERR_NOT_MATCHED,
                "no frontmost application — enumerate apps/windows first",
            )
        })?;
    // SAFETY: AXUIElementCreateApplication never returns null; a pid that went
    // away surfaces as InvalidUIElement on the first attribute read.
    Ok(unsafe { AXUIElement::new_application(app.processIdentifier()) })
}

fn focused_window_of_app(app: &AXUIElement) -> Option<CFRetained<AXUIElement>> {
    attribute_value(app, &axc(AX_FOCUSED_WINDOW))
        .ok()?
        .downcast::<AXUIElement>()
        .ok()
}

/// The element holding an application's focus, by kind and name. `None` when it cannot be read —
/// no focused element, a target that stops answering, or our own interface reached from a
/// worker thread. The one budget bounds the whole read, which runs on every action's answer.
fn focused_element_of_app(app: &AXUIElement, budget: &core::Budget) -> Option<FocusedElement> {
    if ensure_ax_thread(app_pid(app).ok()?).is_err() {
        return None;
    }
    budget.check().ok()?;
    let element = attribute_value(app, &axc(AX_FOCUSED_ELEMENT))
        .ok()?
        .downcast::<AXUIElement>()
        .ok()?;
    budget.check().ok()?;
    let kind = attribute_name(&element, &axc(AX_ROLE)).unwrap_or_default();
    // The name is exactly what the tree prints for the element (its title), so the report matches it.
    let name = attribute_name(&element, &axc(AX_TITLE));
    Some(FocusedElement { kind, name })
}

/// The application in front, as its process and the workspace's name for it. One read, so the
/// `[focused]` mark and the "frontmost application" line can never name different applications.
fn frontmost_identity() -> Option<(u32, String)> {
    let app = NSWorkspace::sharedWorkspace().frontmostApplication()?;
    let name = app
        .localizedName()
        .map(|name| name.to_string())
        .filter(|name| !name.is_empty())?;
    Some((app.processIdentifier() as u32, name))
}

fn running_app_pid(name: &str) -> Option<u32> {
    let needle = name.to_lowercase();
    NSWorkspace::sharedWorkspace()
        .runningApplications()
        .iter()
        .find(|app| {
            app.activationPolicy() == NSApplicationActivationPolicy::Regular
                && app
                    .localizedName()
                    .is_some_and(|n| n.to_string().to_lowercase() == needle)
        })
        .map(|app| app.processIdentifier() as u32)
}

/// App display name for a pid: the workspace's authoritative localized name, with an AXTitle
/// fallback when the lookup misses — an AXTitle read on the application is usually empty.
fn app_display_name(pid: u32, app: &AXUIElement) -> String {
    NSWorkspace::sharedWorkspace()
        .runningApplications()
        .iter()
        .find(|a| a.processIdentifier() == pid as i32)
        .and_then(|a| a.localizedName().map(|n| n.to_string()))
        .filter(|n| !n.is_empty())
        .unwrap_or_else(|| attribute_name(app, &axc(AX_TITLE)).unwrap_or_default())
}

/// Whether the application is still running, from the workspace's record: by pid when the id
/// carries one, else by localized name. An `a` id whose application quit says so.
fn app_running(pid: Option<u32>, name: &str) -> bool {
    match pid {
        Some(pid) => NSWorkspace::sharedWorkspace()
            .runningApplications()
            .iter()
            .any(|app| app.processIdentifier() == pid as i32),
        None => running_app_pid(name).is_some(),
    }
}

fn app_element(pid: Option<u32>, name: &str) -> Result<CFRetained<AXUIElement>, anyhow::Error> {
    let pid = match pid {
        Some(p) => p,
        None => {
            running_app_pid(name).ok_or_else(|| core::app_absent(name, core::AppAbsence::Quit))?
        }
    };
    // SAFETY: `pid` is a running app (or stale); AXUIElementCreateApplication
    // always returns a non-null element — attribute reads surface InvalidUIElement.
    Ok(unsafe { AXUIElement::new_application(pid as libc::pid_t) })
}

/// An application's windows. A target that stopped answering is named as such: the generic
/// "transient AX failure, retry" would send the model re-enumerating a hung application.
fn read_windows(
    app: &AXUIElement,
    app_name: &str,
) -> Result<Vec<CFRetained<AXUIElement>>, anyhow::Error> {
    let val = attribute_value(app, &axc(AX_WINDOWS)).map_err(|e| {
        if e == AXError::CannotComplete {
            core::unanswered(&core::surface_label(app_name, None), "for its window list")
        } else {
            ax_window_error(e, "enumerate windows")
        }
    })?;
    let array: CFRetained<CFArray> = val
        .downcast::<CFArray>()
        .map_err(|_| anyhow!("AXWindows was not a CFArray"))?;
    Ok(typed_members::<AXUIElement>(&array))
}

/// One application's listed windows: the AX window array plus each window's frame, title and
/// identity. A window with neither a title nor a frame is not a surface and is dropped. The
/// budget is checked before the window list and before every window. The listing knows the
/// target process without resolving a `TargetSpec`, so it calls [`on_ax_thread`] itself.
fn windows_of_app(
    pid: u32,
    app_name: &str,
    owner: &str,
    budget: &core::Budget,
    mark_focused: bool,
) -> Result<Vec<WindowInfo>, anyhow::Error> {
    // SAFETY: `pid` is a running app (or stale); AXUIElementCreateApplication
    // always returns a non-null element — attribute reads surface InvalidUIElement.
    let app = unsafe { AXUIElement::new_application(pid as libc::pid_t) };
    budget.check()?;
    let windows = read_windows(&app, app_name)?;
    // One read names the application's focused window; asked only where the answer is usable.
    let focused = mark_focused.then(|| focused_window_of_app(&app)).flatten();
    let mut out = Vec::new();
    for window in &windows {
        budget.check()?;
        let frame = match window_frame(window, budget) {
            Ok(frame) => frame,
            // A refused frame loses this window; a spent share ends the application's answer instead.
            Err(e) if budget.expired() => return Err(e),
            Err(_) => continue,
        };
        // A window costs its frame and its title: a stall on either is caught here.
        budget.check()?;
        let title = window_title(window).unwrap_or_default();
        if title.is_empty() && (frame.width <= 0.0 || frame.height <= 0.0) {
            continue;
        }
        let is_focused = focused.as_ref().is_some_and(|focused| *focused == *window);
        out.push(WindowInfo {
            app_pid: Some(pid),
            app_name: app_name.to_string(),
            title,
            key: window_key(window, owner),
            surface: frame,
            focused: is_focused,
            rank: None,
        });
    }
    Ok(out)
}

/// Resolve a target to its AX window and application element. The only place a target becomes
/// a platform handle, and therefore the one place the "our own process off the main thread"
/// check belongs ([`ensure_ax_thread`]): it runs after the app element exists but before the
/// first AX exchange, so a worker attempt stops here with nothing performed.
fn resolve_window(
    target: &TargetSpec,
    budget: &core::Budget,
) -> Result<(CFRetained<AXUIElement>, CFRetained<AXUIElement>), anyhow::Error> {
    budget.check()?;
    match target {
        TargetSpec::Focused => {
            let app = frontmost_app()?;
            ensure_ax_thread(app_pid(&app)?)?;
            // Strictly the frontmost app's focused window: a coordinate action on a fallback surface would
            // land on whatever is visible (another Space, a minimized window).
            let Some(window) = focused_window_of_app(&app) else {
                // Both leave AXFocusedWindow unset, and only a live application's answer says it
                // has no focused window: one that does not answer at all must be named as such
                // instead.
                return Err(match attribute_value(&app, &axc(AX_ROLE)) {
                    Ok(_) => core::taxonomy_error(
                        core::ERR_NOT_MATCHED,
                        "no focused window (desktop frontmost/screensaver) — use \
                         'apps'/'windows' to pick a surface",
                    ),
                    Err(_) => core::unanswered(
                        &format!(
                            "the frontmost application ({})",
                            app_display_name(app_pid(&app)?, &app)
                        ),
                        "for its focused window",
                    ),
                });
            };
            Ok((window, app))
        }
        TargetSpec::App {
            app_pid: pinned,
            app_name,
        } => {
            // An a-id names the application's own focused window, re-resolved per call. An application
            // that is gone has no window to re-resolve, and the answer says that.
            if !app_running(*pinned, app_name) {
                return Err(core::app_absent(app_name, core::AppAbsence::Quit));
            }
            let app = app_element(*pinned, app_name)?;
            let pid = app_pid(&app)?;
            ensure_ax_thread(pid)?;
            budget.check()?;
            let window = match focused_window_of_app(&app) {
                Some(window) => window,
                // A failed read is the application's answer; only a successful read that found none means none.
                None => read_windows(&app, app_name)?
                    .into_iter()
                    .next()
                    .ok_or_else(|| core::app_absent(app_name, core::AppAbsence::Windowless))?,
            };
            Ok((window, app))
        }
        TargetSpec::Window {
            app_pid: pinned,
            app_name,
            key,
            ..
        } => {
            // A w-id names one window: the key resolves that window or fails, never another one.
            let app = app_element(*pinned, app_name)?;
            ensure_ax_thread(app_pid(&app)?)?;
            Ok((window_by_key(key, app_name)?, app))
        }
        TargetSpec::Screen => Err(core::screen_observe_error()),
    }
}

fn window_origin(window: &AXUIElement) -> Result<(f64, f64), anyhow::Error> {
    let p = attribute_point(window, &axc(AX_POSITION))
        .ok_or_else(|| anyhow!("window position unavailable"))?;
    Ok((p.x, p.y))
}

/// A window's frame: two AX reads, each charged to `budget` so a stall does not outlive the call.
fn window_frame(
    window: &AXUIElement,
    budget: &core::Budget,
) -> Result<SurfaceGeometry, anyhow::Error> {
    budget.check()?;
    let p = attribute_point(window, &axc(AX_POSITION))
        .ok_or_else(|| anyhow!("window position unavailable"))?;
    budget.check()?;
    let s =
        attribute_size(window, &axc(AX_SIZE)).ok_or_else(|| anyhow!("window size unavailable"))?;
    Ok(SurfaceGeometry {
        x: p.x,
        y: p.y,
        width: s.width,
        height: s.height,
    })
}

fn app_pid(app: &AXUIElement) -> Result<u32, anyhow::Error> {
    let mut pid: libc::pid_t = 0;
    // SAFETY: `pid` points to valid storage the binding fills on success.
    let err = unsafe { app.pid(std::ptr::NonNull::new(&mut pid).unwrap()) };
    if err != AXError::Success {
        return Err(ax_error(err, "read application pid"));
    }
    Ok(pid as u32)
}

// Every gesture builds all of its events before posting any, and posting cannot fail, so a
// gesture that cannot be built delivers nothing and one that was delivered completes: nothing
// here can leave a button or a key down partway.

fn cg_mouse_button(button: MouseButton) -> CGMouseButton {
    match button {
        MouseButton::Left => CGMouseButton::Left,
        MouseButton::Right => CGMouseButton::Right,
        MouseButton::Middle => CGMouseButton::Center,
    }
}

fn cg_type_for(button: MouseButton, down: bool) -> CGEventType {
    match (button, down) {
        (MouseButton::Left, true) => CGEventType::LeftMouseDown,
        (MouseButton::Left, false) => CGEventType::LeftMouseUp,
        (MouseButton::Right, true) => CGEventType::RightMouseDown,
        (MouseButton::Right, false) => CGEventType::RightMouseUp,
        (MouseButton::Middle, true) => CGEventType::OtherMouseDown,
        (MouseButton::Middle, false) => CGEventType::OtherMouseUp,
    }
}

fn cg_flags(modifiers: &[Modifier]) -> CGEventFlags {
    modifiers.iter().fold(CGEventFlags::empty(), |acc, m| {
        acc | match m {
            Modifier::Cmd => CGEventFlags::MaskCommand,
            Modifier::Ctrl => CGEventFlags::MaskControl,
            Modifier::Alt => CGEventFlags::MaskAlternate,
            Modifier::Shift => CGEventFlags::MaskShift,
        }
    })
}

fn post_event(event: &CGEvent) {
    CGEvent::post(CGEventTapLocation::HIDEventTap, Some(event));
}

fn source() -> Option<CFRetained<CGEventSource>> {
    CGEventSource::new(CGEventSourceStateID::CombinedSessionState)
}

/// A mouse event of `kind` at `point`; a failed creation is an honest error, never a success.
fn mouse_event(
    source: Option<&CGEventSource>,
    kind: CGEventType,
    point: CGPoint,
    button: CGMouseButton,
) -> Result<CFRetained<CGEvent>, anyhow::Error> {
    CGEvent::new_mouse_event(source, kind, point, button)
        .ok_or_else(|| anyhow!("failed to create a mouse event"))
}

/// A keyboard event for `code`; see [`mouse_event`] on the failure rule.
fn keyboard_event(
    source: Option<&CGEventSource>,
    code: u16,
    down: bool,
) -> Result<CFRetained<CGEvent>, anyhow::Error> {
    CGEvent::new_keyboard_event(source, code, down)
        .ok_or_else(|| anyhow!("failed to create a keyboard event"))
}

/// A click, or double click, of `button` at `point`. `modifiers` ride as flags, never held keys.
fn click(
    point: CGPoint,
    button: MouseButton,
    double: bool,
    modifiers: &[Modifier],
) -> Result<Impact, anyhow::Error> {
    let src = source();
    let flags = cg_flags(modifiers);
    // Both halves of a double click carry click-state 2.
    let state = if double { 2 } else { 1 };
    let mut events = Vec::with_capacity(if double { 4 } else { 2 });
    for _ in 0..if double { 2 } else { 1 } {
        for down in [true, false] {
            let ev = mouse_event(
                src.as_deref(),
                cg_type_for(button, down),
                point,
                cg_mouse_button(button),
            )?;
            CGEvent::set_flags(Some(&ev), flags);
            CGEvent::set_integer_value_field(Some(&ev), CGEventField::MouseEventClickState, state);
            events.push(ev);
        }
    }
    for ev in &events {
        post_event(ev);
    }
    Ok(Impact::Done)
}

fn sleep_millis(ms: u64) {
    std::thread::sleep(std::time::Duration::from_millis(ms));
}

fn ascii_key(c: char) -> Option<i64> {
    // kVK_ANSI_* for the 26 letters and top-row digits.
    Some(match c {
        '0' => 29,
        '1' => 18,
        '2' => 19,
        '3' => 20,
        '4' => 21,
        '5' => 23,
        '6' => 22,
        '7' => 26,
        '8' => 28,
        '9' => 25,
        'a' => 0,
        's' => 1,
        'd' => 2,
        'f' => 3,
        'h' => 4,
        'g' => 5,
        'z' => 6,
        'x' => 7,
        'c' => 8,
        'v' => 9,
        'b' => 11,
        'q' => 12,
        'w' => 13,
        'e' => 14,
        'r' => 15,
        'y' => 16,
        't' => 17,
        'i' => 34,
        'o' => 31,
        'p' => 35,
        'l' => 37,
        'j' => 38,
        'k' => 40,
        'n' => 45,
        'm' => 46,
        'u' => 32,
        _ => return None,
    })
}

fn key_code(key: &str) -> Option<i64> {
    let k = key.to_lowercase();
    if k.len() == 1
        && let Some(c) = k.chars().next().and_then(ascii_key)
    {
        return Some(c);
    }
    Some(match k.as_str() {
        "return" | "enter" => 36,
        "tab" => 48,
        "space" => 49,
        "delete" => 51, // backspace
        "forwarddelete" => 117,
        "escape" => 53,
        "home" => 115,
        "end" => 119,
        "pageup" => 116,
        "pagedown" => 121,
        "up" => 126,
        "down" => 125,
        "left" => 123,
        "right" => 124,
        "f1" => 122,
        "f2" => 120,
        "f3" => 99,
        "f4" => 118,
        "f5" => 96,
        "f6" => 97,
        "f7" => 98,
        "f8" => 100,
        "f9" => 101,
        "f10" => 109,
        "f11" => 103,
        "f12" => 111,
        "minus" => 27,
        "equal" => 24,
        "comma" => 43,
        "period" => 47,
        "slash" => 44,
        "semicolon" => 41,
        "quote" => 39,
        "backslash" => 42,
        "backtick" => 50,
        "leftbracket" => 33,
        "rightbracket" => 30,
        "capslock" => 57,
        _ => return None,
    })
}

const KNOWN_KEYS: &str = "return, enter, tab, space, delete, forwarddelete, escape, home, end, \
     pageup, pagedown, up, down, left, right, f1..f12, minus, equal, comma, period, slash, \
     semicolon, quote, backslash, backtick, leftbracket, rightbracket, capslock, a-z, 0-9";

fn lookup_key(key: &str) -> Result<i64, anyhow::Error> {
    key_code(key).ok_or_else(|| anyhow!("unknown key '{key}' — supported keys: {KNOWN_KEYS}"))
}

fn press_key(key: &str) -> Result<(), anyhow::Error> {
    let code = lookup_key(key)?;
    let src = source();
    let down = keyboard_event(src.as_deref(), code as u16, true)?;
    let up = keyboard_event(src.as_deref(), code as u16, false)?;
    post_event(&down);
    post_event(&up);
    Ok(())
}

/// Typing is one character at a time, so a failure part-way through leaves the earlier
/// characters typed: that is the middle outcome. A failure on the FIRST character stays a failure.
fn type_text(text: &str) -> Result<Impact, anyhow::Error> {
    fn type_char(src: Option<&CGEventSource>, ch: char) -> Result<(), anyhow::Error> {
        let mut buf = [0u16; 2];
        let encoded = ch.encode_utf16(&mut buf);
        // Built before either is posted, so a failed build leaves the character unposted and untyped.
        let down = keyboard_event(src, 0, true)?;
        let up = keyboard_event(src, 0, false)?;
        for event in [&down, &up] {
            // SAFETY: `encoded` is a valid UTF-16 buffer.
            unsafe {
                CGEvent::keyboard_set_unicode_string(
                    Some(event),
                    encoded.len() as u64,
                    encoded.as_ptr(),
                )
            };
        }
        post_event(&down);
        post_event(&up);
        Ok(())
    }

    let src = source();
    let total = text.chars().count();
    for (typed, ch) in text.chars().enumerate() {
        let made = if ch == '\n' {
            press_key("return")
        } else {
            type_char(src.as_deref(), ch)
        };
        match made {
            Ok(()) => sleep_millis(1),
            Err(e) if typed == 0 => return Err(e),
            Err(e) => {
                return Ok(Impact::Unconfirmed(format!(
                    "{typed} of {total} characters were typed before the next keyboard event \
                     could not be created ({e})"
                )));
            }
        }
    }
    Ok(Impact::Done)
}

fn key_chord(chord: &str) -> Result<Impact, anyhow::Error> {
    let (modifiers, key) = core::parse_key_chord(chord)?;
    let code = lookup_key(&key)?;
    let src = source();
    let flags = cg_flags(&modifiers);
    let down = keyboard_event(src.as_deref(), code as u16, true)?;
    let up = keyboard_event(src.as_deref(), code as u16, false)?;
    CGEvent::set_flags(Some(&down), flags);
    // Clear flags on key-up so the modifier doesn't stick.
    CGEvent::set_flags(Some(&up), CGEventFlags::empty());
    post_event(&down);
    post_event(&up);
    Ok(Impact::Done)
}

/// Scroll: wheel 1 = vertical (down positive), wheel 2 = horizontal (right positive).
fn scroll(
    point: Option<CGPoint>,
    direction: ScrollDirection,
    amount: u32,
) -> Result<Impact, anyhow::Error> {
    let src = source();
    // The tool bounds the amount; the conversion is total so no magnitude can wrap the direction.
    let ticks = i32::try_from(amount).unwrap_or(i32::MAX);
    let (w1, w2) = match direction {
        ScrollDirection::Down => (ticks, 0),
        ScrollDirection::Up => (-ticks, 0),
        ScrollDirection::Right => (0, ticks),
        ScrollDirection::Left => (0, -ticks),
    };
    let ev =
        CGEvent::new_scroll_wheel_event2(src.as_deref(), CGScrollEventUnit::Line, 2, w1, w2, 0)
            .ok_or_else(|| anyhow!("failed to create a scroll event"))?;
    if let Some(p) = point {
        CGEvent::set_location(Some(&ev), p);
    }
    post_event(&ev);
    Ok(Impact::Done)
}

fn drag(from: CGPoint, to: CGPoint) -> Result<Impact, anyhow::Error> {
    let src = source();
    let mut events = Vec::with_capacity(14);
    events.push(mouse_event(
        src.as_deref(),
        CGEventType::LeftMouseDown,
        from,
        CGMouseButton::Left,
    )?);
    for i in 1..=12 {
        let t = i as f64 / 12.0;
        events.push(mouse_event(
            src.as_deref(),
            CGEventType::LeftMouseDragged,
            CGPoint::new(from.x + (to.x - from.x) * t, from.y + (to.y - from.y) * t),
            CGMouseButton::Left,
        )?);
    }
    events.push(mouse_event(
        src.as_deref(),
        CGEventType::LeftMouseUp,
        to,
        CGMouseButton::Left,
    )?);
    for event in &events {
        post_event(event);
        sleep_millis(2);
    }
    Ok(Impact::Done)
}

fn active_display_ids() -> Vec<CGDirectDisplayID> {
    let mut displays = [0u32; 32];
    let mut count = 0u32;
    // SAFETY: `displays` and `count` are valid storage the binding fills.
    let err =
        unsafe { CGGetActiveDisplayList(displays.len() as u32, displays.as_mut_ptr(), &mut count) };
    if err != CGError::Success {
        return Vec::new();
    }
    displays[..count as usize].to_vec()
}

fn screen_surface() -> Result<SurfaceGeometry, anyhow::Error> {
    let ids = active_display_ids();
    if ids.is_empty() {
        anyhow::bail!("no active displays found");
    }
    let mut min_x = f64::INFINITY;
    let mut min_y = f64::INFINITY;
    let mut max_x = f64::NEG_INFINITY;
    let mut max_y = f64::NEG_INFINITY;
    for id in ids {
        let b = CGDisplayBounds(id);
        min_x = min_x.min(b.origin.x);
        min_y = min_y.min(b.origin.y);
        max_x = max_x.max(b.origin.x + b.size.width);
        max_y = max_y.max(b.origin.y + b.size.height);
    }
    Ok(SurfaceGeometry {
        x: min_x,
        y: min_y,
        width: max_x - min_x,
        height: max_y - min_y,
    })
}

/// The target's surface. A window frame is an AX read, so the grant gate belongs to
/// [`surface_geometry_with`], which keeps it on the calling thread.
fn surface_geometry_blocking(
    target: &TargetSpec,
    budget: &core::Budget,
) -> Result<SurfaceGeometry, anyhow::Error> {
    if matches!(target, TargetSpec::Screen) {
        return screen_surface();
    }
    // Coordinate input maps points through this frame: a pre-minimization frame is refused here too.
    let (window, app) = resolve_window(target, budget)?;
    budget.check()?;
    let label = resolved_surface_label(target, &app, window_title(&window).as_deref())?;
    budget.check()?;
    refuse_minimized(&window)?;
    // `window_frame` checks the budget itself before each of its two reads.
    window_frame(&window, budget).map_err(|_| core::unanswered(&label, "for its frame"))
}

/// [`surface_geometry_blocking`] with the grant gate hoisted and the read routed to the thread
/// the system answers a self target on. The budget is owned so it can cross to that thread.
fn surface_geometry_with(
    target: &TargetSpec,
    budget: core::Budget,
) -> Result<SurfaceGeometry, anyhow::Error> {
    if !matches!(target, TargetSpec::Screen) {
        ensure(Grant::Accessibility)?;
    }
    with_target(target, move |target| {
        surface_geometry_blocking(target, &budget)
    })
}

/// Raise a window so input aimed at it lands there; `false` when it exposes no usable raise action.
fn raise_window(window: &AXUIElement) -> Result<bool, anyhow::Error> {
    let Some(names) = raw_action_names(window).ok().flatten() else {
        return Ok(false);
    };
    if !names.iter().any(|a| a == AX_RAISE) {
        return Ok(false);
    }
    // SAFETY: AXRaise was verified to exist on the window.
    let err = unsafe { window.perform_action(&axc(AX_RAISE)) };
    if err != AXError::Success {
        return Err(ax_error(err, "raise window"));
    }
    Ok(true)
}

/// Best-effort raise for input not pinned to a window: a refusal is not a failure there,
/// because the input may land wherever its point is. Returns whether a raise was performed,
/// so the caller settles only when there is something to settle.
fn activate_window(target: &TargetSpec, budget: &core::Budget) -> Result<bool, anyhow::Error> {
    let (TargetSpec::Focused | TargetSpec::App { .. } | TargetSpec::Window { .. }) = target else {
        return Ok(false);
    };
    let (window, _app) = match resolve_window(target, budget) {
        Ok(resolved) => resolved,
        // Nothing to raise, but the main-thread marker must reach [`with_target`].
        Err(e) if !is_ax_thread(&e) => return Ok(false),
        Err(e) => return Err(e),
    };
    raise_window(&window)
}

/// The application, and the live frame, of the surface a click addresses. The frame is read
/// rather than taken from the enumeration snapshot: the note about "another window of the same
/// application" must recognise the addressed window itself, and a frame is the one thing the
/// two systems agree on. A failed read leaves no frame, which the check reports as uncheckable.
fn live_surface_identity(
    target: &TargetSpec,
    budget: &core::Budget,
) -> (Option<u32>, Option<core::SurfaceGeometry>) {
    match resolve_window(target, budget) {
        // The frame, not the title: it is what the hit test reads for the window under the point, so
        // the two are compared in one coordinate system.
        Ok((window, app)) => (app_pid(&app).ok(), window_frame(&window, budget).ok()),
        // A window spec without a pid is one whose application could not be identified — never the
        // frontmost process; `core::UnderPoint::classify` answers that as the unknown case.
        Err(_) => (
            match target {
                TargetSpec::Focused => frontmost_identity().map(|(pid, _)| pid),
                TargetSpec::App { app_pid, .. } => {
                    app_pid.or_else(|| frontmost_identity().map(|(pid, _)| pid))
                }
                TargetSpec::Window { app_pid, .. } => *app_pid,
                TargetSpec::Screen => None,
            },
            None,
        ),
    }
}

/// Whether `window` is where input is delivered right now: frontmost application, focused window.
fn window_receives_input(window: &AXUIElement) -> bool {
    let Ok(app) = frontmost_app() else {
        return false;
    };
    focused_window_of_app(&app).is_some_and(|focused| &*focused == window)
}

/// The verification half of pinned input: the window aimed at must be the one the server would
/// deliver to. A raise completes asynchronously, so the check is retried over the shared settle
/// budget — the pauses run here, only each accessibility read is routed.
fn ensure_window_receives(target: &TargetSpec, budget: &core::Budget) -> Result<(), anyhow::Error> {
    for attempt in 0..=core::RAISE_SETTLE_STEPS {
        if attempt > 0 {
            sleep_millis(core::RAISE_SETTLE_MS);
        }
        budget.check()?;
        let probe = budget.clone();
        let receives = with_target(target, move |target| {
            let (window, _app) = resolve_window(target, &probe)?;
            Ok(window_receives_input(&window))
        })?;
        if receives {
            return Ok(());
        }
    }
    Err(core::not_brought_forward(target.describe()))
}

/// The same proof for a window the caller already holds: bring it forward and confirm delivery.
/// A pointer double click is aimed at the screen, so the element's own window is raised and
/// checked before the click rather than clicked blind.
fn bring_window_forward(
    window: &AXUIElement,
    surface: &str,
    budget: &core::Budget,
) -> Result<(), anyhow::Error> {
    raise_window(window)?;
    for attempt in 0..=core::RAISE_SETTLE_STEPS {
        if attempt > 0 {
            sleep_millis(core::RAISE_SETTLE_MS);
        }
        budget.check()?;
        if window_receives_input(window) {
            return Ok(());
        }
    }
    Err(core::not_brought_forward(surface))
}

/// Reject an argument mistake before any grant request: a call that cannot succeed must not prompt.
fn check_input_arguments(input: &RawInput) -> Result<(), anyhow::Error> {
    core::check_raw_input(input)?;
    // The chord's key is resolved here, so an unknown key is refused before any event.
    match input {
        RawInput::KeyChord { chord } => lookup_key(&core::parse_key_chord(chord)?.1).map(|_| ()),
        _ => Ok(()),
    }
}

fn raw_input_blocking(
    target: &TargetSpec,
    input: &RawInput,
    placed: &mut Option<core::Placement>,
) -> Result<core::Actuation, anyhow::Error> {
    let pinned = core::pinned_input(target, input);
    // A chord goes to whatever already has focus, so nothing is raised for it.
    let raises = !matches!(input, RawInput::KeyChord { .. });
    // One lookup budget for the whole call: raise, delivery proof and the frame the input maps through.
    let lookup = core::Budget::new(core::LIST_BUDGET, "surface lookup", target.describe());
    let geometry = lookup.clone();
    if pinned {
        let raise = lookup.clone();
        with_target(target, move |target| {
            let (window, _app) = resolve_window(target, &raise)?;
            raise_window(&window).map(|_| ())
        })?;
        let verify = lookup.clone();
        with_target(target, move |target| {
            ensure_window_receives(target, &verify)
        })?;
    } else if raises {
        let raise = lookup.clone();
        if with_target(target, move |target| activate_window(target, &raise))? {
            // Unpinned input has no delivery to verify, so a best-effort raise gets the same settle budget.
            sleep_millis((core::RAISE_SETTLE_STEPS as u64) * core::RAISE_SETTLE_MS);
        }
    }
    match input {
        RawInput::Click {
            point,
            button,
            double,
            modifiers,
        } => {
            let surface = surface_geometry_with(target, geometry)?;
            let (x, y) = core::normalized_to_surface(point.0, point.1, &surface)?;
            let local = core::surface_local((x, y), &surface);
            let placement = core::Placement {
                geometry: surface,
                from: local,
                to: None,
            };
            // Where the point is put, recorded before posting: an exception must not lose a fixed position.
            *placed = Some(placement);
            // The check runs here, at the moment the event is posted and after the raise above: only now is
            // "in front" the state the click meets. A window of another application means nothing is sent.
            let (addressed_pid, addressed_frame, under) = if matches!(target, TargetSpec::Screen) {
                (None, None, None)
            } else {
                let (pid, frame) = live_surface_identity(target, &lookup);
                (pid, frame, self::window_at_point((x, y), &lookup))
            };
            let note = core::click_under_point(&core::ClickCheck {
                surface: target,
                local,
                geometry: &surface,
                addressed_pid,
                addressed_frame: addressed_frame.as_ref(),
                under: under.as_ref(),
            })?;
            let impact = click(CGPoint::new(x, y), *button, *double, modifiers)?;
            let impact = match note {
                Some(note) => core::impact_note(impact, note),
                None => impact,
            };
            // The point the event was posted at, from the geometry read that mapped it.
            Ok(core::Actuation::at(impact, placement))
        }
        RawInput::TypeText { text } => type_text(text).map(core::Actuation::of),
        RawInput::KeyChord { chord } => key_chord(chord).map(core::Actuation::of),
        RawInput::Scroll {
            point,
            direction,
            amount,
        } => {
            let Some((nx, ny)) = point else {
                return scroll(None, *direction, *amount).map(core::Actuation::of);
            };
            let surface = surface_geometry_with(target, geometry)?;
            let (x, y) = core::normalized_to_surface(*nx, *ny, &surface)?;
            let placement = core::Placement {
                geometry: surface,
                from: core::surface_local((x, y), &surface),
                to: None,
            };
            *placed = Some(placement);
            let impact = scroll(Some(CGPoint::new(x, y)), *direction, *amount)?;
            Ok(core::Actuation::at(impact, placement))
        }
        RawInput::Drag { from, to } => {
            let surface = surface_geometry_with(target, geometry)?;
            let (fx, fy) = core::normalized_to_surface(from.0, from.1, &surface)?;
            let (tx, ty) = core::normalized_to_surface(to.0, to.1, &surface)?;
            let placement = core::Placement {
                geometry: surface,
                from: core::surface_local((fx, fy), &surface),
                to: Some(core::surface_local((tx, ty), &surface)),
            };
            *placed = Some(placement);
            let impact = drag(CGPoint::new(fx, fy), CGPoint::new(tx, ty))?;
            Ok(core::Actuation::at(impact, placement))
        }
    }
}

/// Hand-off wrappers letting SCK completion handlers deliver non-`Send` retained objects.
struct SendShareable(Retained<SCShareableContent>);
unsafe impl Send for SendShareable {}

struct SendImage(Retained<CGImage>);
unsafe impl Send for SendImage {}

/// The failure a completion handler's `NSError` stands for, by its `SCStreamError` code.
fn sc_error(err: &NSError) -> anyhow::Error {
    let code = err.code();
    if code == SCStreamErrorCode::UserDeclined.0 || code == SCStreamErrorCode::MissingEntitlements.0
    {
        permission_error(Grant::ScreenRecording)
    } else if code == SCStreamErrorCode::NoWindowList.0 {
        core::taxonomy_error(
            core::ERR_NOT_MATCHED,
            "no window found — re-enumerate windows",
        )
    } else {
        anyhow!(
            "screen capture failed (code {code}): {}",
            err.localizedDescription()
        )
    }
}

/// Block on an SCK completion handler (5s) and return the handed-off result.
fn sc_wait<T: Send>(
    slot: &Arc<Mutex<Option<Result<T, anyhow::Error>>>>,
    semaphore: &Arc<DispatchRetained<DispatchSemaphore>>,
    what: &str,
) -> Result<T, anyhow::Error> {
    if semaphore.wait(DispatchTime::NOW.time(5_000_000_000)) != 0 {
        return Err(anyhow!("timed out waiting for {what}"));
    }
    slot.lock()
        .unwrap_poison()
        .take()
        .ok_or_else(|| anyhow!("{what} handler never invoked"))?
}

/// Hand one completion handler its answer and release the waiter. The system invokes these
/// bodies on its own frames, where nothing may unwind: [`contained`] holds both guards, and a
/// failure becomes the value the waiter reads. A body that fails after the wait returned is the
/// case with no reader, logged at debug.
fn sc_complete<T>(
    slot: &Mutex<Option<Result<T, anyhow::Error>>>,
    semaphore: &DispatchSemaphore,
    what: &str,
    body: impl FnOnce() -> Result<T, anyhow::Error>,
) {
    let outcome = contained(what, body);
    if let Err(e) = &outcome {
        tracing::debug!("computer use: {e:#}");
    }
    *slot.lock().unwrap_poison() = Some(outcome);
    semaphore.signal();
}

/// Fetch the shareable-content snapshot (availability probe + capture source).
fn get_shareable_content() -> Result<Retained<SCShareableContent>, anyhow::Error> {
    let semaphore = Arc::new(DispatchSemaphore::new(0));
    let sem2 = Arc::clone(&semaphore);
    let slot: Arc<Mutex<Option<Result<SendShareable, anyhow::Error>>>> = Arc::new(Mutex::new(None));
    let slot2 = Arc::clone(&slot);
    let block = RcBlock::new(move |content: *mut SCShareableContent, err: *mut NSError| {
        sc_complete(&slot2, &sem2, "shareable content", || {
            if !err.is_null() {
                // SAFETY: `err` is valid for the handler's duration.
                return Err(sc_error(unsafe { &*err }));
            }
            if content.is_null() {
                return Err(anyhow!("no shareable content"));
            }
            // SAFETY: a retained object the handler hands us; `retain` takes
            // ownership beyond the callback.
            let content = unsafe { Retained::retain(content) }
                .ok_or_else(|| anyhow!("null shareable content"))?;
            Ok(SendShareable(content))
        });
    });
    // SAFETY: `block` is a live stack block; the framework copies it for the
    // asynchronous call, and the wait below keeps the original alive until the
    // handler has run.
    //
    // Off-screen windows are included on purpose: a window on another Space, behind another app or
    // minimized is still the surface a call may name.
    unsafe {
        SCShareableContent::getShareableContentExcludingDesktopWindows_onScreenWindowsOnly_completionHandler(false, false, &block);
    }
    sc_wait::<SendShareable>(&slot, &semaphore, "shareable content").map(|SendShareable(c)| c)
}

/// A single still of `filter`'s content, at the pixel size the caller asked for. That size is put
/// through [`core::capture_size`] BEFORE the request reaches the framework: zero is what a
/// minimized or vanished surface reduces to. Callers guarantee [`sck_available`]: messaging a
/// class that only exists from macOS 14 on aborts the process.
fn capture_filter_to_rgba(
    filter: &SCContentFilter,
    px_w: usize,
    px_h: usize,
    ignore_shadows: bool,
    budget: &CaptureBudget,
) -> Result<Capture, anyhow::Error> {
    let (px_w, px_h) = core::capture_size("the target", px_w, px_h)?;
    let (px_w, px_h) = (px_w as usize, px_h as usize);
    let config = unsafe { SCStreamConfiguration::new() };
    // SAFETY: the config setters are ObjC messages against a live object.
    // No source rect is set: SCK interprets one filter-locally and would crop
    // off-content, so the full filter content is captured and `core::crop_rgba`
    // does the zoom cropping instead.
    unsafe {
        config.setWidth(px_w);
        config.setHeight(px_h);
        config.setShowsCursor(false);
        config.setIgnoreShadowsSingleWindow(ignore_shadows);
        config.setIgnoreShadowsDisplay(ignore_shadows);
    }

    let semaphore = Arc::new(DispatchSemaphore::new(0));
    let sem2 = Arc::clone(&semaphore);
    let slot: Arc<Mutex<Option<Result<SendImage, anyhow::Error>>>> = Arc::new(Mutex::new(None));
    let slot2 = Arc::clone(&slot);
    let block = RcBlock::new(move |image: *mut CGImage, err: *mut NSError| {
        sc_complete(&slot2, &sem2, "screenshot", || {
            if !err.is_null() {
                // SAFETY: `err` is valid for the handler's duration.
                return Err(sc_error(unsafe { &*err }));
            }
            if image.is_null() {
                return Err(anyhow!("no image in the screenshot"));
            }
            // SAFETY: a +0 object the handler hands us; `retain` takes ownership
            // beyond the callback, which ends when the waiter returns.
            let image = unsafe { Retained::retain(image) }
                .ok_or_else(|| anyhow!("null screenshot image"))?;
            Ok(SendImage(image))
        });
    });
    // SAFETY: filter/config/block are valid; the framework copies the block for
    // the asynchronous call, and the wait below keeps the original alive until
    // the handler has run.
    unsafe {
        SCScreenshotManager::captureImageWithFilter_configuration_completionHandler(
            filter,
            &config,
            Some(&block),
        );
    }
    let SendImage(image) = sc_wait::<SendImage>(&slot, &semaphore, "screenshot")?;
    capture_image_to_rgba(&image, budget)
}

/// Turn a CGImage into top-down RGBA bytes. A bitmap context stores its first row at the top, so
/// the identity transform keeps that order — a CTM flip would hand every caller an upside-down
/// still. The buffer is the call's: [`core::capture_size`], charged to `budget`, one copy.
fn capture_image_to_rgba(
    image: &CGImage,
    budget: &CaptureBudget,
) -> Result<Capture, anyhow::Error> {
    let w = CGImage::width(Some(image));
    let h = CGImage::height(Some(image));
    let (px_w, px_h) = core::capture_size("a captured frame", w, h)?;
    let space = CGColorSpace::new_device_rgb()
        .ok_or_else(|| anyhow!("failed to create RGB color space"))?;
    let bitmap_info = CGImageAlphaInfo::PremultipliedLast.0 | CGImageByteOrderInfo::Order32Big.0;
    // SAFETY: sizes/stride are valid; NULL data → CG allocates the buffer.
    let ctx = unsafe {
        CGBitmapContextCreate(
            std::ptr::null_mut(),
            w,
            h,
            8,
            w * 4,
            Some(&space),
            bitmap_info,
        )
    }
    .ok_or_else(|| anyhow!("failed to create bitmap context"))?;
    CGContext::draw_image(
        Some(&ctx),
        CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(w as f64, h as f64)),
        Some(image),
    );
    let data = CGBitmapContextGetData(Some(&ctx));
    if data.is_null() {
        anyhow::bail!("bitmap context returned no data");
    }
    // SAFETY: `data` points to `w*h*4` bytes owned by the context — the buffer's own
    // size, as the charge records — and it is copied before the context is dropped.
    let pixels = unsafe { std::slice::from_raw_parts(data as *const u8, w * h * 4) };
    Capture::from_pixels(budget, "a captured frame", px_w, px_h, pixels)
}

/// The ScreenCaptureKit window a target's AX window is matched to, or a refusal: tied together
/// by owning process and frame, never by the order of a list or a title alone.
fn find_sc_window(
    content: &SCShareableContent,
    pid: u32,
    title: Option<&str>,
    frame: SurfaceGeometry,
) -> Result<Retained<SCWindow>, anyhow::Error> {
    let near = |window: &SCWindow| {
        // SAFETY: ObjC message against a live SCWindow.
        let f = unsafe { window.frame() };
        (f.origin.x - frame.x).abs() < 2.0
            && (f.origin.y - frame.y).abs() < 2.0
            && (f.size.width - frame.width).abs() < 2.0
            && (f.size.height - frame.height).abs() < 2.0
    };
    let titled = |windows: &[Retained<SCWindow>], title: &str| {
        windows
            .iter()
            .filter(|window| {
                // SAFETY: ObjC message against a live SCWindow.
                unsafe { window.title() }.map(|s| s.to_string()).as_deref() == Some(title)
            })
            .cloned()
            .collect::<Vec<_>>()
    };
    // SAFETY: each call below is an ObjC message against a live object.
    let of_app = unsafe { content.windows() }
        .iter()
        .filter(|window| {
            let owner = unsafe { window.owningApplication() };
            owner.as_ref().map(|a| unsafe { a.processID() } as u32) == Some(pid)
        })
        .collect::<Vec<_>>();
    let of_frame = of_app
        .iter()
        .filter(|window| near(window))
        .cloned()
        .collect::<Vec<_>>();
    // The frame is the window's own truth; a title only breaks a tie, and a tie that survives it
    // means the two cannot be told apart — refusing beats capturing the wrong one. With no frame
    // match a unique exact title in the same process still names the window honestly.
    let matching = match title.filter(|t| !t.is_empty()) {
        Some(title) if !of_frame.is_empty() => {
            let by_title = titled(&of_frame, title);
            if by_title.is_empty() {
                of_frame
            } else {
                by_title
            }
        }
        Some(title) => titled(&of_app, title),
        None => of_frame,
    };
    match matching.as_slice() {
        [only] => Ok(only.clone()),
        [] => Err(core::taxonomy_error(
            core::ERR_SURFACE_GONE,
            format!(
                "{} this target names is not in the capture list — it closed, or the capture \
                 facility does not expose it; enumerate windows again to pick a surface",
                core::window_description("", title.unwrap_or_default())
            ),
        )),
        many => Err(core::taxonomy_error(
            core::ERR_DEGRADED,
            format!(
                "{} windows of the same application match this target's title or frame, so the \
                 capture cannot tell which one to shoot — move or resize one of them, or \
                 screenshot the screen instead",
                many.len()
            ),
        )),
    }
}

/// The AX half of a window still: owning process, title and frame — what ScreenCaptureKit is
/// matched against. A minimized window is refused here: no visible pixels, stale frame.
fn window_capture_facts(
    target: &TargetSpec,
    budget: &core::Budget,
) -> Result<(u32, Option<String>, SurfaceGeometry), anyhow::Error> {
    let (window, app) = resolve_window(target, budget)?;
    budget.check()?;
    let pid = app_pid(&app)?;
    let title = window_title(&window);
    budget.check()?;
    let label = resolved_surface_label(target, &app, title.as_deref())?;
    refuse_minimized(&window)?;
    // `window_frame` checks the budget itself before each of its two reads.
    let frame =
        window_frame(&window, budget).map_err(|_| core::unanswered(&label, "for its frame"))?;
    Ok((pid, title, frame))
}

fn capture_window_blocking(
    target: &TargetSpec,
    budget: &CaptureBudget,
) -> Result<Capture, anyhow::Error> {
    // AX resolves the window (pid, title, frame) first; only that half belongs on the AX thread.
    let lookup = core::Budget::new(core::LIST_BUDGET, "surface lookup", target.describe());
    let (pid, title, frame) =
        with_target(target, move |target| window_capture_facts(target, &lookup))?;
    let content = get_shareable_content()?;
    let sc_window = find_sc_window(&content, pid, title.as_deref(), frame)?;
    // SAFETY: `alloc()` is the fresh allocation consumed by the init.
    let filter = unsafe {
        SCContentFilter::initWithDesktopIndependentWindow(SCContentFilter::alloc(), &sc_window)
    };
    let scale = unsafe { filter.pointPixelScale() } as f64;
    let px_w = (frame.width * scale).round();
    let px_h = (frame.height * scale).round();
    capture_filter_to_rgba(&filter, px_w as usize, px_h as usize, true, budget)
}

/// Composite each active display into one RGBA buffer at the virtual-desktop bounding rect, each
/// display drawn at its global-frame offset. One scale governs the whole buffer — the densest
/// display's — and every display is captured AT that size, so a mixed-density arrangement yields
/// one faithful composite. The composite is charged to `budget` before it exists.
fn capture_screen_blocking(budget: &CaptureBudget) -> Result<Capture, anyhow::Error> {
    let content = get_shareable_content()?;
    // SAFETY: SCK getter is an ObjC message against a live object.
    let displays = unsafe { content.displays() };
    if displays.is_empty() {
        anyhow::bail!("no shareable displays found");
    }
    let empty: Retained<NSArray<SCWindow>> = NSArray::new();
    let mut filters = Vec::with_capacity(displays.len());
    let mut ref_scale: f64 = 0.0;
    for display in &displays {
        // SAFETY: `alloc()` is the fresh allocation consumed by the init.
        let filter = unsafe {
            SCContentFilter::initWithDisplay_excludingWindows(
                SCContentFilter::alloc(),
                &display,
                &empty,
            )
        };
        // SAFETY: ObjC message against a live SCDisplay.
        let f = unsafe { display.frame() };
        ref_scale = ref_scale.max(unsafe { filter.pointPixelScale() } as f64);
        filters.push((
            filter,
            SurfaceGeometry {
                x: f.origin.x,
                y: f.origin.y,
                width: f.size.width,
                height: f.size.height,
            },
        ));
    }
    if ref_scale <= 0.0 {
        anyhow::bail!("no display reported a usable pixel scale");
    }
    let bbox = screen_surface()?;
    let out_w = (bbox.width * ref_scale).round() as usize;
    let out_h = (bbox.height * ref_scale).round() as usize;
    let (out_px_w, out_px_h) = core::capture_size("the virtual desktop", out_w, out_h)?;
    let mut composite = Capture::alloc(budget, "the screen composite", out_px_w, out_px_h)?;
    for (filter, frame) in filters {
        let px_w = (frame.width * ref_scale).round() as usize;
        let px_h = (frame.height * ref_scale).round() as usize;
        let cap = capture_filter_to_rgba(&filter, px_w, px_h, false, budget)?;
        // A display that comes back at another size cannot be placed at this scale, and blitting it
        // would leave part of the buffer black without a word.
        if (cap.width as usize, cap.height as usize) != (px_w, px_h) {
            return Err(core::taxonomy_error(
                core::ERR_DEGRADED,
                format!(
                    "a display asked for {px_w}x{px_h} pixels came back at {}x{}, so this \
                     mixed-density arrangement cannot be composited faithfully — screenshot a \
                     window instead, or capture with the display arrangement made uniform",
                    cap.width, cap.height
                ),
            ));
        }
        let dx = ((frame.x - bbox.x) * ref_scale).round();
        let dy = ((frame.y - bbox.y) * ref_scale).round();
        if dx >= 0.0 && dy >= 0.0 {
            core::blit_rgba(
                &mut composite.rgba,
                out_w,
                out_h,
                &cap,
                dx as usize,
                dy as usize,
            );
        }
    }
    Ok(composite)
}

fn capture_blocking(target: &TargetSpec, budget: &CaptureBudget) -> Result<Capture, anyhow::Error> {
    if !sck_available() {
        return Err(screen_capture_needs_14());
    }
    // A window still resolves through AX (frame, title) first, so Accessibility is needed as well.
    if !matches!(target, TargetSpec::Screen) {
        ensure(Grant::Accessibility)?;
    }
    let result = match target {
        TargetSpec::Screen => capture_screen_blocking(budget),
        _ => capture_window_blocking(target, budget),
    };
    // A failed still is diagnosed from the grant, never assumed: the attempt is the authority, so a
    // grantless capture asks for the grant while a transient failure keeps its own.
    result.map_err(|e| ensure(Grant::ScreenRecording).err().unwrap_or(e))
}

fn capture_available_blocking() -> bool {
    // Preflight only: the boot probe must never put a TCC dialog on the owner's screen.
    sck_available() && Grant::ScreenRecording.held()
}

/// Where a refused element press may synthesise a click: the element's frame, the window's origin.
struct PressPoint {
    frame: (f64, f64, f64, f64),
    origin: (f64, f64),
}

impl PressPoint {
    /// The element's centre, in screen coordinates and in the surface's own points.
    fn centre(&self) -> ((f64, f64), (f64, f64)) {
        let (x, y, w, h) = self.frame;
        let local = (x + w / 2.0, y + h / 2.0);
        ((self.origin.0 + local.0, self.origin.1 + local.1), local)
    }
}

/// Perform a reference's press: its own `AXPress`, else its `AXOpen`. An element that offers
/// `open` has two further routes for a platform that advertises the action then refuses it
/// (Finder's icons answer `kAXErrorAttributeUnsupported`): open the item, or double click it.
fn press_element(
    element: &AXUIElement,
    window: &AXUIElement,
    point: Option<&PressPoint>,
    surface: &str,
    budget: &core::Budget,
) -> Result<Impact, anyhow::Error> {
    let names = raw_action_names(element).map_err(|e| ax_error(e, "read element actions"))?;
    let Some(names) = names else {
        return Err(core::taxonomy_error(
            core::ERR_DEGRADED,
            "the accessibility API answered without usable action names for this element — act \
             on it by coordinates instead of by ref",
        ));
    };
    let open_capable = names.iter().any(|a| a == AX_OPEN);
    let press_capable = names.iter().any(|a| a == AX_PRESS);
    if !open_capable && !press_capable {
        let available = action_list(&names);
        return Err(core::taxonomy_error(
            core::ERR_UNSUPPORTED,
            format!(
                "element has no press/open action; available actions: {available} — click it by \
                 coordinates instead"
            ),
        ));
    }
    for (advertised, action, label) in [
        (press_capable, AX_PRESS, "press"),
        (open_capable, AX_OPEN, "open"),
    ] {
        if !advertised {
            continue;
        }
        // SAFETY: the action was verified to be one this element advertises.
        let err = unsafe { element.perform_action(&axc(action)) };
        if !unsupported_action(err) {
            return map_action_err(err, label);
        }
    }
    // Only an open-capable element has a further route: a refused press keeps the refusal below.
    if open_capable {
        if open_pointed_at(element) {
            return Ok(Impact::DoneWith(
                "the element refused its own action, so the item it points at was opened"
                    .to_string(),
            ));
        }
        if let Some(point) = point {
            ensure(Grant::Input)?;
            bring_window_forward(window, surface, budget)?;
            let ((x, y), local) = point.centre();
            click(CGPoint::new(x, y), MouseButton::Left, true, &[])?;
            // A synthesised click is a point action, so it says where the point was put: the element's own
            // centre in the surface's points, against the size read now.
            let placed = match window_frame(window, budget) {
                Ok(frame) => core::placed_point(local, &frame),
                Err(_) => format!(
                    "({:.1}, {:.1}) of the surface, whose size could not be read",
                    local.0, local.1
                ),
            };
            return Ok(Impact::DoneWith(format!(
                "the element refused its own action, so it was double clicked at {placed}"
            )));
        }
    }
    let available = action_list(&names);
    Err(core::taxonomy_error(
        core::ERR_UNSUPPORTED,
        format!(
            "the element advertises {available} but the accessibility API refused it — click it \
             by coordinates instead"
        ),
    ))
}

fn action_list(names: &[String]) -> String {
    names
        .iter()
        .map(|a| normalize_action_name(a))
        .collect::<Vec<_>>()
        .join(", ")
}

/// An action the platform answers with "unsupported" is not really performed: try the next route.
fn unsupported_action(err: AXError) -> bool {
    matches!(
        err,
        AXError::AttributeUnsupported | AXError::ActionUnsupported
    )
}

/// Open the item an element points at, for a reference whose own action was refused: the link is
/// the item itself, so the platform opens it exactly as the element's own action would.
fn open_pointed_at(element: &AXUIElement) -> bool {
    let Some(value) = attribute_value(element, &axc(AX_URL)).ok() else {
        return false;
    };
    let text = if let Some(url) = value.downcast_ref::<CFURL>() {
        url.string().to_string()
    } else if let Some(text) = value.downcast_ref::<CFString>() {
        text.to_string()
    } else {
        return false;
    };
    NSURL::URLWithString(&NSString::from_str(&text))
        .is_some_and(|url| NSWorkspace::sharedWorkspace().openURL(&url))
}

fn set_element_value(element: &AXUIElement, text: &str) -> Result<Impact, anyhow::Error> {
    let role = attribute_name(element, &axc(AX_ROLE)).unwrap_or_default();
    let subrole = attribute_name(element, &axc(AX_SUBROLE));
    if is_secure_field(&role, subrole.as_deref()) {
        return Err(core::taxonomy_error(
            core::ERR_UNSUPPORTED,
            "element is a secure text field — SetValue refused (use click by ref then type)",
        ));
    }
    let cf: CFRetained<CFType> = CFRetained::from(CFString::from_str(text));
    // SAFETY: `cf` is a valid CFString (a CFType).
    let err = unsafe { element.set_attribute_value(&axc(AX_VALUE), &cf) };
    if unsupported_action(err) {
        return Err(core::taxonomy_error(
            core::ERR_UNSUPPORTED,
            "set value — element does not support SetValue; use click by ref then type without ref",
        ));
    }
    map_action_err(err, "set value")
}

fn act_on_element_blocking(
    target: &TargetSpec,
    locator: &Locator,
    act: &ElementAct,
) -> Result<Impact, anyhow::Error> {
    // One clock for the whole call: resolution, the reads naming the surface, the walk and the action.
    let mut budget = core::Budget::new(core::ACT_BUDGET, "element action", target.describe());
    let (window, app) = resolve_window(target, &budget)?;
    budget.check()?;
    let app_name = resolved_app_name(target, &app)?;
    // The header title is a name, not a label: read past the cap so a cut is counted.
    let title = attribute_text(&window, &axc(AX_TITLE), core::MAX_NAME_CHARS);
    let label = core::name_surface(&mut budget, &app_name, title.as_deref());
    let origin =
        window_origin(&window).map_err(|_| core::unanswered(&label, "for its position"))?;
    let (root, handles, _truncation) = build_tree(&window, origin, &budget)?;
    // The ref is acted on only if it is still what the caller saw: same kind, name and place.
    let (matched, confirmed) = core::resolve_locator_confirmed(&root, locator)?;
    let element = &handles[core::pre_order_index(&root, matched)];
    // The element's own frame, for a press the platform can only perform as a pointer double click:
    // the tree stores frames window-relative and the window's origin puts them back on screen.
    let point = matched.frame.map(|frame| PressPoint { frame, origin });
    let impact = match act {
        ElementAct::Press => press_element(element, &window, point.as_ref(), &label, &budget),
        ElementAct::SetValue { text } => set_element_value(element, text),
    }?;
    Ok(core::impact_note(impact, confirmed.note(locator)))
}

/// Map the result of an AX ACTION onto the outcome the model is owed. The one action-specific
/// arm is `CannotComplete`: the request reached the target without confirmation, so it is the
/// middle outcome, [`Impact::Unconfirmed`].
fn map_action_err(err: AXError, ctx: &str) -> Result<Impact, anyhow::Error> {
    match err {
        AXError::Success => Ok(Impact::Done),
        AXError::InvalidUIElement => Err(core::taxonomy_error(
            core::ERR_STALE_ELEMENT,
            format!("{ctx} — window closed or changed — re-enumerate"),
        )),
        AXError::APIDisabled => Err(permission_error(Grant::Accessibility)),
        AXError::CannotComplete => Ok(Impact::Unconfirmed(format!(
            "{ctx} — the application did not confirm the accessibility action, which may already \
             have been performed"
        ))),
        _ => Err(anyhow!("AX error {err:?} while {ctx}")),
    }
}

/// One boolean entry of the session dictionary, or `None` when it is absent or not a boolean.
fn session_flag(dict: &CFDictionary<CFString, CFType>, key: &str) -> Option<bool> {
    let key = CFString::from_str(key);
    let value = dict.get(&key)?;
    Some(value.downcast_ref::<CFBoolean>()?.value())
}

/// Why this session cannot receive an interactive call, or `None` when it can.
fn desktop_unavailable_blocking() -> Option<String> {
    let Some(dict) = objc2_core_graphics::CGSessionCopyCurrentDictionary() else {
        return Some(
            "this process has no window-server session — there is no desktop to read or drive"
                .to_string(),
        );
    };
    // SAFETY: a CFDictionary's generic parameters are a phantom type over one layout,
    // and this dictionary's documented keys are CFStrings whose values are CFTypes —
    // which is exactly what the handle is told to expect before it is read.
    let dict: CFRetained<CFDictionary<CFString, CFType>> =
        unsafe { CFRetained::cast_unchecked(dict) };
    if session_flag(&dict, "kCGSSessionOnConsoleKey") == Some(false) {
        return Some(
            "another logged-in user is on this Mac's screen — this session is not on the console"
                .to_string(),
        );
    }
    if session_flag(&dict, "CGSSessionScreenIsLocked") == Some(true) {
        return Some("the screen is locked".to_string());
    }
    None
}

#[async_trait::async_trait]
impl Backend for MacOsBackend {
    fn is_supported(&self) -> bool {
        // macOS 14 is the floor, so the capability itself is always present.
        true
    }

    /// No dictionary, an unreadable one, or a session that says nothing about itself is answered by
    /// [`desktop_unavailable_blocking`]; a raising read is the one case that reads as "cannot tell".
    async fn desktop_unavailable(&self) -> Option<String> {
        with_platform("read the session state", || {
            Ok(desktop_unavailable_blocking())
        })
        .ok()
        .flatten()
    }

    async fn capture_available(&self) -> bool {
        // A probe that cannot answer counts as "no": the capture attempt carries the real diagnosis.
        with_platform("probe capture", || Ok(capture_available_blocking())).unwrap_or_else(|e| {
            tracing::warn!("computer use: {e:#}");
            false
        })
    }

    /// The diagnosis for a capture that is unavailable. It has no call to fail into, so a raised
    /// exception *becomes* the answer; its platform contacts are the version check and the grant name.
    fn capture_unavailable_error(&self) -> anyhow::Error {
        catching_foreign("diagnose capture", || {
            Ok(if sck_available() {
                permission_error(Grant::ScreenRecording)
            } else {
                screen_capture_needs_14()
            })
        })
        .unwrap_or_else(std::convert::identity)
    }

    async fn list_apps(&self) -> Result<AppListing, anyhow::Error> {
        with_platform("list applications", || {
            let mut out = Vec::new();
            for app in NSWorkspace::sharedWorkspace().runningApplications() {
                if app.activationPolicy() != NSApplicationActivationPolicy::Regular {
                    continue;
                }
                let name = app.localizedName().map_or(String::new(), |s| s.to_string());
                if !name.is_empty() {
                    out.push(AppInfo {
                        pid: Some(app.processIdentifier() as u32),
                        name,
                    });
                }
            }
            out.sort_by(|a, b| a.name.cmp(&b.name));
            out.dedup_by(|a, b| a.pid == b.pid);
            // The workspace names the frontmost application without an accessibility read, including one
            // that is not among the listed regular applications.
            let frontmost = frontmost_identity().map(|(_, name)| name);
            Ok(AppListing {
                apps: out,
                frontmost,
            })
        })
    }

    async fn app_running(&self, app: &AppInfo) -> Option<bool> {
        with_platform("check application", || Ok(app_running(app.pid, &app.name))).ok()
    }

    async fn list_windows(&self, app: Option<&AppInfo>) -> Result<WindowListing, anyhow::Error> {
        with_platform("list windows", || {
            ensure(Grant::Accessibility)?;
            let app_infos: Vec<AppInfo> = if let Some(a) = app {
                vec![a.clone()]
            } else {
                let mut v = Vec::new();
                for run in NSWorkspace::sharedWorkspace().runningApplications() {
                    if run.activationPolicy() != NSApplicationActivationPolicy::Regular {
                        continue;
                    }
                    let name = run.localizedName().map_or(String::new(), |s| s.to_string());
                    if !name.is_empty() {
                        v.push(AppInfo {
                            pid: Some(run.processIdentifier() as u32),
                            name,
                        });
                    }
                }
                v
            };
            let mut listing = WindowListing::default();
            let owner = core::agent_key();
            // The frontmost application is read once — so the mark and the line cannot disagree — and it
            // decides which application's focused window is worth a read.
            let frontmost = frontmost_identity();
            let mark_focused_pid = frontmost.as_ref().map(|(pid, _)| *pid);
            listing.frontmost = frontmost.map(|(_, name)| name);
            // One clock for the whole enumeration, and one slice of it per application: a hung application
            // costs its own part rather than the healthy ones.
            let budget = core::Budget::new(
                core::LIST_BUDGET,
                "window listing",
                app.map_or_else(
                    || "the running applications".to_string(),
                    |a| core::windows_label(&a.name),
                ),
            );
            for ai in app_infos {
                let Some(pid) = ai.pid else { continue };
                let name = ai.name;
                // A listing that runs out of time keeps what it read and names the applications it did not reach.
                if let Err(e) = budget.check() {
                    listing.unread.push(UnreadWindows {
                        app_name: name,
                        reason: format!("{e:#}"),
                    });
                    continue;
                }
                let owner = owner.clone();
                let app_name = name.clone();
                // An application whose accessibility cannot be read is named in the listing with what went
                // wrong — never left out, and never allowed to fail the whole listing.
                let app_budget = budget.slice(core::APP_SLICE, core::windows_label(&name));
                // The copy outlives the closure, so the listing can ask whether this application's share ran out.
                let share = app_budget.clone();
                let mark_focused = app.is_some() || mark_focused_pid == Some(pid);
                match on_ax_thread(pid, move || {
                    windows_of_app(pid, &name, &owner, &app_budget, mark_focused)
                }) {
                    Ok(rows) => listing.windows.extend(rows),
                    // A spent share is one skipped application, said on the line naming it.
                    Err(e) => listing.unread.push(UnreadWindows {
                        app_name,
                        reason: core::unread_reason(&e, &share),
                    }),
                }
            }
            // The order is attributed to the windows actually listed; one with no compositor entry is
            // counted, never treated as a hole, and a list that could not be read is stated as such.
            listing.order = attribute_order(&mut listing.windows);
            Ok(listing)
        })
        .map_err(degraded_read)
    }

    async fn surface_window(&self, target: &TargetSpec) -> Result<WindowInfo, anyhow::Error> {
        let target = target.clone();
        with_platform("resolve the surface", move || {
            ensure(Grant::Accessibility)?;
            let owner = core::agent_key();
            let budget = core::Budget::new(core::LIST_BUDGET, "surface lookup", target.describe());
            with_target(&target, move |target| {
                let (window, app) = resolve_window(target, &budget)?;
                budget.check()?;
                let pid = app_pid(&app)?;
                let app_name = resolved_app_name(target, &app)?;
                let title = window_title(&window);
                let label = resolved_surface_label(target, &app, title.as_deref())?;
                budget.check()?;
                Ok(WindowInfo {
                    app_pid: Some(pid),
                    app_name,
                    title: title.unwrap_or_default(),
                    key: window_key(&window, &owner),
                    surface: window_frame(&window, &budget)
                        .map_err(|_| core::unanswered(&label, "for its frame"))?,
                    focused: false,
                    rank: None,
                })
            })
        })
        .map_err(degraded_read)
    }

    async fn surface_geometry(
        &self,
        target: &TargetSpec,
    ) -> Result<SurfaceGeometry, anyhow::Error> {
        with_platform("read the target's geometry", || {
            let budget = core::Budget::new(core::LIST_BUDGET, "surface lookup", target.describe());
            surface_geometry_with(target, budget)
        })
        .map_err(degraded_read)
    }

    async fn observe(&self, target: &TargetSpec) -> Result<Observation, anyhow::Error> {
        with_platform("observe", || {
            ensure(Grant::Accessibility)?;
            with_target(target, observe_blocking)
        })
        .map_err(degraded_read)
    }

    async fn act_on_element(
        &self,
        target: &TargetSpec,
        locator: &Locator,
        act: ElementAct,
    ) -> Result<Impact, anyhow::Error> {
        with_platform("act on an element", || {
            if matches!(target, TargetSpec::Screen) {
                return Err(core::screen_act_error());
            }
            ensure(Grant::Accessibility)?;
            let locator = locator.clone();
            match with_target(target, move |target| {
                act_on_element_blocking(target, &locator, &act)
            }) {
                // Handed to mahbot's own main queue and the wait ran out: it may still be applied, so this is
                // the middle outcome rather than a failure.
                Err(e) if e.downcast_ref::<AxBusy>().is_some() => Ok(Impact::Unconfirmed(format!(
                    "{e}; the request may still be applied once that thread catches up"
                ))),
                // A framework exception raised inside the exchange stopped somewhere unknown: it may have acted.
                Err(e) if core::is_framework_failed(&e) => Ok(Impact::Unconfirmed(format!(
                    "the system raised an exception while the element action was running, so it \
                     may already have been performed — {e}"
                ))),
                other => other,
            }
        })
    }

    async fn raw_input(
        &self,
        target: &TargetSpec,
        input: RawInput,
    ) -> Result<core::Actuation, anyhow::Error> {
        // The position the call placed is kept outside the firewall: it is worked out before the event
        // is posted, so a posting exception still answers where the point was put.
        let mut placed = None;
        let result = with_platform("synthesize input", || {
            check_input_arguments(&input)?;
            ensure(Grant::Input)?;
            raw_input_blocking(target, &input, &mut placed)
        });
        match result {
            // An own-window exchange that timed out before any event was posted: nothing was actuated.
            Err(e) if e.downcast_ref::<AxBusy>().is_some() => Err(core::taxonomy_error(
                core::ERR_DEGRADED,
                format!("{e} — nothing was sent to the window; retry the call"),
            )),
            // An exception under the call: the events already posted stay posted, so this may have landed.
            Err(e) if core::is_framework_failed(&e) => {
                let impact = Impact::Unconfirmed(format!(
                    "the system raised an exception while the input was being synthesized, so \
                     part of it may already have been delivered — {e}"
                ));
                Ok(core::Actuation::placed(impact, placed))
            }
            other => other,
        }
    }

    async fn cursor_position(&self) -> Result<(f64, f64), anyhow::Error> {
        with_platform("read the pointer position", || {
            let event =
                CGEvent::new(None).ok_or_else(|| anyhow!("failed to create dummy cursor event"))?;
            let p = CGEvent::location(Some(&event));
            Ok((p.x, p.y))
        })
    }

    /// The focused element of the addressed application, read from its own element. Best-effort by
    /// contract: a missing grant, a target that stops answering or no focus answers `None`.
    async fn focused_element(&self, target: Option<&TargetSpec>) -> Option<FocusedElement> {
        let target = target.cloned();
        with_platform("read the focused element", move || {
            // One budget for the whole probe, which answers every action.
            let budget = core::Budget::new(
                core::LIST_BUDGET,
                "focused element",
                target.as_ref().map_or_else(
                    || "the focused application".to_string(),
                    core::TargetSpec::describe,
                ),
            );
            let focused = match &target {
                Some(
                    TargetSpec::Window {
                        app_pid, app_name, ..
                    }
                    | TargetSpec::App { app_pid, app_name },
                ) => app_element(*app_pid, app_name)
                    .ok()
                    .and_then(|app| focused_element_of_app(&app, &budget)),
                _ => frontmost_app()
                    .ok()
                    .and_then(|app| focused_element_of_app(&app, &budget)),
            };
            Ok(focused)
        })
        .ok()
        .flatten()
    }

    async fn capture(
        &self,
        target: &TargetSpec,
        budget: &CaptureBudget,
    ) -> Result<Capture, anyhow::Error> {
        with_platform("capture", || capture_blocking(target, budget)).map_err(degraded_read)
    }
}

/// The window's title as a capped label ([`core::cap_label`]): a cut is counted only where a tree
/// header is at hand — [`observe_blocking`] reads it through [`Truncation::keep_name`] itself.
fn window_title(window: &AXUIElement) -> Option<String> {
    attribute_name(window, &axc(AX_TITLE))
}

#[cfg(test)]
mod tests {
    use super::*;
    use objc2_core_graphics::{CGBitmapInfo, CGColorRenderingIntent, CGDataProvider};

    /// The evidence for this backend's exception route: a framework call that raises must come back
    /// as a failed call, and raising it must not kill the process running this test.
    #[test]
    fn a_framework_exception_becomes_a_failed_call() {
        let err = with_platform("probe", || -> Result<(), anyhow::Error> {
            let array = NSArray::<objc2::runtime::NSObject>::new();
            // An out-of-range read is the framework's own NSRangeException, not something Rust maps.
            let _: *mut objc2::runtime::AnyObject =
                unsafe { objc2::msg_send![&array, objectAtIndex: 0usize] };
            Ok(())
        })
        .expect_err("the exception must not escape the firewall");
        let text = format!("{err:#}");
        assert!(
            text.starts_with(core::ERR_FRAMEWORK_FAILED),
            "expected a framework-failed call, got: {text}"
        );
        assert!(text.contains("exception"), "{text}");
    }

    /// A wrongly-typed member must not be read as the type assumed, nor take the good ones with it.
    #[test]
    fn typed_members_skip_a_member_of_another_type() {
        let name = CFString::from_str("AXPress");
        let number = objc2_core_foundation::CFNumber::new_i64(7);
        let array = CFArray::<CFType>::from_objects(&[&name, &number]);
        let names: Vec<String> = typed_members::<CFString>(array.as_ref())
            .iter()
            .map(ToString::to_string)
            .collect();
        assert_eq!(names, vec!["AXPress".to_string()]);
    }

    /// The capture conversion must keep the source's row order: a still whose rows were reversed puts
    /// the menu bar at the bottom, and nothing else here looks at a pixel. Four distinct corners make
    /// a Y mirror visible in the first and last rows (and an X mirror in the columns).
    #[test]
    fn a_capture_keeps_the_source_row_and_column_order() {
        let corners: [u8; 16] = [
            255, 0, 0, 255, // top-left: red
            0, 255, 0, 255, // top-right: green
            0, 0, 255, 255, // bottom-left: blue
            255, 255, 255, 255, // bottom-right: white
        ];
        // SAFETY: the provider borrows `corners` for at least as long as it lives,
        // and the RGBA8 layout is the one described to the image below.
        let provider = unsafe {
            CGDataProvider::with_data(
                std::ptr::null_mut(),
                corners.as_ptr().cast(),
                corners.len(),
                None,
            )
        }
        .expect("a data provider over the fixture pixels");
        let space = CGColorSpace::new_device_rgb().expect("a device RGB space");
        let info = CGBitmapInfo(
            CGImageAlphaInfo::PremultipliedLast.0 | CGImageByteOrderInfo::Order32Big.0,
        );
        // SAFETY: a 2x2 RGBA8 image over `provider`, which outlives it, with a null
        // decode array as documented.
        let image = unsafe {
            CGImage::new(
                2,
                2,
                8,
                32,
                8,
                Some(&space),
                info,
                Some(&provider),
                std::ptr::null(),
                false,
                CGColorRenderingIntent::RenderingIntentDefault,
            )
        }
        .expect("a 2x2 fixture image");
        let capture = capture_image_to_rgba(&image, &core::CaptureBudget::default())
            .expect("the fixture converts");
        // One comparison pins the whole buffer: a Y mirror swaps the red/blue and green/white pairs, an X
        // mirror swaps the green/blue pair, and the length is the 2x2 image's.
        assert_eq!(
            &capture.rgba[..],
            &corners[..],
            "corners: top-left red, top-right green, bottom-left blue, bottom-right white"
        );
    }

    #[test]
    fn key_table_covers_chord_parser_keys() {
        for key in [
            "a",
            "z",
            "5",
            "0",
            "return",
            "space",
            "backslash",
            "f1",
            "f12",
            "capslock",
        ] {
            let (mods, parsed) = core::parse_key_chord(key).unwrap();
            assert!(mods.is_empty());
            assert_eq!(parsed, key.to_lowercase(), "chord parser mangles '{key}'");
            assert!(key_code(key).is_some(), "kVK table missing '{key}'");
        }
        let (mods, parsed) = core::parse_key_chord("cmd+shift+t").unwrap();
        assert_eq!(mods, vec![Modifier::Cmd, Modifier::Shift]);
        assert_eq!(parsed, "t");
    }
}