nils-macos-agent 0.4.7

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

use crate::backend::process::{ProcessFailure, ProcessRequest, ProcessRunner};
use crate::error::CliError;
use crate::model::{
    AxActionPerformRequest, AxActionPerformResult, AxAttrGetRequest, AxAttrGetResult,
    AxAttrSetRequest, AxAttrSetResult, AxClickRequest, AxClickResult, AxListRequest, AxListResult,
    AxSelector, AxSessionListResult, AxSessionStartRequest, AxSessionStartResult,
    AxSessionStopRequest, AxSessionStopResult, AxTypeRequest, AxTypeResult, AxWatchPollRequest,
    AxWatchPollResult, AxWatchStartRequest, AxWatchStartResult, AxWatchStopRequest,
    AxWatchStopResult,
};
use crate::test_mode;

use super::AxBackendAdapter;

const AX_LIST_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_LIST_JSON";
const AX_CLICK_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_CLICK_JSON";
const AX_TYPE_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_TYPE_JSON";
const AX_ATTR_GET_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_ATTR_GET_JSON";
const AX_ATTR_SET_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_ATTR_SET_JSON";
const AX_ACTION_PERFORM_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_ACTION_PERFORM_JSON";
const AX_SESSION_START_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_SESSION_START_JSON";
const AX_SESSION_LIST_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_SESSION_LIST_JSON";
const AX_SESSION_STOP_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_SESSION_STOP_JSON";
const AX_WATCH_START_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_WATCH_START_JSON";
const AX_WATCH_POLL_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_WATCH_POLL_JSON";
const AX_WATCH_STOP_TEST_MODE_ENV: &str = "AGENTS_MACOS_AGENT_AX_WATCH_STOP_JSON";
const BACKEND_UNAVAILABLE_HINT_PREFIX: &str = "Hammerspoon backend unavailable";

macro_rules! hs_ax_script_with_targeting_prelude {
    ($operation:literal, $body:literal) => {
        concat!(
            r#"
local json = hs.json
local appmod = hs.application
local ax = hs.axuielement

local function fail(message)
  error(message, 0)
end

local function safe(callable, fallback)
  local ok, value = pcall(callable)
  if ok then return value end
  return fallback
end

local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end

local function asTable(value)
  if type(value) == "table" then return value end
  return {}
end

local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end

local function resolveTarget(rawTarget)
  local target = rawTarget or {}
  local state = ensureState()
  if target.session_id and tostring(target.session_id) ~= "" then
    local session = state.sessions[tostring(target.session_id)]
    if not session then
      fail("session_id does not exist")
    end
    return {
      session_id = tostring(target.session_id),
      app = target.app or session.app,
      bundle_id = target.bundle_id or session.bundle_id,
      pid = session.pid,
      window_title_contains = target.window_title_contains or session.window_title_contains,
    }
  end
  return target
end

local function attr(element, name, fallback)
  local value = safe(function() return element:attributeValue(name) end, fallback)
  if value == nil then return fallback end
  return value
end

local function boolAttr(element, name, fallback)
  local value = attr(element, name, fallback)
  if type(value) == "boolean" then return value end
  if value == nil then return fallback end
  return tostring(value):lower() == "true"
end

local function children(element)
  return asTable(attr(element, "AXChildren", {}))
end

local function resolveApp(target)
  target = resolveTarget(target)

  if target.pid then
    local byPid = appmod.applicationForPID(tonumber(target.pid))
    if byPid then return byPid, target end
  end

  if target.app and tostring(target.app) ~= "" then
    local found = appmod.find(tostring(target.app))
    if found then return found, target end
  end

  if target.bundle_id and tostring(target.bundle_id) ~= "" then
    local apps = appmod.applicationsForBundleID(tostring(target.bundle_id))
    if type(apps) == "table" and #apps > 0 then
      return apps[1], target
    end
  end

  return appmod.frontmostApplication(), target
end

local function rootsForApp(app, target)
  local appElement = ax.applicationElement(app)
  if not appElement then
    fail("unable to resolve target app process")
  end

  local roots = asTable(attr(appElement, "AXWindows", {}))
  if #roots == 0 then
    roots = children(appElement)
  end
  local windowFilter = target and target.window_title_contains and string.lower(tostring(target.window_title_contains)) or nil
  if not windowFilter then
    return roots
  end

  local filtered = {}
  for _, root in ipairs(roots) do
    local title = string.lower(normalize(attr(root, "AXTitle", "")))
    if string.find(title, windowFilter, 1, true) then
      table.insert(filtered, root)
    end
  end
  return filtered
end

local function copyPath(path)
  local out = {}
  for i, value in ipairs(path) do
    out[i] = value
  end
  return out
end

local function cliPayloadArg(defaultValue)
  local args = (_cli and _cli.args) or {}
  local raw = args[1]
  if raw == "--" then
    raw = args[2]
  end
  if raw == nil or tostring(raw) == "" then
    return defaultValue
  end
  return raw
end

"#,
            $body
        )
    };
}

const AX_LIST_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.list",
    r#"
local function frameFor(element)
  local pos = attr(element, "AXPosition", nil)
  local size = attr(element, "AXSize", nil)
  if type(pos) ~= "table" or type(size) ~= "table" then return nil end

  local x = tonumber(pos.x or pos[1])
  local y = tonumber(pos.y or pos[2])
  local width = tonumber(size.w or size.width or size[1])
  local height = tonumber(size.h or size.height or size[2])

  if not x or not y or not width or not height then return nil end
  return { x = x, y = y, width = width, height = height }
end

local function actionNames(element)
  local raw = safe(function() return element:actionNames() end, nil)
  if type(raw) ~= "table" then return {} end
  local out = {}
  for _, name in ipairs(raw) do
    local text = normalize(name)
    if text ~= "" then table.insert(out, text) end
  end
  return out
end

local function valuePreview(element)
  local value = attr(element, "AXValue", nil)
  if value == nil then return nil end
  local text = normalize(value)
  if #text > 160 then
    text = string.sub(text, 1, 160) .. "..."
  end
  return text
end

local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then
    fail("invalid payload JSON")
  end
  return payload
end

local payload = parsePayload()
local roleFilter = payload.role and string.lower(tostring(payload.role)) or nil
local titleFilter = payload.title_contains and string.lower(tostring(payload.title_contains)) or nil
local identifierFilter = payload.identifier_contains and string.lower(tostring(payload.identifier_contains)) or nil
local valueFilter = payload.value_contains and string.lower(tostring(payload.value_contains)) or nil
local subroleFilter = payload.subrole and string.lower(tostring(payload.subrole)) or nil
local maxDepth = payload.max_depth and tonumber(payload.max_depth) or nil
local limit = payload.limit and tonumber(payload.limit) or nil
local focusedFilter = payload.focused
local enabledFilter = payload.enabled

local app, resolvedTarget = resolveApp(payload.target)
if not app then
  fail("unable to resolve target app process for ax.list")
end

local roots = rootsForApp(app, resolvedTarget)
local nodes = {}

local function nodeFrom(element, path)
  local role = normalize(attr(element, "AXRole", ""))
  local title = normalize(attr(element, "AXTitle", ""))
  local identifier = normalize(attr(element, "AXIdentifier", ""))
  local subrole = normalize(attr(element, "AXSubrole", ""))

  local node = {
    node_id = table.concat(path, "."),
    role = role,
    subrole = subrole ~= "" and subrole or nil,
    title = title ~= "" and title or nil,
    identifier = identifier ~= "" and identifier or nil,
    value_preview = valuePreview(element),
    enabled = boolAttr(element, "AXEnabled", true),
    focused = boolAttr(element, "AXFocused", false),
    frame = frameFor(element),
    actions = actionNames(element),
    path = copyPath(path),
  }

  return node
end

local function matches(node)
  if roleFilter and string.lower(node.role or "") ~= roleFilter then
    return false
  end

  if titleFilter then
    local title = string.lower(node.title or "")
    local identifier = string.lower(node.identifier or "")
    if not string.find(title, titleFilter, 1, true) and not string.find(identifier, titleFilter, 1, true) then
      return false
    end
  end

  if identifierFilter and not string.find(string.lower(node.identifier or ""), identifierFilter, 1, true) then
    return false
  end

  if valueFilter and not string.find(string.lower(node.value_preview or ""), valueFilter, 1, true) then
    return false
  end

  if subroleFilter and string.lower(node.subrole or "") ~= subroleFilter then
    return false
  end

  if focusedFilter ~= nil and node.focused ~= focusedFilter then
    return false
  end

  if enabledFilter ~= nil and node.enabled ~= enabledFilter then
    return false
  end

  return true
end

local function visit(element, path, depth)
  if limit and #nodes >= limit then
    return
  end

  local node = nodeFrom(element, path)
  if matches(node) then
    table.insert(nodes, node)
  end

  if maxDepth and depth >= maxDepth then
    return
  end

  for index, child in ipairs(children(element)) do
    local childPath = copyPath(path)
    table.insert(childPath, tostring(index))
    visit(child, childPath, depth + 1)
    if limit and #nodes >= limit then
      return
    end
  end
end

for rootIndex, root in ipairs(roots) do
  visit(root, { tostring(rootIndex) }, 0)
  if limit and #nodes >= limit then
    break
  end
end

return json.encode({ nodes = nodes, warnings = {} })
"#
);

const AX_CLICK_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.click",
    r#"
local function nodeFrom(element, path)
  local role = normalize(attr(element, "AXRole", ""))
  local title = normalize(attr(element, "AXTitle", ""))
  local identifier = normalize(attr(element, "AXIdentifier", ""))
  local subrole = normalize(attr(element, "AXSubrole", ""))
  local value = normalize(attr(element, "AXValue", ""))
  local focused = normalize(attr(element, "AXFocused", "false"))
  local enabled = normalize(attr(element, "AXEnabled", "true"))
  return {
    node_id = table.concat(path, "."),
    role = role,
    title = title,
    identifier = identifier,
    subrole = subrole,
    value_preview = value,
    focused = string.lower(focused) == "true",
    enabled = string.lower(enabled) == "true",
  }
end

local function frameCenter(element)
  local pos = attr(element, "AXPosition", nil)
  local size = attr(element, "AXSize", nil)
  if type(pos) ~= "table" or type(size) ~= "table" then return nil end

  local x = tonumber(pos.x or pos[1])
  local y = tonumber(pos.y or pos[2])
  local width = tonumber(size.w or size.width or size[1])
  local height = tonumber(size.h or size.height or size[2])

  if not x or not y or not width or not height then return nil end
  return {
    x = math.floor(x + width / 2),
    y = math.floor(y + height / 2),
  }
end

local function resolveByNodeId(roots, nodeId)
  local parts = {}
  for segment in string.gmatch(tostring(nodeId), "[^.]+") do
    table.insert(parts, tonumber(segment))
  end
  if #parts == 0 then return nil end

  local rootIndex = parts[1]
  if not rootIndex or rootIndex < 1 or rootIndex > #roots then
    return nil
  end

  local element = roots[rootIndex]
  local path = { tostring(rootIndex) }

  for i = 2, #parts do
    local childIndex = parts[i]
    local directChildren = children(element)
    if not childIndex or childIndex < 1 or childIndex > #directChildren then
      return nil
    end
    element = directChildren[childIndex]
    table.insert(path, tostring(childIndex))
  end

  return {
    element = element,
    node = nodeFrom(element, path),
  }
end

local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then
    fail("invalid payload JSON")
  end
  return payload
end

local payload = parsePayload()
local selector = payload.selector or {}
local roleFilter = selector.role and string.lower(tostring(selector.role)) or nil
local titleFilter = selector.title_contains and string.lower(tostring(selector.title_contains)) or nil
local identifierFilter = selector.identifier_contains and string.lower(tostring(selector.identifier_contains)) or nil
local valueFilter = selector.value_contains and string.lower(tostring(selector.value_contains)) or nil
local subroleFilter = selector.subrole and string.lower(tostring(selector.subrole)) or nil
local focusedFilter = selector.focused
local enabledFilter = selector.enabled
local nth = selector.nth and tonumber(selector.nth) or nil
local allowCoordinateFallback = payload.allow_coordinate_fallback and true or false

local app, resolvedTarget = resolveApp(payload.target)
if not app then
  fail("unable to resolve target app process for ax.click")
end

local roots = rootsForApp(app, resolvedTarget)
local matches = {}

if selector.node_id then
  local byId = resolveByNodeId(roots, selector.node_id)
  if byId then
    table.insert(matches, byId)
  end
else
  local function walk(element, path)
    local node = nodeFrom(element, path)
    local roleMatch = (not roleFilter) or (string.lower(node.role or "") == roleFilter)
    local title = string.lower(node.title or "")
    local identifier = string.lower(node.identifier or "")
    local value = string.lower(node.value_preview or "")
    local subrole = string.lower(node.subrole or "")
    local titleMatch = (not titleFilter) or string.find(title, titleFilter, 1, true) or string.find(identifier, titleFilter, 1, true)
    local identifierMatch = (not identifierFilter) or string.find(identifier, identifierFilter, 1, true)
    local valueMatch = (not valueFilter) or string.find(value, valueFilter, 1, true)
    local subroleMatch = (not subroleFilter) or subrole == subroleFilter
    local focusedMatch = (focusedFilter == nil) or (node.focused == focusedFilter)
    local enabledMatch = (enabledFilter == nil) or (node.enabled == enabledFilter)
    if roleMatch and titleMatch and identifierMatch and valueMatch and subroleMatch and focusedMatch and enabledMatch then
      table.insert(matches, { element = element, node = node })
    end

    for index, child in ipairs(children(element)) do
      local childPath = copyPath(path)
      table.insert(childPath, tostring(index))
      walk(child, childPath)
    end
  end

  for rootIndex, root in ipairs(roots) do
    walk(root, { tostring(rootIndex) })
  end
end

if #matches == 0 then
  fail("selector returned zero AX matches")
end

local selected
if selector.node_id then
  selected = matches[1]
elseif nth then
  if nth < 1 or nth > #matches then
    fail("selector nth is out of range")
  end
  selected = matches[nth]
else
  if #matches ~= 1 then
    fail("selector is ambiguous; add --nth or narrow role/title filters")
  end
  selected = matches[1]
end

local actions = asTable(safe(function() return selected.element:actionNames() end, {}))
local actionToRun = nil
for _, name in ipairs(actions) do
  local value = normalize(name)
  if value == "AXPress" or value == "AXConfirm" then
    actionToRun = value
    break
  end
end

local result = {
  node_id = selected.node.node_id,
  matched_count = #matches,
  action = "ax-press",
  used_coordinate_fallback = false,
}

local performOk = false
if actionToRun then
  performOk = safe(function()
    selected.element:performAction(actionToRun)
    return true
  end, false)
end

if not performOk then
  if not allowCoordinateFallback then
    fail("AXPress action unavailable")
  end
  local center = frameCenter(selected.element)
  if not center then
    fail("coordinate fallback requested but AXPosition/AXSize unavailable")
  end
  result.action = "ax-press-fallback"
  result.used_coordinate_fallback = true
  result.fallback_x = center.x
  result.fallback_y = center.y
end

return json.encode(result)
"#
);

const AX_TYPE_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.type",
    r#"
local eventtap = hs.eventtap
local pasteboard = hs.pasteboard

local function nodeFrom(element, path)
  local role = normalize(attr(element, "AXRole", ""))
  local title = normalize(attr(element, "AXTitle", ""))
  local identifier = normalize(attr(element, "AXIdentifier", ""))
  local subrole = normalize(attr(element, "AXSubrole", ""))
  local value = normalize(attr(element, "AXValue", ""))
  return {
    node_id = table.concat(path, "."),
    role = role,
    title = title,
    identifier = identifier,
    subrole = subrole,
    value_preview = value,
    focused = boolAttr(element, "AXFocused", false),
    enabled = boolAttr(element, "AXEnabled", true),
  }
end

local function resolveByNodeId(roots, nodeId)
  local parts = {}
  for segment in string.gmatch(tostring(nodeId), "[^.]+") do
    table.insert(parts, tonumber(segment))
  end
  if #parts == 0 then return nil end

  local rootIndex = parts[1]
  if not rootIndex or rootIndex < 1 or rootIndex > #roots then
    return nil
  end

  local element = roots[rootIndex]
  local path = { tostring(rootIndex) }

  for i = 2, #parts do
    local childIndex = parts[i]
    local directChildren = children(element)
    if not childIndex or childIndex < 1 or childIndex > #directChildren then
      return nil
    end
    element = directChildren[childIndex]
    table.insert(path, tostring(childIndex))
  end

  return {
    element = element,
    node = nodeFrom(element, path),
  }
end

local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then
    fail("invalid payload JSON")
  end
  return payload
end

local payload = parsePayload()
local selector = payload.selector or {}
local roleFilter = selector.role and string.lower(tostring(selector.role)) or nil
local titleFilter = selector.title_contains and string.lower(tostring(selector.title_contains)) or nil
local identifierFilter = selector.identifier_contains and string.lower(tostring(selector.identifier_contains)) or nil
local valueFilter = selector.value_contains and string.lower(tostring(selector.value_contains)) or nil
local subroleFilter = selector.subrole and string.lower(tostring(selector.subrole)) or nil
local focusedFilter = selector.focused
local enabledFilter = selector.enabled
local nth = selector.nth and tonumber(selector.nth) or nil
local text = payload.text and tostring(payload.text) or ""
local allowKeyboardFallback = payload.allow_keyboard_fallback and true or false
local clearFirst = payload.clear_first and true or false
local submit = payload.submit and true or false
local paste = payload.paste and true or false

if text == "" then
  fail("text cannot be empty")
end

local app, resolvedTarget = resolveApp(payload.target)
if not app then
  fail("unable to resolve target app process for ax.type")
end
safe(function() app:activate() end, nil)

local roots = rootsForApp(app, resolvedTarget)
local matches = {}

if selector.node_id then
  local byId = resolveByNodeId(roots, selector.node_id)
  if byId then
    table.insert(matches, byId)
  end
else
  local function walk(element, path)
    local node = nodeFrom(element, path)
    local roleMatch = (not roleFilter) or (string.lower(node.role or "") == roleFilter)
    local title = string.lower(node.title or "")
    local identifier = string.lower(node.identifier or "")
    local value = string.lower(node.value_preview or "")
    local subrole = string.lower(node.subrole or "")
    local titleMatch = (not titleFilter) or string.find(title, titleFilter, 1, true) or string.find(identifier, titleFilter, 1, true)
    local identifierMatch = (not identifierFilter) or string.find(identifier, identifierFilter, 1, true)
    local valueMatch = (not valueFilter) or string.find(value, valueFilter, 1, true)
    local subroleMatch = (not subroleFilter) or subrole == subroleFilter
    local focusedMatch = (focusedFilter == nil) or (node.focused == focusedFilter)
    local enabledMatch = (enabledFilter == nil) or (node.enabled == enabledFilter)
    if roleMatch and titleMatch and identifierMatch and valueMatch and subroleMatch and focusedMatch and enabledMatch then
      table.insert(matches, { element = element, node = node })
    end

    for index, child in ipairs(children(element)) do
      local childPath = copyPath(path)
      table.insert(childPath, tostring(index))
      walk(child, childPath)
    end
  end

  for rootIndex, root in ipairs(roots) do
    walk(root, { tostring(rootIndex) })
  end
end

if #matches == 0 then
  fail("selector returned zero AX matches")
end

local selected
if selector.node_id then
  selected = matches[1]
elseif nth then
  if nth < 1 or nth > #matches then
    fail("selector nth is out of range")
  end
  selected = matches[nth]
else
  if #matches ~= 1 then
    fail("selector is ambiguous; add --nth or narrow selector filters")
  end
  selected = matches[1]
end

local appliedVia = "ax-set-value"
local usedKeyboardFallback = false

local function applyPaste()
  pasteboard.setContents(text)
  eventtap.keyStroke({"cmd"}, "v", 0)
end

local appliedOk = safe(function()
  safe(function() selected.element:setAttributeValue("AXFocused", true) end, nil)
  if clearFirst then
    safe(function() selected.element:setAttributeValue("AXValue", "") end, nil)
  end
  if paste then
    applyPaste()
    appliedVia = "ax-paste"
  else
    selected.element:setAttributeValue("AXValue", text)
    appliedVia = "ax-set-value"
  end
  return true
end, false)

if not appliedOk then
  if not allowKeyboardFallback then
    fail("AX value set failed")
  end

  usedKeyboardFallback = true
  if paste then
    applyPaste()
    appliedVia = "keyboard-paste-fallback"
  else
    eventtap.keyStrokes(text)
    appliedVia = "keyboard-keystroke-fallback"
  end
end

if submit then
  eventtap.keyStroke({}, "return", 0)
end

return json.encode({
  node_id = selected.node.node_id,
  matched_count = #matches,
  applied_via = appliedVia,
  text_length = string.len(text),
  submitted = submit,
  used_keyboard_fallback = usedKeyboardFallback,
})
"#
);

const AX_ATTR_GET_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.attr.get",
    r#"
local function resolveApp(target)
  target = resolveTarget(target)

  if target.pid then
    local byPid = appmod.applicationForPID(tonumber(target.pid))
    if byPid then return byPid end
  end

  if target.app and tostring(target.app) ~= "" then
    local found = appmod.find(tostring(target.app))
    if found then return found, target end
  end

  if target.bundle_id and tostring(target.bundle_id) ~= "" then
    local apps = appmod.applicationsForBundleID(tostring(target.bundle_id))
    if type(apps) == "table" and #apps > 0 then
      return apps[1], target
    end
  end

  return appmod.frontmostApplication(), target
end

local function nodeFrom(element, path)
  local role = normalize(attr(element, "AXRole", ""))
  local title = normalize(attr(element, "AXTitle", ""))
  local identifier = normalize(attr(element, "AXIdentifier", ""))
  local subrole = normalize(attr(element, "AXSubrole", ""))
  local value = normalize(attr(element, "AXValue", ""))
  return {
    node_id = table.concat(path, "."),
    role = role,
    title = title,
    identifier = identifier,
    subrole = subrole,
    value_preview = value,
    focused = boolAttr(element, "AXFocused", false),
    enabled = boolAttr(element, "AXEnabled", true),
  }
end

local function matches(node, selector)
  selector = selector or {}

  if selector.role and string.lower(node.role or "") ~= string.lower(tostring(selector.role)) then
    return false
  end
  if selector.title_contains and not string.find(string.lower(node.title or ""), string.lower(tostring(selector.title_contains)), 1, true) then
    return false
  end
  if selector.identifier_contains and not string.find(string.lower(node.identifier or ""), string.lower(tostring(selector.identifier_contains)), 1, true) then
    return false
  end
  if selector.value_contains and not string.find(string.lower(node.value_preview or ""), string.lower(tostring(selector.value_contains)), 1, true) then
    return false
  end
  if selector.subrole and string.lower(node.subrole or "") ~= string.lower(tostring(selector.subrole)) then
    return false
  end
  if selector.focused ~= nil and node.focused ~= selector.focused then
    return false
  end
  if selector.enabled ~= nil and node.enabled ~= selector.enabled then
    return false
  end
  return true
end

local function resolveByNodeId(roots, nodeId)
  local parts = {}
  for segment in string.gmatch(tostring(nodeId), "[^.]+") do
    table.insert(parts, tonumber(segment))
  end
  if #parts == 0 then return nil end

  local rootIndex = parts[1]
  if not rootIndex or rootIndex < 1 or rootIndex > #roots then
    return nil
  end

  local element = roots[rootIndex]
  local path = { tostring(rootIndex) }
  for i = 2, #parts do
    local childIndex = parts[i]
    local directChildren = children(element)
    if not childIndex or childIndex < 1 or childIndex > #directChildren then
      return nil
    end
    element = directChildren[childIndex]
    table.insert(path, tostring(childIndex))
  end
  return { element = element, node = nodeFrom(element, path) }
end

local function collectMatches(roots, selector)
  local matchesOut = {}

  if selector.node_id then
    local byId = resolveByNodeId(roots, selector.node_id)
    if byId then
      table.insert(matchesOut, byId)
    end
    return matchesOut
  end

  local function walk(element, path)
    local node = nodeFrom(element, path)
    if matches(node, selector) then
      table.insert(matchesOut, { element = element, node = node })
    end
    for index, child in ipairs(children(element)) do
      local childPath = copyPath(path)
      table.insert(childPath, tostring(index))
      walk(child, childPath)
    end
  end

  for rootIndex, root in ipairs(roots) do
    walk(root, { tostring(rootIndex) })
  end
  return matchesOut
end

local function selectOne(matchesOut, selector)
  if #matchesOut == 0 then
    fail("selector returned zero AX matches")
  end

  if selector.node_id then
    return matchesOut[1], #matchesOut
  end

  local nth = selector.nth and tonumber(selector.nth) or nil
  if nth then
    if nth < 1 or nth > #matchesOut then
      fail("selector nth is out of range")
    end
    return matchesOut[nth], #matchesOut
  end

  if #matchesOut ~= 1 then
    fail("selector is ambiguous; add --nth or narrow selector filters")
  end

  return matchesOut[1], #matchesOut
end

local function sanitize(value, depth)
  depth = depth or 0
  if depth > 6 then
    return tostring(value)
  end

  local kind = type(value)
  if kind == "nil" then
    return json.null
  end
  if kind == "string" or kind == "number" or kind == "boolean" then
    return value
  end
  if kind == "table" then
    local out = {}
    local count = 0
    local maxIndex = 0
    local isArray = true
    for key, _ in pairs(value) do
      count = count + 1
      if type(key) ~= "number" or key < 1 or key % 1 ~= 0 then
        isArray = false
        break
      end
      if key > maxIndex then maxIndex = key end
    end
    if isArray and maxIndex ~= count then
      isArray = false
    end
    if isArray then
      for i = 1, maxIndex do
        out[i] = sanitize(value[i], depth + 1)
      end
    else
      for key, child in pairs(value) do
        out[tostring(key)] = sanitize(child, depth + 1)
      end
    end
    return out
  end
  return tostring(value)
end

local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then
    fail("invalid payload JSON")
  end
  return payload
end

local payload = parsePayload()
local selector = payload.selector or {}
local app, target = resolveApp(payload.target)
if not app then
  fail("unable to resolve target app process for ax.attr.get")
end

local roots = rootsForApp(app, target)
local matchesOut = collectMatches(roots, selector)
local selected, matchedCount = selectOne(matchesOut, selector)
local name = normalize(payload.name)
if name == "" then
  fail("attribute name cannot be empty")
end
local value = sanitize(attr(selected.element, name, nil), 0)

return json.encode({
  node_id = selected.node.node_id,
  matched_count = matchedCount,
  name = name,
  value = value,
})
"#
);

const AX_ATTR_SET_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.attr.set",
    r#"
local function nodeFrom(element, path)
  return {
    node_id = table.concat(path, "."),
    role = normalize(attr(element, "AXRole", "")),
    title = normalize(attr(element, "AXTitle", "")),
    identifier = normalize(attr(element, "AXIdentifier", "")),
    subrole = normalize(attr(element, "AXSubrole", "")),
    value_preview = normalize(attr(element, "AXValue", "")),
    focused = boolAttr(element, "AXFocused", false),
    enabled = boolAttr(element, "AXEnabled", true),
  }
end

local function matches(node, selector)
  selector = selector or {}
  if selector.role and string.lower(node.role or "") ~= string.lower(tostring(selector.role)) then return false end
  if selector.title_contains and not string.find(string.lower(node.title or ""), string.lower(tostring(selector.title_contains)), 1, true) then return false end
  if selector.identifier_contains and not string.find(string.lower(node.identifier or ""), string.lower(tostring(selector.identifier_contains)), 1, true) then return false end
  if selector.value_contains and not string.find(string.lower(node.value_preview or ""), string.lower(tostring(selector.value_contains)), 1, true) then return false end
  if selector.subrole and string.lower(node.subrole or "") ~= string.lower(tostring(selector.subrole)) then return false end
  if selector.focused ~= nil and node.focused ~= selector.focused then return false end
  if selector.enabled ~= nil and node.enabled ~= selector.enabled then return false end
  return true
end

local function resolveByNodeId(roots, nodeId)
  local parts = {}
  for segment in string.gmatch(tostring(nodeId), "[^.]+") do table.insert(parts, tonumber(segment)) end
  if #parts == 0 then return nil end

  local rootIndex = parts[1]
  if not rootIndex or rootIndex < 1 or rootIndex > #roots then return nil end

  local element = roots[rootIndex]
  local path = { tostring(rootIndex) }
  for i = 2, #parts do
    local childIndex = parts[i]
    local directChildren = children(element)
    if not childIndex or childIndex < 1 or childIndex > #directChildren then return nil end
    element = directChildren[childIndex]
    table.insert(path, tostring(childIndex))
  end
  return { element = element, node = nodeFrom(element, path) }
end

local function collectMatches(roots, selector)
  local matchesOut = {}

  if selector.node_id then
    local byId = resolveByNodeId(roots, selector.node_id)
    if byId then table.insert(matchesOut, byId) end
    return matchesOut
  end

  local function walk(element, path)
    local node = nodeFrom(element, path)
    if matches(node, selector) then table.insert(matchesOut, { element = element, node = node }) end
    for index, child in ipairs(children(element)) do
      local childPath = copyPath(path)
      table.insert(childPath, tostring(index))
      walk(child, childPath)
    end
  end

  for rootIndex, root in ipairs(roots) do
    walk(root, { tostring(rootIndex) })
  end
  return matchesOut
end

local function selectOne(matchesOut, selector)
  if #matchesOut == 0 then fail("selector returned zero AX matches") end
  if selector.node_id then return matchesOut[1], #matchesOut end

  local nth = selector.nth and tonumber(selector.nth) or nil
  if nth then
    if nth < 1 or nth > #matchesOut then fail("selector nth is out of range") end
    return matchesOut[nth], #matchesOut
  end
  if #matchesOut ~= 1 then fail("selector is ambiguous; add --nth or narrow selector filters") end
  return matchesOut[1], #matchesOut
end

local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end

local payload = parsePayload()
local name = normalize(payload.name)
if name == "" then fail("attribute name cannot be empty") end

local app, target = resolveApp(payload.target)
if not app then fail("unable to resolve target app process for ax.attr.set") end

local roots = rootsForApp(app, target)
local matchesOut = collectMatches(roots, payload.selector or {})
local selected, matchedCount = selectOne(matchesOut, payload.selector or {})

local applied = safe(function()
  selected.element:setAttributeValue(name, payload.value)
  return true
end, false)
if not applied then
  fail("failed to set AX attribute value")
end

local valueType = type(payload.value)
if payload.value == json.null then
  valueType = "null"
end

return json.encode({
  node_id = selected.node.node_id,
  matched_count = matchedCount,
  name = name,
  applied = true,
  value_type = valueType,
})
"#
);

const AX_ACTION_PERFORM_HS_SCRIPT: &str = hs_ax_script_with_targeting_prelude!(
    "ax.action.perform",
    r#"
local function nodeFrom(element, path)
  return {
    node_id = table.concat(path, "."),
    role = normalize(attr(element, "AXRole", "")),
    title = normalize(attr(element, "AXTitle", "")),
    identifier = normalize(attr(element, "AXIdentifier", "")),
    subrole = normalize(attr(element, "AXSubrole", "")),
    value_preview = normalize(attr(element, "AXValue", "")),
    focused = boolAttr(element, "AXFocused", false),
    enabled = boolAttr(element, "AXEnabled", true),
  }
end
local function matches(node, selector)
  selector = selector or {}
  if selector.role and string.lower(node.role or "") ~= string.lower(tostring(selector.role)) then return false end
  if selector.title_contains and not string.find(string.lower(node.title or ""), string.lower(tostring(selector.title_contains)), 1, true) then return false end
  if selector.identifier_contains and not string.find(string.lower(node.identifier or ""), string.lower(tostring(selector.identifier_contains)), 1, true) then return false end
  if selector.value_contains and not string.find(string.lower(node.value_preview or ""), string.lower(tostring(selector.value_contains)), 1, true) then return false end
  if selector.subrole and string.lower(node.subrole or "") ~= string.lower(tostring(selector.subrole)) then return false end
  if selector.focused ~= nil and node.focused ~= selector.focused then return false end
  if selector.enabled ~= nil and node.enabled ~= selector.enabled then return false end
  return true
end
local function resolveByNodeId(roots, nodeId)
  local parts = {}
  for segment in string.gmatch(tostring(nodeId), "[^.]+") do table.insert(parts, tonumber(segment)) end
  if #parts == 0 then return nil end
  local rootIndex = parts[1]
  if not rootIndex or rootIndex < 1 or rootIndex > #roots then return nil end
  local element = roots[rootIndex]
  local path = { tostring(rootIndex) }
  for i = 2, #parts do
    local childIndex = parts[i]
    local directChildren = children(element)
    if not childIndex or childIndex < 1 or childIndex > #directChildren then return nil end
    element = directChildren[childIndex]
    table.insert(path, tostring(childIndex))
  end
  return { element = element, node = nodeFrom(element, path) }
end
local function collectMatches(roots, selector)
  local matchesOut = {}
  if selector.node_id then
    local byId = resolveByNodeId(roots, selector.node_id)
    if byId then table.insert(matchesOut, byId) end
    return matchesOut
  end
  local function walk(element, path)
    local node = nodeFrom(element, path)
    if matches(node, selector) then table.insert(matchesOut, { element = element, node = node }) end
    for index, child in ipairs(children(element)) do
      local childPath = copyPath(path)
      table.insert(childPath, tostring(index))
      walk(child, childPath)
    end
  end
  for rootIndex, root in ipairs(roots) do walk(root, { tostring(rootIndex) }) end
  return matchesOut
end
local function selectOne(matchesOut, selector)
  if #matchesOut == 0 then fail("selector returned zero AX matches") end
  if selector.node_id then return matchesOut[1], #matchesOut end
  local nth = selector.nth and tonumber(selector.nth) or nil
  if nth then
    if nth < 1 or nth > #matchesOut then fail("selector nth is out of range") end
    return matchesOut[nth], #matchesOut
  end
  if #matchesOut ~= 1 then fail("selector is ambiguous; add --nth or narrow selector filters") end
  return matchesOut[1], #matchesOut
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end

local payload = parsePayload()
local name = normalize(payload.name)
if name == "" then fail("action name cannot be empty") end

local app, target = resolveApp(payload.target)
if not app then fail("unable to resolve target app process for ax.action.perform") end

local roots = rootsForApp(app, target)
local matchesOut = collectMatches(roots, payload.selector or {})
local selected, matchedCount = selectOne(matchesOut, payload.selector or {})
local performed = safe(function()
  selected.element:performAction(name)
  return true
end, false)
if not performed then fail("failed to perform AX action") end

return json.encode({
  node_id = selected.node.node_id,
  matched_count = matchedCount,
  name = name,
  performed = true,
})
"#
);

const AX_SESSION_START_HS_SCRIPT: &str = r#"
local json = hs.json
local appmod = hs.application
local timer = hs.timer

local function fail(message) error(message, 0) end
local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end
local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end
local function nowMs()
  return math.floor((timer.secondsSinceEpoch and timer.secondsSinceEpoch() or os.time()) * 1000)
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end
local function resolveApp(target)
  target = target or {}
  if target.app and normalize(target.app) ~= "" then
    local found = appmod.find(normalize(target.app))
    if found then return found end
  end
  if target.bundle_id and normalize(target.bundle_id) ~= "" then
    local apps = appmod.applicationsForBundleID(normalize(target.bundle_id))
    if type(apps) == "table" and #apps > 0 then return apps[1] end
  end
  return appmod.frontmostApplication()
end
local function generateSessionId()
  return string.format("axs-%d-%d", os.time(), math.random(1000, 999999))
end

local payload = parsePayload()
local target = payload.target or {}
local app = resolveApp(target)
if not app then fail("unable to resolve target app process for ax.session.start") end

local state = ensureState()
local requestedId = normalize(payload.session_id)
if requestedId == "" then requestedId = normalize(target.session_id) end
if requestedId == "" then requestedId = generateSessionId() end
local existing = state.sessions[requestedId]

local createdAt = existing and existing.created_at_ms or nowMs()
local info = {
  session_id = requestedId,
  app = normalize(target.app) ~= "" and normalize(target.app) or app:name(),
  bundle_id = normalize(target.bundle_id) ~= "" and normalize(target.bundle_id) or app:bundleID(),
  pid = app:pid(),
  window_title_contains = target.window_title_contains and tostring(target.window_title_contains) or nil,
  created_at_ms = createdAt,
}
state.sessions[requestedId] = info

return json.encode({
  session_id = info.session_id,
  app = info.app,
  bundle_id = info.bundle_id,
  pid = info.pid,
  window_title_contains = info.window_title_contains,
  created_at_ms = info.created_at_ms,
  created = existing == nil,
})
"#;

const AX_SESSION_LIST_HS_SCRIPT: &str = r#"
local json = hs.json

local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end

local state = ensureState()
local sessions = {}
for _, session in pairs(state.sessions) do
  table.insert(sessions, {
    session_id = session.session_id,
    app = session.app,
    bundle_id = session.bundle_id,
    pid = session.pid,
    window_title_contains = session.window_title_contains,
    created_at_ms = session.created_at_ms or 0,
  })
end
table.sort(sessions, function(a, b) return (a.session_id or "") < (b.session_id or "") end)
return json.encode({ sessions = sessions })
"#;

const AX_SESSION_STOP_HS_SCRIPT: &str = r#"
local json = hs.json

local function fail(message) error(message, 0) end
local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end
local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end

local payload = parsePayload()
local sessionId = normalize(payload.session_id)
if sessionId == "" then fail("session_id cannot be empty") end

local state = ensureState()
local removed = state.sessions[sessionId] ~= nil
state.sessions[sessionId] = nil

for watchId, slot in pairs(state.watchers) do
  if slot and slot.session_id == sessionId then
    if slot.observer and slot.observer.stop then pcall(function() slot.observer:stop() end) end
    state.watchers[watchId] = nil
  end
end

return json.encode({
  session_id = sessionId,
  removed = removed,
})
"#;

const AX_WATCH_START_HS_SCRIPT: &str = r#"
local json = hs.json
local appmod = hs.application
local ax = hs.axuielement
local observermod = hs.axuielement and hs.axuielement.observer or nil
local timer = hs.timer

local function fail(message) error(message, 0) end
local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end
local function asTable(value)
  if type(value) == "table" then return value end
  return {}
end
local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end
local function nowMs()
  return math.floor((timer.secondsSinceEpoch and timer.secondsSinceEpoch() or os.time()) * 1000)
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end
local function generateWatchId()
  return string.format("axw-%d-%d", os.time(), math.random(1000, 999999))
end
local function resolveAppFromSession(session)
  if session.pid then
    local byPid = appmod.applicationForPID(tonumber(session.pid))
    if byPid then return byPid end
  end
  if session.app and normalize(session.app) ~= "" then
    local byName = appmod.find(normalize(session.app))
    if byName then return byName end
  end
  if session.bundle_id and normalize(session.bundle_id) ~= "" then
    local apps = appmod.applicationsForBundleID(normalize(session.bundle_id))
    if type(apps) == "table" and #apps > 0 then return apps[1] end
  end
  return nil
end

local payload = parsePayload()
local sessionId = normalize(payload.session_id)
if sessionId == "" then fail("session_id cannot be empty") end
local state = ensureState()
local session = state.sessions[sessionId]
if not session then fail("session_id does not exist") end

local app = resolveAppFromSession(session)
if not app then fail("unable to resolve app from session") end
if not observermod or not observermod.new then
  fail("AX observer backend unavailable in Hammerspoon runtime")
end

local watchId = normalize(payload.watch_id)
if watchId == "" then watchId = generateWatchId() end

local events = asTable(payload.events)
if #events == 0 then
  events = { "AXFocusedUIElementChanged", "AXTitleChanged" }
end
local normalizedEvents = {}
for _, eventName in ipairs(events) do
  local value = normalize(eventName)
  if value ~= "" then
    table.insert(normalizedEvents, value)
  end
end
if #normalizedEvents == 0 then
  normalizedEvents = { "AXFocusedUIElementChanged", "AXTitleChanged" }
end

local maxBuffer = tonumber(payload.max_buffer) or 256
if maxBuffer < 1 then maxBuffer = 1 end

local slot = state.watchers[watchId]
if slot and slot.observer and slot.observer.stop then
  pcall(function() slot.observer:stop() end)
end

local appElement = ax.applicationElement(app)
if not appElement then fail("unable to resolve AX application element from session") end
local pid = tonumber(session.pid) or app:pid()
if not pid then fail("unable to resolve app pid from session") end

slot = {
  watch_id = watchId,
  session_id = sessionId,
  events = normalizedEvents,
  max_buffer = maxBuffer,
  dropped = 0,
  buffer = {},
  observed_pid = pid,
}

local function safeAttr(element, name)
  local ok, value = pcall(function() return element:attributeValue(name) end)
  if ok then return value end
  return nil
end

local function callback(_, element, eventName, details)
  local current = state.watchers[watchId]
  if not current then return end
  local evt = {
    watch_id = watchId,
    event = tostring(eventName),
    at_ms = nowMs(),
    pid = current.observed_pid,
  }
  if element then
    local role = safeAttr(element, "AXRole")
    local title = safeAttr(element, "AXTitle")
    local identifier = safeAttr(element, "AXIdentifier")
    evt.role = role and tostring(role) or nil
    evt.title = title and tostring(title) or nil
    evt.identifier = identifier and tostring(identifier) or nil
  end
  table.insert(current.buffer, evt)
  while #current.buffer > current.max_buffer do
    table.remove(current.buffer, 1)
    current.dropped = (current.dropped or 0) + 1
  end
end

local observer = observermod.new(pid)
if not observer then fail("failed to create AX observer") end
observer:callback(callback)

local registered = {}
for _, eventName in ipairs(normalizedEvents) do
  local ok = pcall(function()
    observer:addWatcher(appElement, eventName)
  end)
  if ok then
    table.insert(registered, eventName)
  end
end
if #registered == 0 then
  fail("failed to register AX notifications for observer")
end

local started = pcall(function()
  observer:start()
end)
if not started then
  fail("failed to start AX observer")
end

slot.observer = observer
slot.events = registered
state.watchers[watchId] = slot

return json.encode({
  watch_id = watchId,
  session_id = sessionId,
  events = registered,
  max_buffer = maxBuffer,
  started = true,
})
"#;

const AX_WATCH_POLL_HS_SCRIPT: &str = r#"
local json = hs.json

local function fail(message) error(message, 0) end
local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end
local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end

local payload = parsePayload()
local watchId = normalize(payload.watch_id)
if watchId == "" then fail("watch_id cannot be empty") end
local limit = tonumber(payload.limit) or 50
if limit < 1 then limit = 1 end
local drain = payload.drain
if drain == nil then drain = true end

local state = ensureState()
local slot = state.watchers[watchId]
if not slot then fail("watch_id does not exist") end

local events = {}
local available = #slot.buffer
local take = math.min(available, limit)
for i = 1, take do
  table.insert(events, slot.buffer[i])
end

if drain then
  for _ = 1, take do
    table.remove(slot.buffer, 1)
  end
end

local running = false
if slot.observer and slot.observer.isRunning then
  local ok, value = pcall(function() return slot.observer:isRunning() end)
  if ok then running = value and true or false end
end

return json.encode({
  watch_id = watchId,
  events = events,
  dropped = slot.dropped or 0,
  running = running,
})
"#;

const AX_WATCH_STOP_HS_SCRIPT: &str = r#"
local json = hs.json

local function fail(message) error(message, 0) end
local function normalize(value)
  if value == nil then return "" end
  return tostring(value)
end
local function ensureState()
  _G.__codex_macos_agent_ax = _G.__codex_macos_agent_ax or { sessions = {}, watchers = {} }
  return _G.__codex_macos_agent_ax
end
local function parsePayload()
  local raw = cliPayloadArg("{}")
  local payload = json.decode(raw)
  if type(payload) ~= "table" then fail("invalid payload JSON") end
  return payload
end

local payload = parsePayload()
local watchId = normalize(payload.watch_id)
if watchId == "" then fail("watch_id cannot be empty") end
local state = ensureState()
local slot = state.watchers[watchId]
if not slot then
  return json.encode({ watch_id = watchId, stopped = false, drained = 0 })
end

local drained = #(slot.buffer or {})
if slot.observer and slot.observer.stop then
  pcall(function() slot.observer:stop() end)
end
state.watchers[watchId] = nil
return json.encode({
  watch_id = watchId,
  stopped = true,
  drained = drained,
})
"#;

#[derive(Debug, Default, Clone, Copy)]
pub struct HammerspoonAxBackend;

impl AxBackendAdapter for HammerspoonAxBackend {
    fn list(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxListRequest,
        timeout_ms: u64,
    ) -> Result<AxListResult, CliError> {
        run_hs_json(
            runner,
            "ax.list",
            request,
            AX_LIST_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn click(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxClickRequest,
        timeout_ms: u64,
    ) -> Result<AxClickResult, CliError> {
        if selector_is_empty(&request.selector) {
            return Err(
                CliError::ax_contract_failure("ax.click", "selector is empty")
                    .with_operation("ax.click.hammerspoon")
                    .with_hint("Provide --node-id or selector filters (--role/--title-contains)."),
            );
        }

        run_hs_json(
            runner,
            "ax.click",
            request,
            AX_CLICK_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn type_text(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxTypeRequest,
        timeout_ms: u64,
    ) -> Result<AxTypeResult, CliError> {
        if request.text.trim().is_empty() {
            return Err(
                CliError::usage("--text cannot be empty").with_operation("ax.type.hammerspoon")
            );
        }
        if selector_is_empty(&request.selector) {
            return Err(
                CliError::ax_contract_failure("ax.type", "selector is empty")
                    .with_operation("ax.type.hammerspoon")
                    .with_hint("Provide --node-id or selector filters (--role/--title-contains)."),
            );
        }

        run_hs_json(
            runner,
            "ax.type",
            request,
            AX_TYPE_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn attr_get(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxAttrGetRequest,
        timeout_ms: u64,
    ) -> Result<AxAttrGetResult, CliError> {
        if request.name.trim().is_empty() {
            return Err(
                CliError::usage("--name cannot be empty").with_operation("ax.attr.get.hammerspoon")
            );
        }
        if selector_is_empty(&request.selector) {
            return Err(
                CliError::ax_contract_failure("ax.attr.get", "selector is empty")
                    .with_operation("ax.attr.get.hammerspoon")
                    .with_hint("Provide --node-id or selector filters."),
            );
        }

        run_hs_json(
            runner,
            "ax.attr.get",
            request,
            AX_ATTR_GET_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn attr_set(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxAttrSetRequest,
        timeout_ms: u64,
    ) -> Result<AxAttrSetResult, CliError> {
        if request.name.trim().is_empty() {
            return Err(
                CliError::usage("--name cannot be empty").with_operation("ax.attr.set.hammerspoon")
            );
        }
        if selector_is_empty(&request.selector) {
            return Err(
                CliError::ax_contract_failure("ax.attr.set", "selector is empty")
                    .with_operation("ax.attr.set.hammerspoon")
                    .with_hint("Provide --node-id or selector filters."),
            );
        }

        run_hs_json(
            runner,
            "ax.attr.set",
            request,
            AX_ATTR_SET_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn action_perform(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxActionPerformRequest,
        timeout_ms: u64,
    ) -> Result<AxActionPerformResult, CliError> {
        if request.name.trim().is_empty() {
            return Err(CliError::usage("--name cannot be empty")
                .with_operation("ax.action.perform.hammerspoon"));
        }
        if selector_is_empty(&request.selector) {
            return Err(
                CliError::ax_contract_failure("ax.action.perform", "selector is empty")
                    .with_operation("ax.action.perform.hammerspoon")
                    .with_hint("Provide --node-id or selector filters."),
            );
        }

        run_hs_json(
            runner,
            "ax.action.perform",
            request,
            AX_ACTION_PERFORM_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn session_start(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxSessionStartRequest,
        timeout_ms: u64,
    ) -> Result<AxSessionStartResult, CliError> {
        run_hs_json(
            runner,
            "ax.session.start",
            request,
            AX_SESSION_START_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn session_list(
        &self,
        runner: &dyn ProcessRunner,
        timeout_ms: u64,
    ) -> Result<AxSessionListResult, CliError> {
        run_hs_json(
            runner,
            "ax.session.list",
            &serde_json::json!({}),
            AX_SESSION_LIST_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn session_stop(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxSessionStopRequest,
        timeout_ms: u64,
    ) -> Result<AxSessionStopResult, CliError> {
        if request.session_id.trim().is_empty() {
            return Err(CliError::usage("--session-id cannot be empty")
                .with_operation("ax.session.stop.hammerspoon"));
        }

        run_hs_json(
            runner,
            "ax.session.stop",
            request,
            AX_SESSION_STOP_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn watch_start(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxWatchStartRequest,
        timeout_ms: u64,
    ) -> Result<AxWatchStartResult, CliError> {
        if request.session_id.trim().is_empty() {
            return Err(CliError::usage("--session-id cannot be empty")
                .with_operation("ax.watch.start.hammerspoon"));
        }
        run_hs_json(
            runner,
            "ax.watch.start",
            request,
            AX_WATCH_START_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn watch_poll(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxWatchPollRequest,
        timeout_ms: u64,
    ) -> Result<AxWatchPollResult, CliError> {
        if request.watch_id.trim().is_empty() {
            return Err(CliError::usage("--watch-id cannot be empty")
                .with_operation("ax.watch.poll.hammerspoon"));
        }
        run_hs_json(
            runner,
            "ax.watch.poll",
            request,
            AX_WATCH_POLL_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }

    fn watch_stop(
        &self,
        runner: &dyn ProcessRunner,
        request: &AxWatchStopRequest,
        timeout_ms: u64,
    ) -> Result<AxWatchStopResult, CliError> {
        if request.watch_id.trim().is_empty() {
            return Err(CliError::usage("--watch-id cannot be empty")
                .with_operation("ax.watch.stop.hammerspoon"));
        }
        run_hs_json(
            runner,
            "ax.watch.stop",
            request,
            AX_WATCH_STOP_HS_SCRIPT,
            timeout_ms.max(1),
        )
    }
}

pub fn is_backend_unavailable_error(error: &CliError) -> bool {
    if !error
        .operation()
        .map(|operation| operation.ends_with(".hammerspoon"))
        .unwrap_or(false)
    {
        return false;
    }

    error
        .hints()
        .iter()
        .any(|hint| hint.starts_with(BACKEND_UNAVAILABLE_HINT_PREFIX))
}

fn run_hs_json<Request, Response>(
    runner: &dyn ProcessRunner,
    operation: &'static str,
    payload: &Request,
    script: &'static str,
    timeout_ms: u64,
) -> Result<Response, CliError>
where
    Request: Serialize,
    Response: DeserializeOwned,
{
    if let Some(override_json) = test_mode_override_json(operation) {
        return parse_hs_output(operation, &override_json);
    }

    if test_mode::enabled()
        && let Some(default_json) = test_mode_default_json(operation)
    {
        return parse_hs_output(operation, default_json);
    }

    let payload_json = serde_json::to_string(payload).map_err(|err| {
        CliError::ax_payload_encode(&format!("{operation}.hammerspoon"), err.to_string())
    })?;
    let timeout_seconds = format!("{:.3}", (timeout_ms.max(1) as f64) / 1000.0);

    let request = ProcessRequest::new(
        "hs",
        vec![
            "-q".to_string(),
            "-t".to_string(),
            timeout_seconds,
            "-c".to_string(),
            script.to_string(),
            "--".to_string(),
            payload_json,
        ],
        timeout_ms.max(1),
    );

    let stdout = runner
        .run(&request)
        .map(|output| output.stdout)
        .map_err(|failure| map_hs_failure(operation, failure))?;

    parse_hs_output(operation, &stdout)
}

fn parse_hs_output<Response>(operation: &str, raw: &str) -> Result<Response, CliError>
where
    Response: DeserializeOwned,
{
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err(CliError::ax_parse_failure(
            &format!("{operation}.hammerspoon"),
            "empty stdout",
        )
        .with_hint(
            "Ensure Hammerspoon is running and `hs.ipc` is enabled in ~/.hammerspoon/init.lua.",
        ));
    }

    serde_json::from_str(trimmed).map_err(|err| {
        CliError::ax_parse_failure(
            &format!("{operation}.hammerspoon"),
            format!("{err}; output preview: {}", output_preview(trimmed, 240)),
        )
        .with_hint("If backend mode is `auto`, macos-agent may fall back to JXA for AX commands.")
    })
}

fn map_hs_failure(operation: &str, failure: ProcessFailure) -> CliError {
    let operation_label = format!("{operation}.hammerspoon");

    match failure {
        ProcessFailure::NotFound { .. } => CliError::runtime(
            "hammerspoon AX backend is unavailable: missing dependency `hs` in PATH",
        )
        .with_operation(operation_label)
        .with_hint(
            "Hammerspoon backend unavailable; install Hammerspoon and ensure `hs` is in PATH.",
        )
        .with_hint("Auto mode will fall back to JXA AX backend."),
        ProcessFailure::Timeout { timeout_ms, .. } => CliError::timeout(
            &operation_label,
            timeout_ms,
        )
        .with_operation(operation_label)
        .with_hint("Hammerspoon backend unavailable; command timed out while connecting to hs IPC.")
        .with_hint(
            "Enable `require('hs.ipc')` in ~/.hammerspoon/init.lua and keep Hammerspoon running.",
        ),
        ProcessFailure::NonZero { code, stderr, .. } => {
            let lower = stderr.to_ascii_lowercase();
            let unavailable = lower.contains("message port")
                || lower.contains("ipc module")
                || lower.contains("is it running")
                || lower.contains("connection refused");

            let mut error = CliError::runtime(format!(
                "{operation_label} failed via `hs` (exit {code}): {stderr}"
            ))
            .with_operation(operation_label);

            if unavailable {
                error = error
                    .with_hint(
                        "Hammerspoon backend unavailable; hs cannot connect to Hammerspoon IPC.",
                    )
                    .with_hint(
                        "Enable `require('hs.ipc')` in ~/.hammerspoon/init.lua and reload config.",
                    )
                    .with_hint("Auto mode will fall back to JXA AX backend.");
            }

            error
        }
        ProcessFailure::Io { message, .. } => {
            CliError::runtime(format!("{operation_label} failed to run `hs`: {message}"))
                .with_operation(operation_label)
                .with_hint(
                    "Hammerspoon backend unavailable; check hs executable and local IPC state.",
                )
        }
    }
}

fn test_mode_override_json(operation: &str) -> Option<String> {
    if !test_mode::enabled() {
        return None;
    }

    let env_name = match operation {
        "ax.list" => AX_LIST_TEST_MODE_ENV,
        "ax.click" => AX_CLICK_TEST_MODE_ENV,
        "ax.type" => AX_TYPE_TEST_MODE_ENV,
        "ax.attr.get" => AX_ATTR_GET_TEST_MODE_ENV,
        "ax.attr.set" => AX_ATTR_SET_TEST_MODE_ENV,
        "ax.action.perform" => AX_ACTION_PERFORM_TEST_MODE_ENV,
        "ax.session.start" => AX_SESSION_START_TEST_MODE_ENV,
        "ax.session.list" => AX_SESSION_LIST_TEST_MODE_ENV,
        "ax.session.stop" => AX_SESSION_STOP_TEST_MODE_ENV,
        "ax.watch.start" => AX_WATCH_START_TEST_MODE_ENV,
        "ax.watch.poll" => AX_WATCH_POLL_TEST_MODE_ENV,
        "ax.watch.stop" => AX_WATCH_STOP_TEST_MODE_ENV,
        _ => return None,
    };

    std::env::var(env_name).ok().and_then(|raw| {
        let trimmed = raw.trim();
        if trimmed.is_empty() {
            None
        } else {
            Some(trimmed.to_string())
        }
    })
}

fn test_mode_default_json(operation: &str) -> Option<&'static str> {
    match operation {
        "ax.list" => Some(r#"{"nodes":[],"warnings":[]}"#),
        "ax.click" => Some(
            r#"{"node_id":"test-node","matched_count":1,"action":"ax-press","used_coordinate_fallback":false}"#,
        ),
        "ax.type" => Some(
            r#"{"node_id":"test-node","matched_count":1,"applied_via":"ax-set-value","text_length":0,"submitted":false,"used_keyboard_fallback":false}"#,
        ),
        "ax.attr.get" => {
            Some(r#"{"node_id":"test-node","matched_count":1,"name":"AXRole","value":"AXButton"}"#)
        }
        "ax.attr.set" => Some(
            r#"{"node_id":"test-node","matched_count":1,"name":"AXValue","applied":true,"value_type":"string"}"#,
        ),
        "ax.action.perform" => {
            Some(r#"{"node_id":"test-node","matched_count":1,"name":"AXPress","performed":true}"#)
        }
        "ax.session.start" => Some(
            r#"{"session_id":"axs-test","app":"Arc","bundle_id":"company.thebrowser.Browser","pid":1001,"created_at_ms":1700000000000,"created":true}"#,
        ),
        "ax.session.list" => Some(r#"{"sessions":[]}"#),
        "ax.session.stop" => Some(r#"{"session_id":"axs-test","removed":true}"#),
        "ax.watch.start" => Some(
            r#"{"watch_id":"axw-test","session_id":"axs-test","events":["AXTitleChanged"],"max_buffer":64,"started":true}"#,
        ),
        "ax.watch.poll" => {
            Some(r#"{"watch_id":"axw-test","events":[],"dropped":0,"running":true}"#)
        }
        "ax.watch.stop" => Some(r#"{"watch_id":"axw-test","stopped":true,"drained":0}"#),
        _ => None,
    }
}

fn selector_is_empty(selector: &AxSelector) -> bool {
    selector.node_id.is_none()
        && selector.role.is_none()
        && selector.title_contains.is_none()
        && selector.identifier_contains.is_none()
        && selector.value_contains.is_none()
        && selector.subrole.is_none()
        && selector.focused.is_none()
        && selector.enabled.is_none()
}

fn output_preview(raw: &str, max_chars: usize) -> String {
    let mut preview = raw.chars().take(max_chars).collect::<String>();
    if raw.chars().count() > max_chars {
        preview.push_str("...");
    }
    preview
}

#[cfg(test)]
mod tests {
    use nils_test_support::{EnvGuard, GlobalStateLock};
    use serde_json::json;

    use crate::backend::AxBackendAdapter;
    use crate::backend::hammerspoon::{
        is_backend_unavailable_error, map_hs_failure, output_preview, selector_is_empty,
    };
    use crate::backend::process::ProcessFailure;
    use crate::model::{
        AxActionPerformRequest, AxAttrGetRequest, AxAttrSetRequest, AxClickRequest, AxSelector,
        AxSessionStartRequest, AxSessionStopRequest, AxTarget, AxTypeRequest, AxWatchPollRequest,
        AxWatchStartRequest, AxWatchStopRequest,
    };

    fn node_selector() -> AxSelector {
        AxSelector {
            node_id: Some("1.1".to_string()),
            ..AxSelector::default()
        }
    }

    #[test]
    fn message_port_error_is_marked_backend_unavailable() {
        let error = map_hs_failure(
            "ax.list",
            ProcessFailure::NonZero {
                program: "hs".to_string(),
                code: 69,
                stderr: "can't access Hammerspoon message port Hammerspoon; is it running with the ipc module loaded?".to_string(),
            },
        );

        assert!(is_backend_unavailable_error(&error));
    }

    #[test]
    fn test_mode_override_is_honored_for_click() {
        let lock = GlobalStateLock::new();
        let _mode = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_TEST_MODE", "1");
        let _override = EnvGuard::set(
            &lock,
            "AGENTS_MACOS_AGENT_AX_CLICK_JSON",
            r#"{"node_id":"1.1","matched_count":1,"action":"ax-press","used_coordinate_fallback":false}"#,
        );

        let runner = crate::backend::process::RealProcessRunner;
        let request = crate::model::AxClickRequest {
            target: crate::model::AxTarget::default(),
            selector: crate::model::AxSelector {
                node_id: Some("1.1".to_string()),
                ..crate::model::AxSelector::default()
            },
            allow_coordinate_fallback: false,
            reselect_before_click: false,
            fallback_order: Vec::new(),
        };

        let result = super::HammerspoonAxBackend
            .click(&runner, &request, 1000)
            .expect("click should parse test override");
        assert_eq!(result.node_id.as_deref(), Some("1.1"));
        assert_eq!(result.matched_count, 1);
    }

    #[test]
    fn default_test_mode_fixtures_cover_all_hammerspoon_ax_operations() {
        let lock = GlobalStateLock::new();
        let _mode = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_TEST_MODE", "1");
        let backend = super::HammerspoonAxBackend;
        let runner = crate::backend::process::RealProcessRunner;

        let list = backend
            .list(&runner, &crate::model::AxListRequest::default(), 1000)
            .expect("list default fixture");
        assert!(list.nodes.is_empty());

        let click = backend
            .click(
                &runner,
                &AxClickRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    allow_coordinate_fallback: false,
                    reselect_before_click: false,
                    fallback_order: Vec::new(),
                },
                1000,
            )
            .expect("click default fixture");
        assert_eq!(click.matched_count, 1);

        let typ = backend
            .type_text(
                &runner,
                &AxTypeRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    text: "test".to_string(),
                    clear_first: false,
                    submit: false,
                    paste: false,
                    allow_keyboard_fallback: false,
                },
                1000,
            )
            .expect("type default fixture");
        assert_eq!(typ.applied_via, "ax-set-value");

        let attr_get = backend
            .attr_get(
                &runner,
                &AxAttrGetRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: "AXRole".to_string(),
                },
                1000,
            )
            .expect("attr get default fixture");
        assert_eq!(attr_get.name, "AXRole");

        let attr_set = backend
            .attr_set(
                &runner,
                &AxAttrSetRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: "AXValue".to_string(),
                    value: json!("hello"),
                },
                1000,
            )
            .expect("attr set default fixture");
        assert!(attr_set.applied);

        let action = backend
            .action_perform(
                &runner,
                &AxActionPerformRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: "AXPress".to_string(),
                },
                1000,
            )
            .expect("action default fixture");
        assert!(action.performed);

        let session_start = backend
            .session_start(
                &runner,
                &AxSessionStartRequest {
                    target: AxTarget::default(),
                    session_id: Some("axs-test".to_string()),
                },
                1000,
            )
            .expect("session start default fixture");
        assert_eq!(session_start.session.session_id, "axs-test");

        let session_list = backend
            .session_list(&runner, 1000)
            .expect("session list default fixture");
        assert!(session_list.sessions.is_empty());

        let session_stop = backend
            .session_stop(
                &runner,
                &AxSessionStopRequest {
                    session_id: "axs-test".to_string(),
                },
                1000,
            )
            .expect("session stop default fixture");
        assert!(session_stop.removed);

        let watch_start = backend
            .watch_start(
                &runner,
                &AxWatchStartRequest {
                    session_id: "axs-test".to_string(),
                    events: vec!["AXTitleChanged".to_string()],
                    max_buffer: 64,
                    watch_id: Some("axw-test".to_string()),
                },
                1000,
            )
            .expect("watch start default fixture");
        assert_eq!(watch_start.watch_id, "axw-test");

        let watch_poll = backend
            .watch_poll(
                &runner,
                &AxWatchPollRequest {
                    watch_id: "axw-test".to_string(),
                    limit: 10,
                    drain: true,
                },
                1000,
            )
            .expect("watch poll default fixture");
        assert!(watch_poll.running);

        let watch_stop = backend
            .watch_stop(
                &runner,
                &AxWatchStopRequest {
                    watch_id: "axw-test".to_string(),
                },
                1000,
            )
            .expect("watch stop default fixture");
        assert!(watch_stop.stopped);
    }

    #[test]
    fn validation_errors_are_reported_for_empty_hammerspoon_inputs() {
        let backend = super::HammerspoonAxBackend;
        let runner = crate::backend::process::RealProcessRunner;

        let click_err = backend
            .click(
                &runner,
                &AxClickRequest {
                    target: AxTarget::default(),
                    selector: AxSelector::default(),
                    allow_coordinate_fallback: false,
                    reselect_before_click: false,
                    fallback_order: Vec::new(),
                },
                1000,
            )
            .expect_err("empty click selector should fail");
        assert!(click_err.to_string().contains("selector is empty"));

        let type_err = backend
            .type_text(
                &runner,
                &AxTypeRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    text: "   ".to_string(),
                    clear_first: false,
                    submit: false,
                    paste: false,
                    allow_keyboard_fallback: false,
                },
                1000,
            )
            .expect_err("empty text should fail");
        assert!(type_err.to_string().contains("--text cannot be empty"));

        let attr_get_err = backend
            .attr_get(
                &runner,
                &AxAttrGetRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: " ".to_string(),
                },
                1000,
            )
            .expect_err("empty attr get name should fail");
        assert!(attr_get_err.to_string().contains("--name cannot be empty"));

        let attr_set_err = backend
            .attr_set(
                &runner,
                &AxAttrSetRequest {
                    target: AxTarget::default(),
                    selector: AxSelector::default(),
                    name: "AXValue".to_string(),
                    value: json!("hello"),
                },
                1000,
            )
            .expect_err("empty attr set selector should fail");
        assert!(attr_set_err.to_string().contains("selector is empty"));

        let action_err = backend
            .action_perform(
                &runner,
                &AxActionPerformRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: " ".to_string(),
                },
                1000,
            )
            .expect_err("empty action name should fail");
        assert!(action_err.to_string().contains("--name cannot be empty"));

        let session_stop_err = backend
            .session_stop(
                &runner,
                &AxSessionStopRequest {
                    session_id: " ".to_string(),
                },
                1000,
            )
            .expect_err("empty session id should fail");
        assert!(
            session_stop_err
                .to_string()
                .contains("--session-id cannot be empty")
        );

        let watch_start_err = backend
            .watch_start(
                &runner,
                &AxWatchStartRequest {
                    session_id: " ".to_string(),
                    events: vec![],
                    max_buffer: 10,
                    watch_id: None,
                },
                1000,
            )
            .expect_err("empty watch session should fail");
        assert!(
            watch_start_err
                .to_string()
                .contains("--session-id cannot be empty")
        );

        let watch_poll_err = backend
            .watch_poll(
                &runner,
                &AxWatchPollRequest {
                    watch_id: " ".to_string(),
                    limit: 10,
                    drain: true,
                },
                1000,
            )
            .expect_err("empty watch id should fail");
        assert!(
            watch_poll_err
                .to_string()
                .contains("--watch-id cannot be empty")
        );

        let watch_stop_err = backend
            .watch_stop(
                &runner,
                &AxWatchStopRequest {
                    watch_id: " ".to_string(),
                },
                1000,
            )
            .expect_err("empty watch id should fail");
        assert!(
            watch_stop_err
                .to_string()
                .contains("--watch-id cannot be empty")
        );
    }

    #[test]
    fn invalid_override_json_reports_parse_hint() {
        let lock = GlobalStateLock::new();
        let _mode = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_TEST_MODE", "1");
        let _override = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_AX_ATTR_GET_JSON", "not-json");

        let backend = super::HammerspoonAxBackend;
        let runner = crate::backend::process::RealProcessRunner;
        let err = backend
            .attr_get(
                &runner,
                &AxAttrGetRequest {
                    target: AxTarget::default(),
                    selector: node_selector(),
                    name: "AXRole".to_string(),
                },
                1000,
            )
            .expect_err("invalid json override should fail");
        let rendered = err.to_string();
        assert!(rendered.contains("output preview"));
    }

    #[test]
    fn empty_override_value_falls_back_to_default_fixture() {
        let lock = GlobalStateLock::new();
        let _mode = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_TEST_MODE", "1");
        let _override = EnvGuard::set(&lock, "AGENTS_MACOS_AGENT_AX_SESSION_LIST_JSON", "   ");

        let backend = super::HammerspoonAxBackend;
        let runner = crate::backend::process::RealProcessRunner;
        let result = backend
            .session_list(&runner, 1000)
            .expect("default fixture should be used");
        assert!(result.sessions.is_empty());
    }

    #[test]
    fn not_found_failure_is_marked_backend_unavailable() {
        let error = map_hs_failure(
            "ax.list",
            ProcessFailure::NotFound {
                program: "hs".to_string(),
            },
        );
        assert!(is_backend_unavailable_error(&error));
    }

    #[test]
    fn selector_and_preview_helpers_cover_expected_cases() {
        assert!(selector_is_empty(&AxSelector::default()));
        assert!(!selector_is_empty(&AxSelector {
            title_contains: Some("Save".to_string()),
            ..AxSelector::default()
        }));

        let preview = output_preview("abcdefghijklmnopqrstuvwxyz", 8);
        assert_eq!(preview, "abcdefgh...");
    }

    #[test]
    fn ax_list_script_prelude_has_valid_unquoted_fail_message() {
        assert!(
            !super::AX_LIST_HS_SCRIPT
                .contains("fail(\"unable to resolve target app process for \"#,"),
            "AX list prelude should not contain broken Rust concat tokens"
        );
        assert!(
            super::AX_LIST_HS_SCRIPT.contains(r#"fail("unable to resolve target app process")"#),
            "AX list prelude should keep an actionable target resolution failure"
        );
        assert!(
            super::AX_LIST_HS_SCRIPT.contains("local function cliPayloadArg(defaultValue)"),
            "AX list script should include CLI payload normalization helper"
        );
        assert!(
            super::AX_LIST_HS_SCRIPT.contains("if raw == \"--\" then"),
            "AX list script should skip CLI `--` separator before JSON decoding"
        );
        assert!(
            super::AX_LIST_HS_SCRIPT.contains("local raw = cliPayloadArg(\"{}\")"),
            "AX list parsePayload should read normalized CLI payload argument"
        );
    }
}