File size: 82,454 Bytes
c1c6a0c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Android TestGen Kit — the single source of every test helper, so a test's
NAVIGATION DEPTH and JUMP RIGOR are DECLARED (not inferred), uniformly recorded,
and self-auditable.

LOCATION AT RUNTIME: alongside the generated test files (testgen: $TESTGEN_DIR/eval/,
eval: the restored eval dir). READ-ONLY — never edit, copy, or reimplement it.
`import` it from every test file:

    import os, sys
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    from android_testgen_kit import *          # noqa: F403

WHY THIS EXISTS
  Helpers used to be re-emitted verbatim into every generated test file (~370
  lines x 6 files). That blew the output-token ceiling, forced a "write the script
  in pieces" protocol, let each copy drift, and duplicated one API key into every
  file. Everything mechanical now lives here; prompts carry only judgement.

  Two orthogonal properties decide whether a suite really exercises an app:
    * navigation DEPTH — how many SURFACES you cross before the assertion
                         (0 = first screen, 1 = one page/dialog/sheet, 2+ = deeper)
    * jump RIGOR       — what the assertion after the trigger actually checks
  Prose alone let these drift, so every behavioral test DECLARES both:

      @and_test(expects=("interaction_create_note", "interaction_create_note_vlm"))
      def test_create_note():
          ...
          record("interaction_create_note", ok, "behavior_wrong: ...",
                 depth=1, jump_kind="value", expect="list shows 'Milk'")

  jump_kind (verbatim strings — audit/stats key off them):
    "none"        no trigger; existence/gate only                  -> tier 0
    "liveness"    only "did not crash / still foreground"          -> tier 1 (weak; never ship)
    "reach"       a real surface jump: the TARGET surface's element
                  APPEARED *and* the SOURCE surface's DISAPPEARED   -> tier 2
    "transition"  a state flip (checked/enabled/selected/mode) with before->after -> tier 2
    "value"       a specific expected value/content was asserted    -> tier 3

WHAT A "SURFACE" IS ON ANDROID
  NOT the Activity — single-Activity Compose/Fragment apps never change it, so
  get_current_activity() cannot discriminate. A surface is the SET of visible
  discriminating element keys: and_showing() -> {"Button|Save", "TextView|Total"}.
  and_reach(before, after, target, source) therefore proves a real jump; reading a
  flat tree for an always-present element cannot fake it.

DETERMINISTIC DENOMINATOR
  Scoring is eval_pass_case / origin_total_case, so a test function MUST contribute
  the same number of records on every code path. @and_test(expects=(...)) owns the
  try/except and back-fills any declared-but-unrecorded name as a failure, and
  record() refuses duplicates. N is a literal in the decorator.

PORTABILITY (the same file scores the ORIGINAL and the RECREATION, whose package
name differs): always use the module-level PACKAGE (argv[1]). Never write a package
name, an .apk path, a /data/data path, or a pixel coordinate as a literal.
    python3 android_testgen_kit.py lint_sources <dir>     # flags all of those

SELF-AUDIT (report-only — these are GOALS, never a gate that blocks delivery):
    python3 android_testgen_kit.py audit        <results_dir>
    python3 android_testgen_kit.py lint         <results_dir>
    python3 android_testgen_kit.py lint_sources <testgen_dir>
    python3 android_testgen_kit.py audit_depth  <testgen_dir> [results_dir]
"""
from __future__ import annotations

import ast
import base64
import functools
import glob
import hashlib
import json
import math
import os
import re
import shlex
import subprocess
import sys
import time
import urllib.error
import urllib.request

KIT_API_VERSION = 1

# ── Runtime context ────────────────────────────────────────────────────────────
# argv[1] = package under test (ORIGINAL during testgen, RECREATION during eval).
# argv[2] / $RESULTS_DIR = where the eval JSON + screenshots go.
PACKAGE = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("PACKAGE", "")
RESULTS_DIR = (
    sys.argv[2]
    if len(sys.argv) > 2
    else os.environ.get("RESULTS_DIR", "/workspace/testgen/eval")
)
ADB = os.environ.get("ADB_PATH", "adb")
DEVICE = os.environ.get("DEVICE_SERIAL", "emulator-5554")

# Known emulator packages (from adb-tips). Used by type_text, never by tests.
CLIPPER_PKG = "ca.zgrs.clipper"
ADB_KEYBOARD_IME = "com.android.adbkeyboard/.AdbIME"

# ── Settling table (adb-tips §5). ANDROID_REMOTE=1 doubles it for tunnelled adb. ─
_REMOTE = os.environ.get("ANDROID_REMOTE", "") in ("1", "true", "yes")
_SETTLE_MULT = 2.0 if _REMOTE else 1.0
SETTLE = {
    "launch": 3.0,
    "tap": 1.0,
    "key": 0.5,
    "keyboard": 0.5,
    "dump": 1.0,
    "ime": 0.5,
    "text": 0.5,
    "swipe": 1.0,
    "dump_retry": 2.0,
}

JUMP_KINDS = {"none": 0, "liveness": 1, "reach": 2, "transition": 2, "value": 3}

# Double-axis quota TARGETS (fractions). rb_audit REPORTS these; they are NOT a
# gate. Tune here only — never restate them in a prompt.
QUOTAS = {
    "existence_max": 0.30,   # jump_kind=="none" share of ALL tests
    "interactive_min": 0.60,  # reach|transition|value share of ALL tests
    "depth_ge1_min": 0.40,   # depth>=1 share of INTERACTIVE tests
    "depth_ge2_min": 0.15,   # depth>=2 share of INTERACTIVE tests
    "value_min": 0.25,       # jump_kind=="value" share of INTERACTIVE tests
    # Suite-wide VLM budget, measured as vlm records / ALL records. The right
    # share is app-dependent (a chart/canvas app earns more than a list app) and
    # individual modules may legitimately contribute zero, so this is a BAND on
    # the whole suite, never a per-module requirement.
    "vlm_share_min": 0.30,
    "vlm_share_max": 0.50,
    "vlm_fine_min": 0.66,    # fine-grained share of VLM records
}

# Depth family (naming convention — see and_audit_depth). A test "crosses a
# surface" iff it calls a member of this family; and_back* pops one. Semantic
# aliases (and_enter_settings, and_reach_detail) match BY PREFIX, so the kit stays
# small and the authored tests stay diverse.
DEPTH_FWD_RE = re.compile(r"^and_(enter|reach)[a-z0-9_]*$")
DEPTH_BACK_RE = re.compile(r"^and_back[a-z0-9_]*$")
DEPTH_RESET_RE = re.compile(r"^and_reset_depth$")

# VLM tags. The fine-grained ones test an exact rendered property; and_audit
# computes the >=2/3 fine share from these instead of trusting self-report.
VLM_FINE_TAGS = {"color", "shape", "position", "size"}
VLM_TAGS = VLM_FINE_TAGS | {"layout", "content"}

# Failure-message taxonomy. and_lint flags a failed record that uses none of them.
FAIL_PREFIXES = ("setup_failed:", "feature_missing:", "behavior_wrong:", "exception:")

# Never tap these (tests mutate real device state).
DANGEROUS_TEXTS = [
    "delete", "remove", "clear", "reset", "erase", "discard", "uninstall",
    "sign out", "log out", "logout", "format", "wipe", "revoke", "deactivate",
    "删除", "移除", "清空", "清除", "重置", "退出登录", "注销", "格式化",
]

_MODULE_ALIAS = {
    "states": "states", "state": "states",
    "structure": "structure", "structures": "structure",
    "navigation": "navigation", "nav": "navigation",
    "interaction": "interaction", "interactions": "interaction",
    "computation": "computation", "computations": "computation",
    "text": "text", "texts": "text",
}

_DEPTH = 0            # surface counter for and_enter/and_back
_results: list[dict] = []
_seen: set[str] = set()
_module: str = ""
_screen_info: dict | None = None


def require_kit(min_version: int) -> None:
    """Fail loudly at import time if the kit is older than the test expects."""
    if KIT_API_VERSION < min_version:
        raise RuntimeError(
            f"android_testgen_kit v{KIT_API_VERSION} is older than the required "
            f"v{min_version}; the restored testcase bundle and the kit disagree"
        )


def _infer_module() -> str:
    stem = os.path.splitext(os.path.basename(sys.argv[0] or ""))[0]
    if stem.startswith("test_android_"):
        return _MODULE_ALIAS.get(stem[len("test_android_"):], stem[len("test_android_"):])
    return ""


def init(module: str = "", package: str = "", results_dir: str = "") -> None:
    """Optional. Overrides the values inferred from argv/env."""
    global _module, PACKAGE, RESULTS_DIR
    if module:
        _module = _MODULE_ALIAS.get(module, module)
    if package:
        PACKAGE = package
    if results_dir:
        RESULTS_DIR = results_dir


_module = _infer_module()


def tier_of(jump_kind: str) -> int:
    return JUMP_KINDS.get(jump_kind, 2)


def settle(kind: str = "tap") -> None:
    """Sleep the calibrated settling time for `kind` (see SETTLE)."""
    time.sleep(SETTLE.get(kind, 1.0) * _SETTLE_MULT)


# ══════════════════════════════════════════════════════════════════════════════
# (1) Results / recording
# ══════════════════════════════════════════════════════════════════════════════

def record(test_name, passed, message="", *, depth=None, jump_kind="none",
           expect="", tag=None, backfilled=False) -> bool:
    """Record ONE test result. Returns bool(passed).

    The three positional parameters are unchanged from the legacy inline helper.
    Everything new is keyword-only with a default, so old call sites still work.

    depth      surfaces this test crossed before asserting (see and_enter/and_reach)
    jump_kind  none | liveness | reach | transition | value
    expect     MANDATORY for reach/transition/value — the exact target you
               OBSERVED on the original app (and_lint flags an empty one)
    tag        for VLM records: color|shape|position|size|layout|content
    message    on failure, start it with setup_failed: / feature_missing: /
               behavior_wrong: / exception:
    """
    if test_name in _seen:
        print(f"  [DUP ] {_module}:{test_name} refused (already recorded) — "
              f"a duplicate would drift the denominator")
        return bool(passed)
    if jump_kind not in JUMP_KINDS:
        jump_kind = "none"
    d = _DEPTH if depth is None else int(depth)
    p = bool(passed)
    rec = {
        "test": test_name,
        "passed": p,
        "message": str(message),
        "depth": max(0, d),
        "jump_kind": jump_kind,
        "tier": tier_of(jump_kind),
        "expect": str(expect),
    }
    if tag:
        rec["tag"] = str(tag)
    if backfilled:
        rec["backfilled"] = True
    _results.append(rec)
    _seen.add(test_name)
    print(f"  [{'PASS' if p else 'FAIL'}] {_module}:{test_name} "
          f"(depth={rec['depth']}, {jump_kind})"
          + (f" {message}" if message and not p else ""))
    _flush()
    return p


def _payload(module_name: str) -> dict:
    """The eval JSON. Shape is byte-compatible with the legacy helper: the
    aggregator reads module/total/passed/pass_rate, and the results extraction
    reads the rule/vlm sub-objects. New keys ride inside results[] + `audit`."""
    rule = [r for r in _results if not r["test"].endswith("_vlm")]
    vlm = [r for r in _results if r["test"].endswith("_vlm")]
    rt, rp = len(rule), sum(1 for r in rule if r["passed"])
    vt, vp = len(vlm), sum(1 for r in vlm if r["passed"])
    total, passed = len(_results), sum(1 for r in _results if r["passed"])
    fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
    inter = [r for r in _results if r["jump_kind"] in ("reach", "transition", "value")]
    return {
        "module": module_name,
        "total": total,
        "passed": passed,
        "failed": total - passed,
        "pass_rate": round(passed / total, 4) if total else 0,
        "rule": {"total": rt, "passed": rp, "failed": rt - rp,
                 "pass_rate": round(rp / rt, 4) if rt else 0},
        "vlm": {"total": vt, "passed": vp, "failed": vt - vp,
                "pass_rate": round(vp / vt, 4) if vt else 0},
        "vlm_ratio": round(vt / rt, 4) if rt else 0,
        "audit": {
            "kit_api_version": KIT_API_VERSION,
            "existence": sum(1 for r in _results if r["jump_kind"] == "none"),
            "liveness": sum(1 for r in _results if r["jump_kind"] == "liveness"),
            "interactive": len(inter),
            "depth_ge1": sum(1 for r in inter if r["depth"] >= 1),
            "depth_ge2": sum(1 for r in inter if r["depth"] >= 2),
            "value": sum(1 for r in inter if r["jump_kind"] == "value"),
            "vlm_fine": fine,
        },
        "results": _results,
    }


def _write_json(path: str, data: dict) -> None:
    """Atomic write, so a mid-run SIGKILL never leaves a truncated JSON."""
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    tmp = path + ".tmp"
    with open(tmp, "w") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    os.replace(tmp, path)


def _flush() -> None:
    """Persist after EVERY record, so a timeout/emulator hang leaves N results
    instead of zero. save_results() stays the documented finalizer."""
    if not _module:
        return
    try:
        _write_json(os.path.join(RESULTS_DIR, f"android_{_module}_eval.json"),
                    _payload(_module))
    except Exception:
        pass


def save_results(module_name: str) -> dict:
    """MANDATORY finalizer. Authoritatively rewrites the eval JSON under the
    confirmed module name, prints the summary, and runs the in-process audit.
    Idempotent."""
    global _module
    _module = _MODULE_ALIAS.get(module_name, module_name)
    out = _payload(_module)
    path = os.path.join(RESULTS_DIR, f"android_{_module}_eval.json")
    _write_json(path, out)
    print(f"Results: {out['passed']}/{out['total']} passed "
          f"(rule: {out['rule']['passed']}/{out['rule']['total']}, "
          f"vlm: {out['vlm']['passed']}/{out['vlm']['total']}) -> {path}")
    try:
        and_audit(RESULTS_DIR)
        and_lint(RESULTS_DIR)
    except Exception as exc:
        print(f"[audit] skipped: {exc}")
    return out


def declared_names() -> list[str]:
    """Every record name produced so far. The eval run MUST produce this same set
    against the recreation — a missing feature FAILS, it never vanishes from the
    denominator."""
    return [r["test"] for r in _results]


def and_test(*, expects, module: str = ""):
    """Wrap a test function so it contributes EXACTLY len(expects) records on
    every code path — the deterministic-denominator guarantee.

    Any name in `expects` still unrecorded when the function returns or raises is
    back-filled as a failure. The literal also lets and_audit_depth attribute
    records to this function exactly.

        @and_test(expects=("states_toggle_dark", "states_toggle_dark_vlm"))
        def test_toggle_dark():
            ...
    """
    names = tuple(expects)

    def deco(fn):
        @functools.wraps(fn)
        def wrapper(*a, **kw):
            if module:
                init(module=module)
            err = ""
            try:
                return fn(*a, **kw)
            except Exception as exc:
                err = f"{type(exc).__name__}: {exc}"
                print(f"  [EXC ] {fn.__name__}: {err}")
                return None
            finally:
                for n in names:
                    if n not in _seen:
                        record(n, False,
                               f"exception: not_reached ({err})" if err
                               else "setup_failed: not_reached (no exception raised)",
                               backfilled=True)
        wrapper._and_expects = names
        return wrapper
    return deco


def run_suite(tests, module: str) -> dict:
    """Run every test, then finalize. Each test owns its own entry point, so one
    failure never cascades."""
    init(module=module)
    n_fix = len(fixture_names())
    print(f"=== {module}: {len(tests)} tests | package={PACKAGE}"
          + (f" | fixtures={n_fix}" if n_fix else "") + " ===")
    if n_fix and not push_fixtures():
        print("  [fixtures] WARNING: not all fixtures reached the device — every "
              "test that opens one will record setup_failed")
    for t in tests:
        and_reset_depth()
        try:
            t()
        except Exception as exc:
            print(f"  [EXC ] {getattr(t, '__name__', t)}: {exc}")
    return save_results(module)


# ══════════════════════════════════════════════════════════════════════════════
# (2) Device & adb primitives
# ══════════════════════════════════════════════════════════════════════════════

def adb_shell(*args, timeout: int = 30) -> str:
    """`adb -s $DEVICE shell ...` -> stdout. The -s serial is ALWAYS injected, so
    a multi-device host can never dispatch to the wrong emulator."""
    try:
        r = subprocess.run([ADB, "-s", DEVICE, "shell", *[str(a) for a in args]],
                           capture_output=True, text=True, timeout=timeout)
        return r.stdout.strip()
    except subprocess.TimeoutExpired:
        return ""
    except Exception:
        return ""


def adb_raw(*args, timeout: int = 30) -> str:
    """`adb -s $DEVICE ...` (no `shell`) — for install/pull/exec-out."""
    try:
        r = subprocess.run([ADB, "-s", DEVICE, *[str(a) for a in args]],
                           capture_output=True, text=True, timeout=timeout)
        return r.stdout.strip()
    except Exception:
        return ""


def device_online() -> bool:
    try:
        out = subprocess.run([ADB, "devices"], capture_output=True, text=True,
                             timeout=15).stdout
    except Exception:
        return False
    return any(ln.startswith(DEVICE) and ln.rstrip().endswith("device")
               for ln in out.splitlines()[1:])


def get_screen_info() -> dict:
    """Cached screen geometry. EVERY coordinate must be derived from this, never
    written as a literal — density and font scale differ across devices."""
    global _screen_info
    if _screen_info:
        return _screen_info
    m = re.search(r"(\d+)x(\d+)", adb_shell("wm", "size"))
    w, h = (int(m.group(1)), int(m.group(2))) if m else (1080, 2400)
    md = re.search(r"(\d+)", adb_shell("wm", "density"))
    _screen_info = {"width": w, "height": h,
                    "density": int(md.group(1)) if md else 440,
                    "center_x": w // 2, "center_y": h // 2}
    return _screen_info


def screencap(path: str) -> bool:
    """Screenshot to a local path. exec-out first; falls back to on-device
    screencap + pull, which is what survives a tunnelled adb connection."""
    os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
    try:
        with open(path, "wb") as f:
            subprocess.run([ADB, "-s", DEVICE, "exec-out", "screencap", "-p"],
                           stdout=f, timeout=20)
        if os.path.getsize(path) > 0:
            return True
    except Exception:
        pass
    remote = "/sdcard/_kit_shot.png"
    adb_shell("screencap", "-p", remote)
    adb_raw("pull", remote, path, timeout=40)
    adb_shell("rm", "-f", remote)
    return os.path.exists(path) and os.path.getsize(path) > 0


# ── Fixtures: sample files a file/image/document app needs to have anything to
# open. These MUST be a pipeline artifact, not something you push by hand while
# exploring: testgen and eval run in DIFFERENT jobs on DIFFERENT emulators, so a
# hand-pushed file is gone by eval and every test that opens it records
# setup_failed — blaming the recreation for a harness gap.
#
#   authoring (once, during recon):  write the files into <EVAL_OUT>/fixtures/
#   consuming (every test run):      run_suite() pushes them before the first test
#
# The directory rides along with the test files into the testcases bank, so the
# bytes are restored on every later eval. Sub-directories are preserved, so
# fixtures/docs/a.pdf lands at /sdcard/Download/docs/a.pdf.
FIXTURES_DEVICE_DIR = "/sdcard/Download"
_fixtures_pushed = False


def fixtures_dir() -> str:
    """The host fixtures directory, or "" when this app needs none.

    The script's own directory comes FIRST: at eval, RESULTS_DIR is a separate
    eval_results/ dir, while the fixtures were restored next to the test files.
    """
    for cand in (os.environ.get("FIXTURES_DIR", ""),
                 os.path.join(os.path.dirname(os.path.abspath(sys.argv[0] or ".")),
                              "fixtures"),
                 os.path.join(RESULTS_DIR, "fixtures")):
        if cand and os.path.isdir(cand):
            return cand
    return ""


def fixture_names() -> list[str]:
    """Fixture paths relative to fixtures_dir(), e.g. ["doc.pdf", "docs/b.epub"]."""
    src = fixtures_dir()
    if not src:
        return []
    out = []
    for root, _dirs, files in os.walk(src):
        for fn in sorted(files):
            if fn.startswith("."):
                continue
            out.append(os.path.relpath(os.path.join(root, fn), src))
    return sorted(out)


def fixture_on_device(name: str, dest: str = FIXTURES_DEVICE_DIR) -> str:
    """Where `name` lives on the device after push_fixtures()."""
    return f"{dest.rstrip('/')}/{name}"


def push_fixtures(dest: str = FIXTURES_DEVICE_DIR, *, force: bool = False) -> bool:
    """Mirror the host fixtures onto the device. Idempotent and safe to call from
    every test — a file already there with the same size is not re-pushed, so the
    six module processes cost one real push between them.

    Returns True when the device holds every fixture (including the vacuous case
    of an app that needs none).
    """
    global _fixtures_pushed
    if _fixtures_pushed and not force:
        return True
    src = fixtures_dir()
    names = fixture_names()
    if not src or not names:
        _fixtures_pushed = True
        return True
    ok = True
    pushed = 0
    for rel in names:
        local = os.path.join(src, rel)
        remote = fixture_on_device(rel, dest)
        try:
            want = os.path.getsize(local)
        except OSError:
            ok = False
            continue
        got = adb_shell("stat", "-c", "%s", remote)
        if not force and got.isdigit() and int(got) == want:
            continue
        parent = remote.rsplit("/", 1)[0]
        if parent:
            adb_shell("mkdir", "-p", parent)
        adb_raw("push", local, remote, timeout=120)
        check = adb_shell("stat", "-c", "%s", remote)
        if check.isdigit() and int(check) == want:
            pushed += 1
        else:
            ok = False
            print(f"  [fixtures] FAILED to push {rel} -> {remote}")
    if pushed:
        # Make the files visible to gallery/media-backed pickers. Both forms are
        # API-level dependent and neither is required for plain SAF browsing, so
        # failures here are not fatal.
        adb_shell("content", "call", "--uri", "content://media/external/file",
                  "--method", "scan_volume", "--arg", "external_primary")
        adb_shell("am", "broadcast", "-a",
                  "android.intent.action.MEDIA_SCANNER_SCAN_FILE",
                  "-d", f"file://{dest}")
        print(f"  [fixtures] pushed {pushed}/{len(names)} fixture(s) to {dest}")
    _fixtures_pushed = ok
    return ok


# ══════════════════════════════════════════════════════════════════════════════
# (3) UI tree query & element matching
# ══════════════════════════════════════════════════════════════════════════════

def dump_xml(retries: int = 3, settle_first: bool = True) -> str:
    """uiautomator dump -> XML text. Retries because the dump fails outright
    while an animation is in flight."""
    if settle_first:
        settle("dump")
    remote = "/sdcard/_kit_ui.xml"
    for attempt in range(retries):
        adb_shell("uiautomator", "dump", remote)
        xml = adb_shell("cat", remote, timeout=60)
        if "<node" in xml:
            return xml
        settle("dump_retry")
    return ""


def parse_nodes(xml_str: str) -> list[dict]:
    """XML -> list of attribute dicts, each with _bounds and _center."""
    nodes = []
    for m in re.finditer(r"<node\s+([^>]+?)/?>", xml_str):
        attrs_str = m.group(1)
        attrs = {am.group(1): am.group(2)
                 for am in re.finditer(r'([\w-]+)="([^"]*)"', attrs_str)}
        b = re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', attrs_str)
        if b:
            x1, y1, x2, y2 = (int(v) for v in b.groups())
            attrs["_bounds"] = (x1, y1, x2, y2)
            attrs["_center"] = ((x1 + x2) // 2, (y1 + y2) // 2)
        nodes.append(attrs)
    return nodes


def ui(retries: int = 3) -> list[dict]:
    """THE entry point for a fresh tree. Call it again after ANY state change —
    a scroll, navigation, dialog, or keyboard invalidates every prior coordinate."""
    return parse_nodes(dump_xml(retries=retries))


def find_nodes(nodes, **criteria) -> list[dict]:
    """Nodes matching ALL criteria, EXACT string match. `True`/`False` match the
    "true"/"false" attribute strings. Underscores in keys become dashes
    (content_desc -> content-desc)."""
    out = []
    for n in nodes:
        ok = True
        for k, v in criteria.items():
            key = k.replace("_", "-") if "_" in k and k != "class" else k
            if key not in n:
                ok = False
                break
            if v is True and n[key] != "true":
                ok = False
                break
            if v is False and n[key] != "false":
                ok = False
                break
            if v is not True and v is not False and n[key] != v:
                ok = False
                break
        if ok:
            out.append(n)
    return out


def find_node(nodes, **criteria) -> dict | None:
    f = find_nodes(nodes, **criteria)
    return f[0] if f else None


def find_by_class(nodes, widget_class: str) -> list[dict]:
    """Partial class-name match, e.g. "Switch", "EditText", "RecyclerView"."""
    return [n for n in nodes if widget_class in n.get("class", "")]


def find_node_ci(nodes, text: str) -> dict | None:
    """Case-insensitive text or content-desc match. Use for user-visible labels
    whose casing a faithful recreation may legitimately differ on."""
    t = text.strip().lower()
    for n in nodes:
        if (n.get("text", "").strip().lower() == t
                or n.get("content-desc", "").strip().lower() == t):
            return n
    return None


def node_by_id(nodes, rid_suffix: str) -> dict | None:
    """Match the LAST segment of resource-id, so the package prefix (which
    differs between original and recreation) is never compared."""
    for n in nodes:
        rid = n.get("resource-id", "")
        if rid and rid.rsplit("/", 1)[-1] == rid_suffix:
            return n
    return None


def find_closest_match(nodes, original_node) -> dict | None:
    """Re-locate a node in a fresh dump by similarity (class/text/desc/position)."""
    best, best_score = None, 0
    for n in nodes:
        score = 0
        if n.get("class") == original_node.get("class"):
            score += 3
        if n.get("text") and n.get("text") == original_node.get("text"):
            score += 5
        if (n.get("content-desc")
                and n.get("content-desc") == original_node.get("content-desc")):
            score += 4
        if "_center" in n and "_center" in original_node:
            if (abs(n["_center"][0] - original_node["_center"][0]) < 100
                    and abs(n["_center"][1] - original_node["_center"][1]) < 100):
                score += 2
        if score > best_score:
            best, best_score = n, score
    return best if best_score >= 3 else None


def node_key(n: dict) -> str:
    """"{shortClass}|{identity}" — the surface-membership key. Identity priority:
    text -> content-desc -> resource-id suffix. Returns "" for anonymous nodes
    (pure layout containers), which are excluded from a surface."""
    cls = n.get("class", "").rsplit(".", 1)[-1]
    ident = (n.get("text", "").strip()
             or n.get("content-desc", "").strip()
             or n.get("resource-id", "").rsplit("/", 1)[-1])
    return f"{cls}|{ident}" if ident else ""


def and_showing(nodes=None) -> set[str]:
    """Snapshot the current SURFACE as a set of discriminating element keys.
    Only on-screen, non-degenerate, identity-bearing nodes count. Take one
    before and one after a trigger and feed them to and_reach()."""
    nodes = ui() if nodes is None else nodes
    s = get_screen_info()
    out = set()
    for n in nodes:
        b = n.get("_bounds")
        if not b:
            continue
        x1, y1, x2, y2 = b
        if (x2 - x1) < 5 or (y2 - y1) < 5:
            continue
        if x2 <= 0 or y2 <= 0 or x1 >= s["width"] or y1 >= s["height"]:
            continue
        k = node_key(n)
        if k:
            out.add(k)
    return out


def and_reach(before, after, target: str, source: str | None = None) -> bool:
    """TRUE-JUMP verdict: the TARGET surface's element newly APPEARED and (if
    given) the SOURCE surface's element DISAPPEARED. This is what separates a
    real surface jump from reading an element that was in the tree all along."""
    before, after = set(before or []), set(after or [])
    t = target.strip().lower()
    appeared = any(t in k.lower() for k in (after - before))
    if source is None:
        return appeared
    s = source.strip().lower()
    return (appeared
            and any(s in k.lower() for k in before)
            and not any(s in k.lower() for k in after))


def surface_changed(before, after, min_delta: int = 2) -> bool:
    """Weaker than and_reach: the surface changed materially but you are not
    naming the target. Use for shape deltas, never to claim a `reach`."""
    return len(set(before or []) ^ set(after or [])) >= min_delta


def and_surface_id(nodes=None) -> str:
    """A stable-ish fingerprint of the current surface, for "did this change?"."""
    keys = sorted(and_showing(nodes))
    return f"{len(keys)}:{hash(tuple(keys)) & 0xFFFFFF:06x}"


# ══════════════════════════════════════════════════════════════════════════════
# (4) Interaction
# ══════════════════════════════════════════════════════════════════════════════

def tap(x, y) -> None:
    adb_shell("input", "tap", int(x), int(y))
    settle("tap")


def tap_node(node) -> bool:
    """Tap a node's centre, validating bounds against the real screen first."""
    if not node or "_center" not in node:
        return False
    x, y = node["_center"]
    s = get_screen_info()
    if x < 0 or x > s["width"] or y < 0 or y > s["height"]:
        return False
    if "_bounds" in node:
        x1, y1, x2, y2 = node["_bounds"]
        if (x2 - x1) < 5 or (y2 - y1) < 5:
            return False
    tap(x, y)
    return True


def tap_text(nodes, text: str) -> bool:
    n = find_node(nodes, text=text) or find_node_ci(nodes, text)
    return tap_node(n) if n else False


def is_safe(node) -> bool:
    """False for destructive controls. Tests mutate real device state, so every
    exploratory tap must go through this."""
    blob = " ".join([node.get("text", ""), node.get("content-desc", ""),
                     node.get("resource-id", "")]).lower()
    return not any(d in blob for d in DANGEROUS_TEXTS)


def safe_tap(node) -> bool:
    return tap_node(node) if node and is_safe(node) else False


def long_press(node, ms: int = 800) -> bool:
    """Long-press = a zero-distance swipe with a duration."""
    if not node or "_center" not in node:
        return False
    x, y = node["_center"]
    adb_shell("input", "swipe", x, y, x, y, int(ms))
    settle("tap")
    return True


def swipe(x1, y1, x2, y2, ms: int = 300) -> None:
    adb_shell("input", "swipe", int(x1), int(y1), int(x2), int(y2), int(ms))
    settle("swipe")


def scroll_down(frac: float = 0.5) -> None:
    s = get_screen_info()
    swipe(s["center_x"], int(s["height"] * 0.7),
          s["center_x"], int(s["height"] * (0.7 - frac)))


def scroll_up(frac: float = 0.5) -> None:
    s = get_screen_info()
    swipe(s["center_x"], int(s["height"] * 0.3),
          s["center_x"], int(s["height"] * (0.3 + frac)))


def open_drawer() -> None:
    s = get_screen_info()
    swipe(5, s["center_y"], int(s["width"] * 0.8), s["center_y"], ms=400)


def scroll_into_view(text: str, max_swipes: int = 4) -> dict | None:
    """Scroll until `text` is on screen, RE-DUMPING between swipes. This encodes
    "after a scroll every previous coordinate is invalid" as code."""
    for _ in range(max_swipes + 1):
        nodes = ui()
        n = find_node(nodes, text=text) or find_node_ci(nodes, text)
        if n:
            return n
        scroll_down(0.4)
    return None


def press_key(keycode) -> None:
    adb_shell("input", "keyevent", keycode)
    settle("key")


def back() -> None:
    """Raw BACK. Use and_back() when you are leaving a surface you entered."""
    press_key("KEYCODE_BACK")


def home() -> None:
    press_key("KEYCODE_HOME")


def enter() -> None:
    press_key("KEYCODE_ENTER")


def keyboard_visible() -> bool:
    return "mInputShown=true" in adb_shell("dumpsys", "input_method")


def hide_keyboard() -> bool:
    """Dismiss the soft keyboard without navigating away. Tries, in order: the
    collapse affordance, an empty region, then BACK — and BACK is only accepted
    if the surface did NOT change, because BACK can navigate instead."""
    if not keyboard_visible():
        return True
    nodes = ui()
    for n in nodes:
        blob = (n.get("content-desc", "") + n.get("resource-id", "")).lower()
        if any(w in blob for w in ("hide", "collapse", "close_keyboard", "back")):
            if tap_node(n):
                settle("keyboard")
                if not keyboard_visible():
                    return True
    s = get_screen_info()
    tap(s["center_x"], int(s["height"] * 0.12))   # top strip is rarely interactive
    settle("keyboard")
    if not keyboard_visible():
        return True
    sid = and_surface_id()
    back()
    settle("keyboard")
    if keyboard_visible():
        return False
    if and_surface_id() != sid:
        print("  [warn] hide_keyboard: BACK also changed the surface")
    return True


def _quote_for_device(text: str) -> str:
    """Quote a string for the on-device shell (adb joins argv with spaces)."""
    return shlex.quote(text)


def type_text(node, text: str, *, method: str = "auto",
              verify_focus: bool = True) -> bool:
    """Type into an EditText, safely.

    An unfocused EditText silently swallows ALL input (including paste and the
    ADB-Keyboard broadcast), so this taps the field, re-dumps, and asserts
    focused="true" before typing — retrying the tap once.

    Routing: pure ASCII -> `input text`. Non-ASCII -> Clipper broadcast + paste.
    method="ime" -> ADB Keyboard, which needs a re-tap after the IME switch (the
    switch drops focus) and ALWAYS restores the original IME in a finally.
    """
    if not node:
        return False
    target = node
    if verify_focus:
        ok = False
        for _ in range(2):
            if not tap_node(target):
                return False
            settle("keyboard")
            fresh = find_closest_match(ui(), target) or target
            if fresh.get("focused") == "true":
                target, ok = fresh, True
                break
            target = fresh
        if not ok:
            print("  [warn] type_text: field never reported focused=true")
    else:
        tap_node(target)
        settle("keyboard")

    is_ascii = all(ord(c) < 128 for c in text)
    use = method
    if use == "auto":
        use = "input" if is_ascii else "clipper"

    if use == "input":
        adb_shell("input", "text", _quote_for_device(text.replace(" ", "%s")))
        settle("text")
        return True

    if use == "clipper":
        adb_shell("am", "broadcast", "-a", "clipper.set",
                  "-e", "text", _quote_for_device(text))
        settle("text")
        press_key(279)                                  # KEYCODE_PASTE
        settle("text")
        return True

    # method="ime": ADB Keyboard. Some custom views ignore paste, this is the fallback.
    original = adb_shell("settings", "get", "secure", "default_input_method")
    try:
        adb_shell("ime", "set", ADB_KEYBOARD_IME)
        settle("ime")
        tap_node(target)                                # IME switch dropped focus
        settle("keyboard")
        adb_shell("am", "broadcast", "-a", "ADB_INPUT_TEXT",
                  "--es", "msg", _quote_for_device(text))
        settle("text")
        return True
    finally:
        if original and "null" not in original.lower():
            adb_shell("ime", "set", original)           # NEVER leave it switched
            settle("ime")


# ══════════════════════════════════════════════════════════════════════════════
# (5) Navigation & the depth family
# ══════════════════════════════════════════════════════════════════════════════

def and_reset_depth() -> None:
    global _DEPTH
    _DEPTH = 0


def and_enter(surface: str = "") -> int:
    """Call right AFTER your test navigates into a new surface. This is what
    backs a declared depth>=1 — and_audit_depth looks for a call from the
    and_enter*/and_reach* family."""
    global _DEPTH
    _DEPTH += 1
    return _DEPTH


def and_back() -> int:
    """Press BACK and pop one surface."""
    global _DEPTH
    back()
    _DEPTH = max(0, _DEPTH - 1)
    return _DEPTH


def and_enter_surface(nodes, target_text: str = "", content_desc: str = "",
                      rid: str = "") -> tuple[bool, str]:
    """Tap a named trigger, then confirm the surface changed. Counts one surface
    on success. Returns (ok, note). Prefer and_reach_surface when you can name
    the destination — that yields jump_kind="reach"."""
    n = None
    if target_text:
        n = find_node(nodes, text=target_text) or find_node_ci(nodes, target_text)
    if n is None and content_desc:
        n = find_node(nodes, content_desc=content_desc)
    if n is None and rid:
        n = node_by_id(nodes, rid)
    if n is None:
        return False, f"setup_failed: trigger not found ({target_text or content_desc or rid})"
    before = and_showing(nodes)
    if not tap_node(n):
        return False, "setup_failed: trigger not tappable"
    after = and_showing()
    if not surface_changed(before, after):
        return False, "behavior_wrong: surface did not change after tapping the trigger"
    and_enter(target_text or content_desc or rid)
    return True, ""


def and_reach_surface(node, target: str, source: str | None = None) -> bool:
    """Tap `node`, then PROVE the jump: `target` appeared and `source` vanished.
    Counts one surface. This is the only honest way to claim jump_kind="reach"."""
    before = and_showing()
    if not tap_node(node):
        return False
    after = and_showing()
    ok = and_reach(before, after, target, source)
    if ok:
        and_enter(target)
    return ok


# ══════════════════════════════════════════════════════════════════════════════
# (6) App lifecycle — always keyed on PACKAGE (argv[1]), never a literal
# ══════════════════════════════════════════════════════════════════════════════

def launch_app() -> None:
    adb_shell("monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1")
    settle("launch")


def force_stop() -> None:
    adb_shell("am", "force-stop", PACKAGE)
    settle("key")


def clear_data() -> None:
    """Wipe app data. Use to guarantee a clean entry point, never mid-assertion."""
    adb_shell("pm", "clear", PACKAGE)
    settle("key")


def restart_app() -> None:
    force_stop()
    launch_app()


def force_stop_and_relaunch() -> None:
    """The persistence probe: kill the process, relaunch, then assert the state
    survived. An in-memory-only recreation fails this."""
    force_stop()
    settle("key")
    launch_app()


def get_current_activity() -> str:
    out = adb_shell("dumpsys", "activity", "activities")
    m = re.search(r"mResumedActivity.*?\{[^}]*?([\w.]+/[\w.$]+)", out)
    if m:
        return m.group(1)
    m = re.search(r"mCurrentFocus=.*?\{[^}]*?([\w.]+/[\w.$]+)", adb_shell("dumpsys", "window"))
    return m.group(1) if m else ""


def is_app_foreground() -> bool:
    return PACKAGE in get_current_activity() or PACKAGE in adb_shell("dumpsys", "window")


def wait_for_foreground(timeout: int = 10) -> bool:
    deadline = time.time() + timeout
    while time.time() < deadline:
        if is_app_foreground():
            return True
        time.sleep(0.5)
    return False


# ══════════════════════════════════════════════════════════════════════════════
# (7) VLM
# ══════════════════════════════════════════════════════════════════════════════

# OpenAI-compatible endpoint. Hardcoded on purpose: the public DashScope native
# endpoint rejected the key that pods are provisioned with, so every generated
# suite either lost its whole VLM track or shipped a hand-rolled `dashscope.py`
# shim to reroute it. This speaks plain chat/completions over the standard library
# only — no `pip install`, and the stale shims in the testcases bank can no longer
# shadow the transport because nothing imports `dashscope` any more.
VLM_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
_VLM_DEFAULT_KEY = "sk-bd0c3f375649439bba62b5b0e8c13057"
# Attempts per key. 3 covers the blips seen in practice (empty body, gateway 5xx,
# rate-limit bursts) without turning a genuine outage into a 10-minute stall.
VLM_RETRIES = int(os.environ.get("VLM_RETRIES", "3"))
# Repeating these cannot help: the request itself is wrong (malformed, missing,
# too large, or semantically rejected). Everything else 4xx/5xx is worth a retry.
_VLM_TERMINAL_CODES = {400, 404, 413, 422}


def _vlm_key() -> str:
    """The judge model's API key: first non-empty of DASHSCOPE_API_KEY,
    VLM_API_KEY, JUDGE_API_KEY. Empty when none is set."""
    for name in ("DASHSCOPE_API_KEY", "VLM_API_KEY", "JUDGE_API_KEY"):
        v = os.environ.get(name, "").strip()
        if v:
            return v
    return ""


def call_vlm(image_path: str, prompt: str, *, retries: int = 0) -> str | None:
    """Ask the VLM one question about a local screenshot. Returns the answer text.

    Retries transient API failures (empty body, 429, 408/409/425, any 5xx) up to
    `retries` times — default VLM_RETRIES (3), overridable via the VLM_RETRIES env
    var. Terminal errors (bad key, malformed/oversized request) are not retried.
    """
    retries = retries or VLM_RETRIES
    key = _vlm_key() or _VLM_DEFAULT_KEY
    try:
        with open(image_path, "rb") as f:
            b64 = base64.b64encode(f.read()).decode()
    except Exception as exc:
        print(f"[VLM] cannot read screenshot {image_path}: {exc}")
        return None
    mime = "image/jpeg" if image_path.lower().endswith((".jpg", ".jpeg")) else "image/png"
    body = json.dumps({
        "model": os.environ.get("JUDGE_MODEL", "qwen3.7-plus"),
        "temperature": 0,
        "messages": [{"role": "user", "content": [
            {"type": "image_url",
             "image_url": {"url": f"data:{mime};base64,{b64}"}},
            {"type": "text", "text": prompt},
        ]}],
    }).encode()

    for attempt in range(retries):
        backoff = 2 * (attempt + 1)
        req = urllib.request.Request(
            f"{VLM_BASE_URL}/chat/completions", data=body,
            headers={"Authorization": f"Bearer {key}",
                     "Content-Type": "application/json"})
        try:
            with urllib.request.urlopen(req, timeout=120) as resp:
                data = json.loads(resp.read().decode())
            text = (data["choices"][0]["message"]["content"] or "").strip()
            if text:
                return text
            print(f"[VLM] empty response (attempt {attempt + 1}/{retries})")
        except urllib.error.HTTPError as exc:
            detail = exc.read().decode(errors="replace")[:200]
            print(f"[VLM] HTTP {exc.code} (attempt {attempt + 1}/{retries}): {detail}")
            if exc.code in (401, 403) or exc.code in _VLM_TERMINAL_CODES:
                return None                        # repeating cannot help
            if exc.code == 429:
                backoff = 10 * (attempt + 1)       # rate limit, not a blip
        except Exception as exc:                   # timeout, DNS, reset, bad JSON
            print(f"[VLM] call failed (attempt {attempt + 1}/{retries}): {exc}")
        if attempt < retries - 1:
            time.sleep(backoff)
    print(f"[VLM] giving up after {retries} attempt(s)")
    return None


def _vlm_log(results_dir: str, entry: dict) -> None:
    """Append one attempt to vlm_assertions.json. Called on EVERY vlm_assert exit
    path, including failures — a `_vlm` case with no entry here then provably never
    invoked the VLM, which is what build_manifest keys off."""
    af = os.path.join(results_dir, "vlm_assertions.json")
    try:
        existing = json.load(open(af)) if os.path.exists(af) else []
        if not isinstance(existing, list):
            existing = []
    except Exception:
        existing = []
    existing.append(entry)
    try:
        _write_json(af, existing)  # type: ignore[arg-type]
    except Exception:
        try:
            with open(af, "w") as f:
                json.dump(existing, f, indent=2, ensure_ascii=False)
        except Exception as exc:
            print(f"  [warn] vlm_assert: cannot write {af}: {exc}")


def vlm_assert(test_name, question, results_dir=None, expect="YES", *,
               depth=None, jump_kind="none", tag=None) -> bool:
    """Screenshot the current screen, ask the VLM one YES/NO question, record it.

    `test_name` is auto-suffixed with `_vlm`, which is what routes it to the VLM
    track in save_results(). `tag` (color|shape|position|size|layout|content) lets
    and_audit compute the fine-grained share mechanically — always set it.

    Ask about a SPECIFIC observable rendered property. A question that a blank
    screen or any app would pass is worthless.
    """
    if not test_name.endswith("_vlm"):
        test_name += "_vlm"
    rd = results_dir or RESULTS_DIR
    if tag and tag not in VLM_TAGS:
        print(f"  [warn] vlm_assert: unknown tag {tag!r}")
    ss_path = os.path.join(rd, "screenshots", f"{test_name}.png")

    def _fail(msg: str, resp=None, answer="") -> bool:
        _vlm_log(rd, {"test_name": test_name, "question": question,
                      "screenshot": ss_path, "vlm_response": resp,
                      "vlm_answer": answer, "expected": expect,
                      "passed": False, "tag": tag or "", "error": msg})
        return record(test_name, False, msg,
                      depth=depth, jump_kind=jump_kind, tag=tag)

    if not screencap(ss_path):
        return _fail("setup_failed: screenshot capture failed")

    prompt = ("Look at this Android app screenshot and answer the following question "
              "with ONLY 'YES' or 'NO'. Do not explain.\n\n"
              f"Question: {question}\n\nAnswer (YES or NO):")
    # An unparseable answer is the same class of flakiness as an empty body, so
    # re-ask rather than scoring harness noise against the VLM track.
    answer, resp = "", None
    for ask in range(VLM_RETRIES):
        resp = call_vlm(ss_path, prompt)
        if resp is None:
            return _fail("setup_failed: VLM API call failed")
        a = resp.strip().upper()
        # Whole-word match only: a bare `"NO" in a` also fires on CANNOT / NOT /
        # NONE / KNOW, turning "Maybe? I cannot tell." into a confident NO and
        # failing the test on harness noise instead of re-asking.
        has_yes = re.search(r"\bYES\b", a) is not None
        has_no = re.search(r"\bNO\b", a) is not None
        if a.startswith("YES"):
            answer = "YES"
        elif a.startswith("NO"):
            answer = "NO"
        elif has_yes and not has_no:
            answer = "YES"
        elif has_no and not has_yes:
            answer = "NO"
        if answer:
            break
        print(f"[VLM] unparseable answer {resp!r} (ask {ask + 1}/{VLM_RETRIES})")
    if not answer:
        return _fail(f"setup_failed: ambiguous VLM response after {VLM_RETRIES} "
                     f"asks {resp!r}", resp=resp)

    passed = answer == expect.upper()
    record(test_name, passed,
           (f"VLM: Q='{question}' A={answer} expect={expect}" if passed
            else f"behavior_wrong: VLM Q='{question}' A={answer} expect={expect}"),
           depth=depth, jump_kind=jump_kind, expect=f"VLM {expect}: {question}", tag=tag)
    _vlm_log(rd, {"test_name": test_name, "question": question,
                  "screenshot": ss_path, "vlm_response": resp,
                  "vlm_answer": answer, "expected": expect,
                  "passed": passed, "tag": tag or ""})
    return passed


# ══════════════════════════════════════════════════════════════════════════════
# (8) Audit / lint — ALL report-only. None of these ever blocks delivery.
# ══════════════════════════════════════════════════════════════════════════════

def _load_all(results_dir: str) -> list[dict]:
    recs, seen_files = [], set()
    for pat in (os.path.join(results_dir, "android_*_eval.json"),
                os.path.join(results_dir, "eval_results", "android_*_eval.json")):
        for path in glob.glob(pat):
            base = os.path.basename(path)
            if base in seen_files:
                continue
            seen_files.add(base)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            for t in data.get("results", []):
                if isinstance(t, dict) and "test" in t:
                    recs.append(t)
    return recs


def and_audit(results_dir: str = "", quotas: dict | None = None) -> dict:
    """Aggregate declared depth/jump_kind/vlm-tag across the suite and report the
    quota TARGETS with the concrete gap. GOALS, not a gate."""
    results_dir = results_dir or RESULTS_DIR
    q = quotas or QUOTAS
    recs = _load_all(results_dir)
    backfilled = [r for r in recs if r.get("backfilled")]
    recs = [r for r in recs if not r.get("backfilled")]
    n = len(recs)
    if not n:
        print(f"[and_audit] no records under {results_dir}")
        return {"total": 0}
    kinds = [r.get("jump_kind", "none") for r in recs]
    none_n = sum(1 for k in kinds if k == "none")
    live_n = sum(1 for k in kinds if k == "liveness")
    inter = [r for r in recs if r.get("jump_kind") in ("reach", "transition", "value")]
    ni = len(inter) or 1
    d1 = sum(1 for r in inter if int(r.get("depth", 0)) >= 1)
    d2 = sum(1 for r in inter if int(r.get("depth", 0)) >= 2)
    val = sum(1 for r in inter if r.get("jump_kind") == "value")
    vlm = [r for r in recs if r["test"].endswith("_vlm")]
    fine = sum(1 for r in vlm if r.get("tag") in VLM_FINE_TAGS)
    vlm_share = len(vlm) / n

    def line(label, got, need, kind):
        ok = got >= need if kind == "min" else got <= need
        return ok, (f"  [{'ok ' if ok else 'GAP'}] {label}: {got:.0%} "
                    f"({'>=' if kind == 'min' else '<='} {need:.0%})")

    lo, hi = q["vlm_share_min"], q["vlm_share_max"]
    vlm_ok = lo <= vlm_share <= hi
    if vlm_share < lo:
        # each added vlm record also grows the denominator: (v+x)/(n+x) >= lo
        need_more = math.ceil((lo * n - len(vlm)) / (1 - lo))
        vlm_hint = (f"under budget by ~{max(1, need_more)} record(s) — allocate more "
                    f"per lane NEXT run; do not re-run to chase it")
    elif vlm_share > hi:
        vlm_hint = "over budget — allocate fewer per lane next run"
    else:
        vlm_hint = "in budget"
    vlm_msg = (f"  [{'ok ' if vlm_ok else 'GAP'}] VLM BUDGET vlm/total: "
               f"{len(vlm)}/{n} = {vlm_share:.0%} (target {lo:.0%}-{hi:.0%}) "
               f"— {vlm_hint}")

    checks = [
        line("existence(none)/all", none_n / n, q["existence_max"], "max"),
        line("interactive/all", len(inter) / n, q["interactive_min"], "min"),
        line("depth>=1 /interactive", d1 / ni, q["depth_ge1_min"], "min"),
        line("depth>=2 /interactive", d2 / ni, q["depth_ge2_min"], "min"),
        line("value(tier3)/interactive", val / ni, q["value_min"], "min"),
        (vlm_ok, vlm_msg),
        line("vlm fine-grained/vlm", fine / (len(vlm) or 1), q["vlm_fine_min"], "min"),
    ]
    print(f"[and_audit] {results_dir}  total={n} interactive={len(inter)} "
          f"none={none_n} liveness={live_n} depth>=1={d1} depth>=2={d2} "
          f"value={val} vlm={len(vlm)} vlm_fine={fine}")
    if backfilled:
        print(f"  [!!!] {len(backfilled)} record(s) never reached their assertion "
              f"(back-filled as failures) — excluded from the ratios above; the "
              f"100%-pass gate on the original app must catch these")
    for _ok, msg in checks:
        print(msg)
    passed = all(ok for ok, _ in checks)
    print("[and_audit] " + ("ALL TARGETS MET" if passed else
          "some targets below — this is a REPORT, not a task: finalize now and fix "
          "the shortfall in the NEXT run's plan. Re-running the suite to move these "
          "numbers costs hours and changes nothing about the app under test"))
    return {"total": n, "interactive": len(inter), "none": none_n,
            "liveness": live_n, "depth_ge1": d1, "depth_ge2": d2, "value": val,
            "vlm": len(vlm), "vlm_fine": fine, "vlm_share": round(vlm_share, 4),
            "backfilled": len(backfilled),
            "passed": passed, "checks": [m for _o, m in checks]}


def and_lint(results_dir: str = "") -> list[str]:
    """Flag weak or inconsistent DECLARATIONS."""
    results_dir = results_dir or RESULTS_DIR
    issues, names = [], set()
    for r in _load_all(results_dir):
        jk, nm = r.get("jump_kind", "none"), r.get("test", "?")
        if nm in names:
            issues.append(f"{nm}: duplicate record name (drifts the denominator)")
        names.add(nm)
        if jk not in JUMP_KINDS:
            issues.append(f"{nm}: unknown jump_kind {jk!r}")
        if jk in ("reach", "transition", "value") and not str(r.get("expect", "")).strip():
            issues.append(f"{nm}: jump_kind={jk} but empty expect "
                          f"(name the specific observed target)")
        if jk == "liveness":
            issues.append(f"{nm}: liveness is tier1 — assert the app-authored effect instead")
        if int(r.get("depth", 0)) < 0:
            issues.append(f"{nm}: negative depth")
        msg = str(r.get("message", ""))
        if not r.get("passed") and not msg.startswith(FAIL_PREFIXES):
            issues.append(f"{nm}: failure message must start with one of "
                          f"{'/'.join(FAIL_PREFIXES)} (got {msg[:40]!r})")
        if nm.endswith("_vlm") and not r.get("tag") and not r.get("backfilled"):
            issues.append(f"{nm}: VLM record has no tag "
                          f"(color|shape|position|size|layout|content)")
    if issues:
        print(f"[and_lint] {len(issues)} issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[and_lint] no issues")
    return issues


# Non-portable source patterns: they pass on the ORIGINAL app and break on the
# RECREATION (different package, different install path). Each is a hard defect.
_BAD_SOURCE_PATTERNS = [
    (r"""["'][a-z][a-z0-9_]*(?:\.[a-z][a-z0-9_]*){2,}["']""",
     "hardcodes a package name; use the module-level PACKAGE (argv[1]) — the "
     "recreation's package differs", ("android.", "androidx.", "java.", "javax.",
                                     "com.android.adbkeyboard", "ca.zgrs.clipper",
                                     "android.intent.", "com.google.android.inputmethod")),
    (r"""["'][^"']*\.apk["']|clean\.apk""",
     "names an APK path; the test must never install or locate the app", ()),
    (r"/data/data/|/sdcard/Android/data/",
     "uses a per-package data path, which breaks when the recreation's package "
     "differs; drive state through the GUI", ()),
    (r"\btap\(\s*\d{2,}\s*,\s*\d{2,}",
     "taps a hardcoded pixel coordinate; derive it from a node's _center or "
     "get_screen_info()", ()),
    (r"\bpm\s+grant\b|\bappops\s+set\b|\bsettings\s+put\b|\bcontent\s+insert\b",
     "seeds state outside the GUI; the recreation may not honor it — drive the "
     "same state through the UI", ()),
    (r"am\s+start\s+-n\s",
     "deep-links straight to a component: not portable, and not navigation "
     "(it cannot back a depth claim)", ()),
    (r"emulator-\d{4}|127\.0\.0\.1:\d{4}",
     "hardcodes a device serial; use the module-level DEVICE", ()),
]


def and_lint_sources(testgen_dir: str = "") -> list[str]:
    """Scan authored test/helper .py for NON-PORTABLE patterns and for kit API
    drift. A clean result means the suite will actually drive the recreation, not
    just the original."""
    testgen_dir = testgen_dir or RESULTS_DIR
    kit_base = os.path.basename(__file__)
    py = [p for p in (glob.glob(os.path.join(testgen_dir, "*.py"))
                      + glob.glob(os.path.join(testgen_dir, "tests", "*.py")))
          if os.path.basename(p) != kit_base]
    kit_names = set(globals().keys())
    # A sample file the app is supposed to OPEN. Testgen and eval run on DIFFERENT
    # emulators, so naming one without pushing it means it only ever existed
    # because someone put it there by hand while exploring.
    _DEV_PATH_RE = re.compile(r"/sdcard/|/storage/emulated/|\bDCIM\b", re.I)
    _DOC_RE = re.compile(
        r"""["'][^"']*\.(?:pdf|epub|mobi|djvu|zim|mp3|mp4|mkv|wav|ogg)["']""", re.I)
    _fix_files = [f for f in glob.glob(os.path.join(testgen_dir, "fixtures", "**"),
                                      recursive=True) if os.path.isfile(f)]
    issues = []
    srcs = {}
    for p in py:
        try:
            srcs[p] = open(p, errors="replace").read()
        except Exception:
            continue
    suite_pushes = any(re.search(r"\b(push_fixtures|fixture_on_device)\b", s)
                       for s in srcs.values())
    if _fix_files and not suite_pushes:
        issues.append(
            f"fixtures/: {len(_fix_files)} fixture file(s) are authored but NO test "
            f"calls push_fixtures() — they never reach the device, so every test "
            f"that opens one records setup_failed. Call it once via run_suite(), "
            f"or drop the directory.")
    for p, src in srcs.items():
        base = os.path.basename(p)
        # Strip comments AND docstrings: prose describing the app under test names
        # files it opens, which is not the same as the code depending on one.
        scan = re.sub(r'"""[\s\S]*?"""|\'\'\'[\s\S]*?\'\'\'', '""', src)
        scan = re.sub(r"#[^\n]*", "", scan)
        # adb is called argv-style — adb_shell("am", "start", "-n", x) — so collapse
        # the quote-comma-quote separators to read those calls as command lines.
        flat = re.sub(r"""["']\s*,\s*["']""", " ", scan)
        if not suite_pushes:
            for ln in scan.splitlines():
                m = _DEV_PATH_RE.search(ln) or _DOC_RE.search(ln)
                if m:
                    issues.append(
                        f"{base}: needs a sample file on the device "
                        f"[{ln.strip()[:60]}] but the suite never calls "
                        f"push_fixtures() — testgen and eval run on DIFFERENT "
                        f"emulators, so at eval the file is absent. Author the bytes "
                        f"into {os.path.join(testgen_dir, 'fixtures')}/ and let "
                        f"run_suite() push them.")
                    break
        for pat, why, allow in _BAD_SOURCE_PATTERNS:
            hit = None
            for form in (scan, flat):
                for m in re.finditer(pat, form):
                    cand = m.group(0)
                    if allow and any(a in cand for a in allow):
                        continue
                    hit = cand
                    break
                if hit:
                    break
            if hit:
                issues.append(f"{base}: {why} [{hit[:48]}]")
        # kit API drift — an import/attr the kit does not define
        imported: list[str] = []
        for m in re.finditer(
                r"from\s+android_testgen_kit\s+import\s+\(([^)]*)\)", scan, re.S):
            imported += m.group(1).split(",")
        for m in re.finditer(
                r"from\s+android_testgen_kit\s+import\s+([^\n(]+)", scan):
            imported += m.group(1).split(",")
        for raw in imported:
            nm = raw.strip().split(" as ")[0].strip()
            if nm and nm != "*" and nm not in kit_names:
                issues.append(f"{base}: imports android_testgen_kit.{nm} which the "
                              f"kit does not define (would ImportError at eval)")
        for m in re.finditer(r"\bkit\.(\w+)\s*\(", scan):
            if m.group(1) not in kit_names:
                issues.append(f"{base}: calls kit.{m.group(1)}() which the kit does "
                              f"not define (would AttributeError at eval)")
    if issues:
        print(f"[and_lint_sources] {len(issues)} portability issue(s):")
        for i in issues:
            print("  - " + i)
    else:
        print("[and_lint_sources] no portability issues")
    return issues


# ── MEASURED depth cross-check (report-only): does the SOURCE back the DECLARE? ─
def _ast_call_name(node) -> str:
    f = node.func
    if isinstance(f, ast.Attribute):
        return f.attr
    if isinstance(f, ast.Name):
        return f.id
    return ""


def _string_locals(fn_node) -> dict[str, str]:
    """`name = "states_toggle"` inside a test — so record(name, ...) resolves."""
    out = {}
    for n in ast.walk(fn_node):
        if isinstance(n, ast.Assign) and isinstance(n.value, ast.Constant) \
                and isinstance(n.value.value, str):
            for t in n.targets:
                if isinstance(t, ast.Name):
                    out[t.id] = n.value.value
    return out


def _record_names(fn_node) -> list[str]:
    """Literal record()/vlm_assert() names in this function, preferring the
    @and_test(expects=(...)) literal when present."""
    for dec in getattr(fn_node, "decorator_list", []):
        if isinstance(dec, ast.Call) and _ast_call_name(dec) == "and_test":
            for kw in dec.keywords:
                if kw.arg == "expects" and isinstance(kw.value, (ast.Tuple, ast.List)):
                    return [e.value for e in kw.value.elts
                            if isinstance(e, ast.Constant) and isinstance(e.value, str)]
    slocals = _string_locals(fn_node)
    names = []
    for n in ast.walk(fn_node):
        if not (isinstance(n, ast.Call)
                and _ast_call_name(n) in ("record", "vlm_assert")):
            continue
        if not n.args:
            continue
        a0 = n.args[0]
        if isinstance(a0, ast.Constant) and isinstance(a0.value, str):
            names.append(a0.value)
        elif isinstance(a0, ast.Name) and a0.id in slocals:
            names.append(slocals[a0.id])
    return names


def _depth_calls(fn_node, local_funcs, budget: int = 2, seen=None):
    """(fwd, back, reach) depth-family calls, descending `budget` levels into
    file-local helpers. Cycle-guarded. A LOWER BOUND — never an over-claim."""
    seen = seen if seen is not None else set()
    fwd = bk = rch = 0
    relaunch = False
    for node in ast.walk(fn_node):
        if not isinstance(node, ast.Call):
            continue
        cn = _ast_call_name(node)
        if DEPTH_FWD_RE.match(cn):
            fwd += 1
            if cn.startswith("and_reach"):
                rch += 1
        elif DEPTH_BACK_RE.match(cn):
            bk += 1
        elif cn in ("launch_app", "restart_app", "force_stop_and_relaunch"):
            relaunch = True
        elif budget > 0 and cn in local_funcs and cn not in seen:
            seen.add(cn)
            f, b, r = _depth_calls(local_funcs[cn], local_funcs, budget - 1, seen)[:3]
            fwd, bk, rch = fwd + f, bk + b, rch + r
    return fwd, bk, rch, relaunch


def and_audit_depth(testgen_dir: str = "", results_dir: str = "") -> list[str]:
    """MEASURE navigation depth from the test SOURCE (AST) and cross-check the
    DECLARED depth/jump_kind — so a test cannot just TYPE depth=2. REPORT-ONLY.

    Flags a declared depth>=1 or jump_kind="reach" with NO backing call from the
    depth family and_enter*/and_reach* (directly, in a file-local helper it calls,
    or anywhere in the module for variable-named records), plus a "reach" that was
    achieved by relaunching the app rather than navigating.
    """
    testgen_dir = testgen_dir or RESULTS_DIR
    results_dir = results_dir or testgen_dir
    files = [p for p in (glob.glob(os.path.join(testgen_dir, "test_android_*.py"))
                         + glob.glob(os.path.join(testgen_dir, "tests",
                                                  "test_android_*.py")))]
    per_record, per_module = {}, {}
    for p in files:
        try:
            tree = ast.parse(open(p, errors="replace").read())
        except Exception:
            continue
        stem = os.path.basename(p)[len("test_android_"):-len(".py")]
        mod = _MODULE_ALIAS.get(stem, stem)
        local_funcs = {n.name: n for n in ast.walk(tree)
                       if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
        module_backing = any(
            isinstance(n, ast.Call) and DEPTH_FWD_RE.match(_ast_call_name(n))
            for n in ast.walk(tree))
        per_module[mod] = {"module_backing": module_backing}
        for fn in local_funcs.values():
            if not fn.name.startswith("test_"):
                continue
            fwd, bk, rch, relaunch = _depth_calls(fn, local_funcs)
            measured = max(0, max((fwd - rch) - bk, 1 if rch >= 1 else 0))
            for nm in _record_names(fn):
                per_record[(mod, nm)] = {"measured_depth": measured,
                                        "backing": fwd >= 1, "n_reach": rch,
                                        "relaunch": relaunch, "fn": fn.name}
    issues = []
    for r in _load_all(results_dir):
        nm, jk = r.get("test", "?"), r.get("jump_kind", "none")
        depth = int(r.get("depth", 0) or 0)
        strong = depth >= 1 or jk == "reach"
        hit = None
        for (mod, rname), v in per_record.items():
            if rname == nm:
                hit = v
                break
        if hit is not None:
            if strong and not hit["backing"]:
                issues.append(f"{nm} ({hit['fn']}): declared depth={depth}/"
                              f"jump_kind={jk} but NO backing and_enter*/and_reach* "
                              f"call (fake depth)")
            elif jk == "reach" and hit["n_reach"] == 0:
                issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but no "
                              f"and_reach* call in its code")
            elif jk == "reach" and hit["relaunch"]:
                issues.append(f"{nm} ({hit['fn']}): jump_kind=reach but the function "
                              f"relaunches the app — that is not navigation")
        elif strong and not any(v.get("module_backing", True)
                                for v in per_module.values()):
            issues.append(f"{nm}: declared depth={depth}/jump_kind={jk} but no "
                          f"and_enter*/and_reach* call anywhere (fake depth)")
    if issues:
        print(f"[and_audit_depth] {len(issues)} fake-depth issue(s) (REPORT-ONLY — "
              f"fix by adding the and_reach/and_enter you navigated with, or lower "
              f"the declared depth):")
        for i in issues:
            print("  - " + i)
    else:
        print("[and_audit_depth] no fake-depth issues "
              "(declared depth/reach backed by nav calls)")
    return issues


# ══════════════════════════════════════════════════════════════════════════════
# (9) Frozen manifest — the FIXED denominator (ported from RecreationBench v7.2)
#
# Without this, the eval denominator is whatever the candidate happened to emit:
# a recreation that crashes a module SHRINKS its own denominator instead of
# counting the missing behaviour as failures. The manifest is frozen ONCE per
# task from the ORIGINAL app's run and is the denominator authority for every
# candidate. Missing tests are injected as `not_run`; extra tests are ignored.
# ══════════════════════════════════════════════════════════════════════════════

MANIFEST_NAME = "test_manifest.json"
MANIFEST_VERSION = 1


def qualify_name(module: str, test: str) -> str:
    """`module::test` — two modules may legitimately reuse a short test name."""
    return test if "::" in test else f"{module}::{test}"


def _record_status(rec: dict) -> str:
    if rec.get("status") in ("passed", "failed", "error", "skipped", "not_run"):
        return rec["status"]
    return "passed" if rec.get("passed") else "failed"


def _load_by_module(results_dir: str) -> list[tuple[str, dict]]:
    """Like _load_all but keeps the owning module, so names can be qualified."""
    out, seen_files = [], set()
    for pat in (os.path.join(results_dir, "android_*_eval.json"),
                os.path.join(results_dir, "eval_results", "android_*_eval.json")):
        for path in sorted(glob.glob(pat)):
            base = os.path.basename(path)
            if base in seen_files:
                continue
            seen_files.add(base)
            try:
                data = json.load(open(path))
            except Exception:
                continue
            mod = data.get("module") or base[len("android_"):-len("_eval.json")]
            for t in data.get("results", []):
                if isinstance(t, dict) and "test" in t:
                    out.append((str(mod), t))
    return out


def _vlm_logged_names(results_dir: str) -> tuple[set[str], bool]:
    """(names with >=1 logged VLM attempt, whether any log file was found).

    Checks the root AND eval_results/ — the agent's self-validation run drives
    test_verify.sh with --output-dir, which puts the log one level down.
    """
    names, found = set(), False
    for sub in ("", "eval_results"):
        p = os.path.join(results_dir, sub, "vlm_assertions.json")
        if not os.path.isfile(p):
            continue
        found = True
        try:
            for x in json.load(open(p)):
                if isinstance(x, dict) and x.get("test_name"):
                    names.add(str(x["test_name"]))
        except Exception:
            pass
    return names, found


def build_manifest(results_dir: str = "", *, task_id: str = "",
                   baseline_model: str = "", out_path: str = "") -> dict:
    """Freeze the ORIGINAL app's PASSING tests as the denominator.

    A test that fails on the original is not a signal about any recreation, so it
    is moved to `ignored[reason=baseline_fail]` instead of counting against every
    candidate. This is the only denominator-shrinking mechanism, and it is applied
    identically to all candidates.
    """
    results_dir = results_dir or RESULTS_DIR
    logged, log_found = _vlm_logged_names(results_dir)
    tests, ignored, vlm_assertions = [], [], []
    n_unverified = 0
    for mod, rec in _load_by_module(results_dir):
        name = qualify_name(mod, str(rec.get("test", "")))
        status = _record_status(rec)
        entry = {"name": name, "module": mod, "baseline_status": status}
        is_vlm = name.endswith("_vlm")
        # A passing _vlm case with no logged attempt never provably reached the
        # judge on the original app — it must not sit in the VLM denominator that
        # every recreation is scored against.
        if is_vlm and status == "passed" and str(rec.get("test", "")) not in logged:
            n_unverified += 1
            ignored.append({"name": name, "module": mod,
                            "reason": "vlm_unverified",
                            "baseline_status": status,
                            "message": "no attempt in vlm_assertions.json — the VLM "
                                       "was never provably invoked for this case"})
            continue
        if status == "passed":
            tests.append(entry)
            if is_vlm:
                vlm_assertions.append({"name": name, "module": mod,
                                       "tag": rec.get("tag", "")})
        else:
            ignored.append({"name": name, "module": mod,
                            "reason": "baseline_fail",
                            "baseline_status": status,
                            "message": str(rec.get("message", ""))[:300]})
    tests.sort(key=lambda t: t["name"])
    ignored.sort(key=lambda t: t["name"])
    payload = "\n".join(t["name"] for t in tests)
    pkg = (os.environ.get("ORIG_PACKAGE") or os.environ.get("PACKAGE")
           or (PACKAGE if "." in PACKAGE else ""))
    manifest = {
        "manifest_version": MANIFEST_VERSION,
        "kit_api_version": KIT_API_VERSION,
        "task_id": task_id or os.environ.get("INSTANCE_ID", ""),
        "baseline_model": baseline_model or os.environ.get("MODEL", ""),
        "baseline_package": pkg,
        "total": len(tests),
        "manifest_sha": hashlib.sha256(payload.encode()).hexdigest()[:12],
        "tests": tests,
        "ignored": ignored,
        "vlm_assertions": vlm_assertions,
        "vlm_total": len(vlm_assertions),
        "n_vlm_unverified": n_unverified,
        "vlm_log_found": log_found,
    }
    dest = out_path or os.path.join(results_dir, MANIFEST_NAME)
    tmp = dest + ".tmp"
    with open(tmp, "w") as f:
        json.dump(manifest, f, indent=2, ensure_ascii=False)
    os.replace(tmp, dest)
    print(f"[build_manifest] {dest}  total={manifest['total']} "
          f"vlm={manifest['vlm_total']} ignored={len(ignored)} "
          f"sha={manifest['manifest_sha']}")
    if n_unverified:
        print(f"  [!!!] {n_unverified} passing _vlm case(s) EXCLUDED as "
              f"vlm_unverified — no attempt logged in vlm_assertions.json"
              + ("" if log_found else " (no log file found at all — the suite may "
                                      "have bypassed the kit's vlm_assert)")
              + ". They are out of the VLM denominator; fix the VLM path rather "
                "than accepting the smaller denominator.")
    base_fail = [i for i in ignored if i["reason"] == "baseline_fail"]
    if base_fail:
        print(f"  {len(base_fail)} baseline failure(s) excluded from the denominator "
              f"(they say nothing about a recreation):")
        for i in base_fail[:20]:
            print(f"    - {i['name']}: {i['message'][:120]}")
    return manifest


def load_manifest(d: str = "") -> dict | None:
    """Return the frozen manifest from `d` (or its eval_results/), else None."""
    d = d or RESULTS_DIR
    for p in (os.path.join(d, MANIFEST_NAME),
              os.path.join(d, "eval_results", MANIFEST_NAME)):
        if os.path.isfile(p):
            try:
                m = json.load(open(p))
            except Exception:
                continue
            if isinstance(m, dict) and m.get("tests"):
                return m
    return None


def score_against_manifest(results_dir: str = "",
                           manifest: dict | None = None) -> dict:
    """Score a candidate run against the frozen denominator.

    denominator = len(manifest["tests"]) regardless of what the candidate emitted.
    A manifest test the candidate never reported is injected as `not_run` (a
    non-pass); a test the candidate invented is excluded. A module that crashed
    on import therefore scores 0/full instead of vanishing.
    """
    results_dir = results_dir or RESULTS_DIR
    manifest = manifest or load_manifest(results_dir)
    if not manifest:
        return {}
    expected = {t["name"]: t for t in manifest["tests"]}
    got = {}
    for mod, rec in _load_by_module(results_dir):
        got[qualify_name(mod, str(rec.get("test", "")))] = rec

    per_test, by_module = {}, {}
    injected = 0
    for name, meta in expected.items():
        rec = got.get(name)
        if rec is None:
            status, msg = "not_run", "not_run: absent from the candidate's output"
            injected += 1
        else:
            status, msg = _record_status(rec), str(rec.get("message", ""))
        per_test[name] = {"status": status, "message": msg[:300]}
        m = by_module.setdefault(meta.get("module", "?"),
                                 {"total": 0, "passed": 0, "not_run": 0})
        m["total"] += 1
        m["passed"] += status == "passed"
        m["not_run"] += status == "not_run"

    unexpected = sorted(set(got) - set(expected))
    total = len(expected)
    passed = sum(1 for v in per_test.values() if v["status"] == "passed")
    vlm_names = {a["name"] for a in manifest.get("vlm_assertions", [])}
    vlm_total = len(vlm_names)
    vlm_passed = sum(1 for n in vlm_names if per_test.get(n, {}).get("status") == "passed")
    rule_total = total - vlm_total
    rule_passed = passed - vlm_passed
    for m in by_module.values():
        m["pass_rate"] = round(m["passed"] / m["total"], 4) if m["total"] else 0.0

    out = {
        "scored_against": "manifest",
        "manifest_sha": manifest.get("manifest_sha", ""),
        "manifest_total": total,
        "total": total,
        "passed": passed,
        "pass_rate": round(passed / total, 4) if total else 0.0,
        "n_injected_not_run": injected,
        "n_unexpected": len(unexpected),
        "unexpected": unexpected[:50],
        "rule": {"total": rule_total, "passed": rule_passed,
                 "pass_rate": round(rule_passed / rule_total, 4) if rule_total else 0.0},
        "vlm": {"total": vlm_total, "passed": vlm_passed,
                "pass_rate": round(vlm_passed / vlm_total, 4) if vlm_total else 0.0},
        "by_module": by_module,
        "per_test": per_test,
    }
    print(f"[score_against_manifest] sha={out['manifest_sha']} "
          f"{passed}/{total} = {out['pass_rate']:.4f} "
          f"(injected_not_run={injected} unexpected={len(unexpected)}) "
          f"rule={rule_passed}/{rule_total} vlm={vlm_passed}/{vlm_total}")
    return out


if __name__ == "__main__":
    _fns = {"audit": and_audit, "lint": and_lint, "lint_sources": and_lint_sources,
            "build_manifest": build_manifest}
    _argv = sys.argv[1:]
    if _argv[:1] == ["audit_depth"] and len(_argv) >= 2:
        and_audit_depth(_argv[1], _argv[2] if len(_argv) >= 3 else "")
    elif _argv[:1] == ["score"] and len(_argv) >= 2:
        _m = load_manifest(_argv[2]) if len(_argv) >= 3 else load_manifest(_argv[1])
        _out = score_against_manifest(_argv[1], _m)
        if not _out:
            print("no manifest found — cannot score against a fixed denominator",
                  file=sys.stderr)
            sys.exit(2)
        print(json.dumps(_out, ensure_ascii=False))
    elif len(_argv) >= 2 and _argv[0] in _fns:
        _fns[_argv[0]](_argv[1])
    else:
        print("usage: android_testgen_kit.py {audit|lint|lint_sources|build_manifest} <dir>\n"
              "       android_testgen_kit.py audit_depth <testgen_dir> [results_dir]\n"
              "       android_testgen_kit.py score <results_dir> [manifest_dir]")