cranpose 0.1.97

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

fn crate_source(path: &str) -> String {
    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    std::fs::read_to_string(crate_dir.join(path)).expect("failed to read cranpose source file")
}

/// Manifest comments explain what the framework contributes, and name the very
/// declarations an application must not make. Only the markup is asserted on.
fn strip_xml_comments(source: &str) -> String {
    let mut remaining = source;
    let mut out = String::with_capacity(source.len());
    while let Some(open) = remaining.find("<!--") {
        out.push_str(&remaining[..open]);
        remaining = match remaining[open..].find("-->") {
            Some(close) => &remaining[open + close + "-->".len()..],
            None => "",
        };
    }
    out.push_str(remaining);
    out
}

/// The one place the Cranpose native build is configured.
const CRANPOSE_GRADLE_PLUGIN: &str =
    "android/cranpose-gradle-plugin/src/main/kotlin/dev/cranpose/gradle/CranposeAndroidPlugin.kt";

/// Every Android application built from this repository.
const ANDROID_APPLICATION_BUILD_FILES: [&str; 2] = [
    "apps/android-demo/android/app/build.gradle.kts",
    "apps/isolated-demo/android/app/build.gradle.kts",
];

/// Their manifests, which state only what is specific to each application.
const ANDROID_APPLICATION_MANIFESTS: [&str; 2] = [
    "apps/android-demo/android/app/src/main/AndroidManifest.xml",
    "apps/isolated-demo/android/app/src/main/AndroidManifest.xml",
];

fn workspace_source(path: &str) -> String {
    std::fs::read_to_string(workspace_path(path)).expect("failed to read workspace source file")
}

fn workspace_path(path: &str) -> PathBuf {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    workspace_dir.join(path)
}

#[test]
fn ci_architecture_budget_runs_required_gates() {
    let workflow = workspace_source(".github/workflows/rust.yml");
    let heavy_workflow = workspace_source(".github/workflows/heavy-selfhosted.yml");
    let release_workflow = workspace_source(".github/workflows/release.yml");
    let pages_workflow = workspace_source(".github/workflows/deploy-pages.yml");

    assert!(
        workflow.contains("architecture-budget:")
            && workflow.contains("name: architecture budgets (linux)"),
        "Rust CI should keep a dedicated architecture budget job"
    );
    assert!(
        workflow.contains("cargo build --workspace --no-default-features"),
        "architecture budget job should prove the workspace builds with default features disabled"
    );
    assert!(
        workflow.contains("cargo check --workspace --all-features"),
        "architecture budget job should prove the all-features graph still type-checks"
    );
    assert!(
        workflow.contains("cargo xtask dependency-budget --explain"),
        "architecture budget job should print duplicate dependency owner details"
    );
    assert!(
        workflow.contains("cargo xtask dependency-budget --strict --explain")
            && workflow
                .contains("cargo xtask dependency-budget --strict --slice desktop-platform --explain")
            && workflow.contains(
                "cargo xtask dependency-budget --strict --slice optional-features --explain"
            ),
        "architecture budget job should enforce full strict zero duplicates and keep focused clean-slice diagnostics"
    );
    assert!(
        workflow.contains("cargo xtask binary-size")
            && workflow.contains("--package isolated-demo")
            && workflow.contains("--bin isolated-demo")
            && workflow.contains("--profile release-small")
            && workflow.contains("--max-bytes 15728640"),
        "architecture budget job should enforce the accessibility-enabled release-small binary size ceiling"
    );
    assert!(
        workflow.contains("wasm-build:")
            && workflow.contains("wasm-opt --version")
            && workflow.contains("cargo install wasm-pack --version 0.13.1 --locked")
            && workflow.contains("run: apps/desktop-demo/build-web.sh --release"),
        "Rust CI should keep the web release build job wired through explicit build-web.sh --release so the wasm-release profile and WASM size budget cannot depend on ambient CI defaults"
    );
    assert!(
        pages_workflow.contains("Deploy to GitHub Pages")
            && pages_workflow.contains("Install binaryen (wasm-opt) for size optimization")
            && pages_workflow.contains("cargo install wasm-pack --version 0.13.1")
            && pages_workflow.contains("./build-web.sh --release")
            && pages_workflow.contains("actions/upload-pages-artifact@v5"),
        "GitHub Pages deployment must publish the same budgeted optimized WASM produced by build-web.sh --release"
    );
    assert!(
        !workflow.contains("android-actions/setup-android")
            && !release_workflow.contains("android-actions/setup-android"),
        "Android CI should install only required SDK packages instead of running the broad setup-android action"
    );
    assert!(
        heavy_workflow.contains("ANDROID_NDK_HOME=$sdk_root/ndk/27.0.12077973")
            && heavy_workflow.contains("sdkmanager \"ndk;27.0.12077973\"")
            && heavy_workflow.contains("test -f \"$ANDROID_NDK_HOME/source.properties\"")
            && release_workflow.contains("bash scripts/ci/install_android_ndk.sh 27.0.12077973"),
        "self-hosted Android CI and hosted release builds should provision and validate the pinned NDK"
    );
}

#[test]
fn render_common_package_embeds_crate_owned_text_assets() {
    let software_text_source =
        workspace_source("crates/cranpose-render/common/src/software_text_raster.rs");
    let font_layout_source = workspace_source("crates/cranpose-render/common/src/font_layout.rs");
    let wgpu_lib_source = workspace_source("crates/cranpose-render/wgpu/src/lib.rs");
    let wgpu_test_support_source = workspace_source("crates/cranpose-render/wgpu/tests/support.rs");

    for (path, source) in [
        (
            "crates/cranpose-render/common/src/software_text_raster.rs",
            software_text_source.as_str(),
        ),
        (
            "crates/cranpose-render/common/src/font_layout.rs",
            font_layout_source.as_str(),
        ),
        (
            "crates/cranpose-render/wgpu/src/lib.rs",
            wgpu_lib_source.as_str(),
        ),
        (
            "crates/cranpose-render/wgpu/tests/support.rs",
            wgpu_test_support_source.as_str(),
        ),
    ] {
        assert!(
            !source.contains("apps/desktop-demo/assets"),
            "{path} must not embed demo-app assets; library crates must package their own fallback fonts"
        );
    }

    for path in [
        "crates/cranpose-render/common/assets/NotoSansMerged.ttf",
        "crates/cranpose-render/common/assets/NotoSansBold.ttf",
        "crates/cranpose-render/common/assets/TwemojiMozilla.ttf",
    ] {
        let metadata = std::fs::metadata(workspace_path(path)).unwrap_or_else(|error| {
            panic!("{path} should be packaged with render-common: {error}")
        });
        assert!(
            metadata.len() > 1024,
            "{path} should contain the fallback font bytes"
        );
    }
}

#[test]
fn app_shell_frame_schedule_targets_platform_frame_driver() {
    let source = workspace_source("crates/cranpose-app-shell/src/lib.rs");

    assert!(
        source.contains("pub trait PlatformFrameDriver")
            && source.contains("pub struct FrameScheduler"),
        "AppShell scheduling should expose a scheduler and platform driver boundary"
    );
    assert!(
        source.contains("impl FrameSchedule")
            && source.contains("pub fn apply_to<D>(self, driver: &D)")
            && source.contains("pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)")
            && source.contains("pub fn schedule_platform_frame<D>(&self, driver: &D)")
            && source.contains("self.frame_scheduler.schedule(schedule, driver)")
            && source.contains("driver.request_frame()")
            && source.contains("driver.request_wake_at(deadline)")
            && source.contains("driver.clear_wake()"),
        "FrameSchedule should be interpreted through the AppShell-owned scheduler and platform driver contract"
    );
}

#[test]
fn desktop_no_vsync_chains_dirty_presented_frames_only() {
    let source = crate_source("src/desktop.rs");

    assert!(
        source.contains(
            "fn should_chain_no_vsync_redraw(frame_interval: Option<Duration>, needs_frame: bool) -> bool"
        ) && source.contains("frame_interval.is_none() && needs_frame"),
        "desktop no-vsync frame chaining must require both an uncapped present mode and pending frame work"
    );
    assert!(
        source.contains(
            "if !robot_driven\n                        && should_chain_no_vsync_redraw(\n                            frame_interval,\n                            app.frame_schedule().needs_frame,"
        )
            && source.contains("request_redraw_once(window, &mut self.primary_redraw_pending);"),
        "primary desktop frames should chain dirty no-vsync redraws while allowing robot commands to advance between presented frames"
    );
    assert!(
        source.contains(
            "native.frame_interval(),\n            native.app.frame_schedule().needs_frame"
        ) && source.contains("native.window.request_redraw();"),
        "native desktop frames should use the same no-vsync redraw chaining rule"
    );
}

#[test]
fn surface_present_decision_is_shared_across_platform_loops() {
    // The first-present / warmup decision lives once in wgpu_surface
    // (compiled for every wgpu shell: desktop, web, iOS, Android) so the
    // render loops cannot drift apart (the web loop "white until scroll"
    // bug was a desktop/web divergence).
    let shared = crate_source("src/wgpu_surface.rs");
    assert!(
        shared.contains("pub(crate) fn surface_present_required(")
            && shared.contains("surface_dirty || update_visual_changed || app_needs_redraw"),
        "the shared desktop_input module must own the single surface present decision"
    );
}

#[test]
fn desktop_renderer_warmup_reaches_primary_and_native_surfaces() {
    let source = crate_source("src/desktop.rs");

    assert!(
        source.contains(
            "surface_present_required(\n            native.surface_dirty,\n            update_result.visual_changed,\n            native.app.needs_redraw(),"
        ),
        "native windows must still render when renderer-side warmup is the only pending frame work"
    );
    assert!(
        source.contains(
            "surface_present_required(\n                    primary_surface_dirty_before_update || robot_surface_dirty_before_update,\n                    update_result.visual_changed,\n                    app.needs_redraw(),"
        ),
        "primary windows must not skip a redraw requested only by renderer-side warmup"
    );
}

#[test]
fn web_first_frame_is_forced_through_surface_dirty() {
    // Regression guard for the "white until scroll" bug: the web render loop must
    // present the scene built during construction on the first frame even though
    // `update()` reports no visual work, by starting `surface_dirty` true and
    // only clearing it after a successful present.
    let source = crate_source("src/web.rs");

    assert!(
        source.contains("let surface_dirty = Rc::new(Cell::new(true));"),
        "web surface_dirty must start true so the first frame is always presented"
    );
    assert!(
        source.contains(
            "let present_required = surface_present_required(\n            surface_dirty_for_loop.get(),\n            update_result.visual_changed,\n            app.borrow().needs_redraw(),\n        );"
        ),
        "web render loop must gate the present through the shared surface_present_required helper"
    );
    assert!(
        source.contains("surface_dirty_for_loop.set(false);"),
        "web surface_dirty must be cleared only after a successful present"
    );
}

#[test]
fn android_first_frame_is_forced_through_surface_dirty() {
    // The android render loop shares the desktop/web first-present contract: the
    // surface starts dirty and is cleared only after a successful present.
    let source = crate_source("src/android.rs");

    assert!(
        source.contains("surface_dirty: true,"),
        "android GpuResources must start with a dirty surface so the first frame presents"
    );
    assert!(
        source.contains(
            "if surface_present_required(\n                    resources.surface_dirty,\n                    update_result.visual_changed,\n                    shell.needs_redraw(),\n                )"
        ),
        "android render loop must gate the present through the shared surface_present_required helper"
    );
    assert!(
        source.contains("resources.surface_dirty = false;"),
        "android surface_dirty must be cleared only after a successful present"
    );
}

#[test]
fn android_resume_robot_contract_retains_gpu_and_marks_shell_dirty() {
    let source = crate_source("src/android.rs");

    assert!(
        !source.contains(
            "drop_present_surface(&mut gpu_resources, &mut app_shell);\n                            } else {\n                                gpu_resources = None;"
        ),
        "the resume robot must not discard the device and renderer on TerminateWindow"
    );
    assert!(
        source.contains("resources.surface = None;"),
        "the resume robot must detach only the native surface"
    );
    assert!(
        source.contains("setup.resources.surface_dirty = true;\n            shell.mark_dirty();"),
        "the resume robot must force a composition before the first resumed present"
    );
}

#[test]
fn web_idle_does_not_request_recursive_raf() {
    let source = crate_source("src/web.rs");

    assert!(
        source.contains("struct WebPlatformFrameDriver")
            && source.contains("impl PlatformFrameDriver for WebPlatformFrameDriver"),
        "web runtime should own a concrete platform frame driver"
    );
    assert!(
        !source.contains("request_animation_frame(render_loop.borrow().as_ref().unwrap())"),
        "web runtime must not recursively request RAF every frame"
    );
    assert!(
        source.contains("app.borrow().schedule_platform_frame(&frame_driver)")
            && source.contains("request_web_frame_at_deadline")
            && source.contains("clear_web_frame_wake")
            && source.contains("set_timeout_with_callback_and_timeout_and_arguments_0"),
        "web runtime should translate idle frame deadlines into timeout-driven one-shot RAF requests"
    );
}

#[test]
fn web_frame_request_scheduling_does_not_panic_on_browser_api_failures() {
    let source = crate_source("src/web.rs");
    let start = source
        .find("fn request_animation_frame")
        .expect("web frame scheduling helper should exist");
    let end = source
        .find("fn clear_web_frame_wake")
        .expect("web frame wake clearer should exist");
    let scheduling_source = &source[start..end];

    assert!(
        !scheduling_source.contains(".unwrap()") && !scheduling_source.contains(".expect("),
        "web frame scheduling should log and clear pending state instead of panicking on browser API failures"
    );
}

#[test]
fn web_frame_waker_is_shell_owned_without_thread_local_router() {
    let web_source = crate_source("src/web.rs");
    let app_shell_source = workspace_source("crates/cranpose-app-shell/src/lib.rs");

    assert!(
        !web_source.contains("WEB_FRAME_REQUESTER")
            && !web_source.contains("install_web_frame_requester")
            && !web_source.contains("request_current_web_frame"),
        "web frame wakeups must not route through a process-global/thread-local requester"
    );
    assert!(
        app_shell_source
            .contains("#[cfg(target_arch = \"wasm32\")]\n    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static)"),
        "wasm AppShell frame wakers should be single-threaded instead of requiring Send"
    );
    assert!(
        web_source.contains("app.borrow_mut().set_frame_waker({")
            && web_source.contains("move || request_frame()"),
        "web runtime should install the per-shell frame requester directly on AppShell"
    );
}

#[test]
fn web_surface_capabilities_are_checked_before_indexing() {
    let source = crate_source("src/web.rs");

    assert!(
        !source.contains("surface_caps.formats[0]")
            && !source.contains("surface_caps.alpha_modes[0]"),
        "web renderer startup should return an error for empty surface capabilities instead of indexing directly"
    );
}

#[test]
fn native_surface_capabilities_are_checked_before_indexing() {
    for path in ["src/android.rs", "src/desktop.rs"] {
        let source = crate_source(path);

        assert!(
            !source.contains("surface_caps.formats[0]")
                && !source.contains("surface_caps.alpha_modes[0]"),
            "{path} should return typed errors for empty surface capabilities instead of indexing directly"
        );
    }
}

#[test]
fn platform_surface_reconfigure_uses_fallible_renderer_device_access() {
    for path in ["src/desktop.rs", "src/web.rs"] {
        let source = crate_source(path);
        assert!(
            !source.contains(".renderer().device()"),
            "{path} should not panic on surface reconfiguration when renderer GPU state is unavailable"
        );
        assert!(
            source.contains(".renderer().try_device()"),
            "{path} should use fallible renderer device access for surface reconfiguration"
        );
    }
}

#[test]
fn desktop_initial_shell_render_enters_native_window_registry() {
    let source = crate_source("src/desktop.rs");

    assert!(
        source.contains("let mut app = native_window::with_native_window_registry(&registry, || {")
            && source.contains("AppShell::new_with_size_and_density("),
        "desktop run_windows uses a hidden primary declaration host, so AppShell construction must enter the native-window registry before the first stable render"
    );
}

#[test]
fn android_idle_does_not_poll_16ms() {
    let source = crate_source("src/android.rs");

    assert!(
        source.contains("app_waker.wake()"),
        "android runtime frame waker should wake the Android looper"
    );
    let offscreen_period = "const OFFSCREEN_UPDATE_PERIOD: Duration = Duration::from_millis(16);";
    assert!(
        source.contains(offscreen_period),
        "the off-screen work pace is the one 16 ms period this file may hold"
    );
    assert_eq!(
        source.matches("from_millis(16)").count(),
        1,
        "android runtime must not poll at 16 ms while idle; the only 16 ms period is OFFSCREEN_UPDATE_PERIOD, which paces work for an app that asked to keep running off screen"
    );
    assert!(
        source.contains("let offscreen = no_surface && cranpose_services::background_active();"),
        "the off-screen pass must run only when an app asked to keep working with no surface"
    );
    assert!(
        source.contains("struct AndroidFrameDriver")
            && source.contains("impl PlatformFrameDriver for AndroidFrameDriver")
            && source.contains("shell.schedule_platform_frame(&android_frame_driver)")
            && source.contains("android_frame_driver.deadline_timeout()")
            && source.contains("earliest_android_poll_timeout"),
        "android runtime should route AppShell schedules through the platform frame driver"
    );
}

#[test]
fn android_overlay_events_are_runtime_owned() {
    let overlay_source = crate_source("src/android_overlay_window.rs");
    let jni_source = crate_source("src/android_jni.rs");
    let java_source = workspace_source(
        "crates/cranpose/android/java/dev/cranpose/android/CranposeOverlayWindow.java",
    );
    let runtime_source = crate_source("src/android.rs");

    assert!(
        overlay_source.contains("pub(crate) struct AndroidOverlayEventQueue")
            && overlay_source.contains("pub(crate) struct AndroidOverlayEventQueueHandle")
            && overlay_source.contains("retain_android_overlay_event_queue_handle"),
        "Android overlay callbacks should route through an explicit handle to a runtime-owned event queue"
    );
    assert!(
        !overlay_source.contains("OnceLock<Mutex<VecDeque<AndroidOverlayWindowEvent>>>")
            && !overlay_source.contains("fn overlay_events() -> &'static Mutex<VecDeque")
            && !overlay_source.contains("OnceLock<")
            && !overlay_source.contains("register_android_overlay_event_queue")
            && !overlay_source.contains("lock_overlay_event_queue_slot"),
        "Android overlay events and helper classes must not be retained in process-global Rust storage"
    );
    assert!(
        jni_source.contains("nativeOverlayReleaseQueue")
            && jni_source.contains("push_overlay_event_for_handle"),
        "Android JNI callbacks should release and dispatch explicit overlay queue handles"
    );
    assert!(
        java_source.contains("long eventQueueHandle")
            && java_source.contains("nativeOverlayReleaseQueue")
            && java_source.contains("nativeOverlaySurfaceChanged(eventQueueHandle"),
        "Android overlay Java helper should carry the runtime queue handle through callbacks"
    );
    assert!(
        runtime_source.contains("let overlay_event_queue = Arc::new")
            && !runtime_source.contains("let _overlay_event_queue_registration =")
            && runtime_source.contains("drain_android_overlay_window_events(&overlay_event_queue)"),
        "Android runtime should own and explicitly drain overlay events"
    );
    assert!(
        jni_source.contains("jni_str!(\"getClassLoader\")")
            && !jni_source.contains("jni_str!(\"getClass\")")
            && overlay_source.contains("load_cranpose_java_class")
            && !overlay_source.contains("jni_str!(\"getClass\")"),
        "Android Java bridge loading must use the Activity context classloader (via the shared \
         android_jni helper); android.app.NativeActivity itself is framework-loaded by the boot \
         classloader"
    );
}

#[test]
fn android_activity_jni_attaches_the_caller_without_recreating_the_vm() {
    let jni_source = crate_source("src/android_jni.rs");

    assert!(
        jni_source.contains("JavaVM::singleton()")
            && jni_source.contains("vm.attach_current_thread")
            && jni_source.contains("env.as_cast_raw::<JObject>")
            && jni_source.contains("env.new_local_ref"),
        "Android activity JNI access must reach the activity through the process JavaVM singleton and attach the calling thread (cheap when android_main is already attached, required when called from a worker thread such as audio playback opening a content:// document), creating a scoped local Activity reference from the global Activity handle"
    );
    assert!(
        !jni_source.contains("JavaVM::from_raw(app.vm_as_ptr"),
        "Android activity JNI access must not recreate the JavaVM from AndroidApp; it must reuse the JavaVM singleton"
    );
}

#[test]
fn android_launch_arguments_reach_the_service_registry() {
    let services_source = crate_source("src/android_services.rs");
    let decoder_source = crate_source("src/android_launch_args.rs");
    let environment_source = crate_source("src/platform_env.rs");
    let java_source =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeActivity.java");

    assert!(
        java_source.contains("public String cranposeEncodeLaunchArguments()")
            && java_source.contains("ApplicationInfo.FLAG_DEBUGGABLE")
            && java_source.contains("private static native void nativeOnLaunchArguments(String payload);")
            && java_source.contains("nativeOnLaunchArguments(cranposeEncodeLaunchArguments());"),
        "CranposeActivity should encode the launching intent's extras with the debuggable flag and re-push them from onNewIntent; a NativeActivity has no other way to see them"
    );
    assert!(
        java_source.contains("private void loadCranposeNativeLibrary()")
            && java_source.contains("System.loadLibrary(libraryName)"),
        "the Java-declared launch-argument callback only resolves because CranposeActivity loads the library itself; libnativeloader does not register it with ART's JNI resolver"
    );
    assert!(
        services_source.contains("jni_str!(\"cranposeEncodeLaunchArguments\")")
            && services_source
                .contains("set_platform_launch_args(Rc::new(read_launch_arguments(&app)))"),
        "the Android backend should pull the launching intent's extras at startup, where getIntent() is already populated, instead of racing a push from onCreate"
    );
    assert!(
        services_source
            .contains("Java_dev_cranpose_android_CranposeActivity_nativeOnLaunchArguments")
            && services_source.contains("PENDING_LAUNCH_ARGS")
            && services_source.contains("shell.request_root_render()"),
        "onNewIntent extras should be parked for the native loop, which owns the snapshot, and force a root render once applied"
    );
    assert!(
        decoder_source.contains("pub(crate) fn decode_launch_arguments"),
        "the intent-extra wire format should be decoded in safe Rust, outside the JNI boundary"
    );
    assert!(
        environment_source.contains("local_launch_args().provides(launch_args)"),
        "the platform environment should publish the launch arguments so composition observes a replacement intent"
    );
}

#[test]
fn android_play_billing_reaches_the_purchase_registry() {
    let services_source = crate_source("src/android_services.rs");
    let backend_source = crate_source("src/android_purchases.rs");
    let wire_source = crate_source("src/android_purchase_wire.rs");
    let java_source = workspace_source(
        "crates/cranpose/android/java-billing/dev/cranpose/android/CranposeBilling.java",
    );

    assert!(
        services_source.contains("crate::android_purchases::register(app.clone())"),
        "the Android backend should install the Play Billing purchase backend alongside the other platform services"
    );
    assert!(
        backend_source.contains("set_platform_purchases(Arc::new(AndroidPurchases {")
            && backend_source.contains("load_cranpose_java_class(env, &activity, BILLING_CLASS)"),
        "the Play Billing backend should reach its Java bridge through the activity class loader and register itself into cranpose_services::purchases"
    );
    assert!(
        backend_source.contains("jni_str!(\"cranposeBillingConfigure\")")
            && backend_source.contains("jni_str!(\"cranposeBillingPurchase\")")
            && backend_source.contains("jni_str!(\"cranposeBillingRestore\")"),
        "querying products, buying and restoring should each be one non-blocking JNI call into the Java bridge"
    );
    assert!(
        backend_source
            .contains("Java_dev_cranpose_android_CranposeBilling_nativeBillingSnapshot")
            && backend_source.contains("Java_dev_cranpose_android_CranposeBilling_nativeBillingEvent")
            && backend_source.contains("wake_native_loop()"),
        "store answers arrive on Play Billing worker threads and must be parked for the native loop, which is woken so the frame that reads them happens"
    );
    assert!(
        wire_source.contains("pub(crate) fn decode_store_snapshot")
            && wire_source.contains("pub(crate) fn decode_purchase_event"),
        "the Play Billing wire format should be decoded in safe Rust, outside the JNI boundary"
    );
    assert!(
        java_source.contains("private static native void nativeBillingSnapshot(String payload);")
            && java_source.contains("activity.runOnUiThread")
            && java_source.contains("client.launchBillingFlow(activity, flow)"),
        "the Java bridge should flatten the whole store snapshot into one JNI call and launch the payment sheet on the Java UI thread"
    );
    assert!(
        java_source.contains("acknowledgePurchase"),
        "Play refunds an unacknowledged purchase, so the bridge must acknowledge every entitlement it sees"
    );
}

/// The accessibility payload is a positional record split on tabs on the Java
/// side, so the two ends have to agree on how many fields there are. Rust
/// builds the record and Java rejects any record of the wrong width, which
/// means a field added on one side alone does not fail loudly — it makes the
/// app silently unreachable to a screen reader. Hence this check.
#[test]
fn android_accessibility_record_width_agrees_across_the_jni_boundary() {
    let wire_source = crate_source("src/android_accessibility_wire.rs");
    let java_source =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeActivity.java");

    let rust_fields = wire_source
        .lines()
        .find(|line| line.trim_start().starts_with("\"{}\\t"))
        .map(|line| line.matches("{}").count())
        .expect("the accessibility record format string should be one line");
    let java_fields = java_source
        .lines()
        .find(|line| line.contains("ACCESSIBILITY_FIELDS ="))
        .and_then(|line| {
            line.rsplit('=')
                .next()
                .map(|value| value.trim().trim_end_matches(';').to_string())
        })
        .and_then(|value| value.parse::<usize>().ok())
        .expect("CranposeActivity should declare the accessibility record width");

    assert_eq!(
        rust_fields, java_fields,
        "the encoder writes {rust_fields} fields but CranposeActivity parses {java_fields}"
    );
    assert!(
        java_source.contains("if (fields.length != ACCESSIBILITY_FIELDS) continue;"),
        "a record of the wrong width should be skipped, not indexed past its end"
    );
}

/// A custom action is the only screen-reader command with no position to
/// synthesise a tap at, so it is the one that needs a dispatch path of its
/// own — declared in Java, exported from the JNI boundary, and resolved back
/// to a handler on the frame loop.
#[test]
fn android_accessibility_custom_actions_reach_the_frame_loop() {
    let java_source =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeActivity.java");
    let boundary_source = crate_source("src/android_accessibility.rs");
    let loop_source = crate_source("src/android.rs");
    let projection_source = crate_source("src/accessibility.rs");

    assert!(
        java_source.contains(
            "private static native void nativeOnAccessibilityCustomAction(int virtualViewId, int actionIndex);"
        ) && java_source.contains("nativeOnAccessibilityCustomAction(element.id, customIndex);"),
        "the provider should route a custom action back by identity rather than by synthesising a tap it has no position for"
    );
    assert!(
        boundary_source.contains(
            "Java_dev_cranpose_android_CranposeActivity_nativeOnAccessibilityCustomAction"
        ) && boundary_source.contains("pub(crate) fn drain_custom_actions()"),
        "the JNI boundary should park custom actions for the frame loop instead of running app code on the Java thread"
    );
    assert!(
        loop_source.contains("crate::android_accessibility::drain_custom_actions()")
            && loop_source.contains("crate::accessibility::resolve_element_id(")
            && loop_source.contains("crate::accessibility::perform_custom_action("),
        "the frame loop should resolve the virtual view id and run the action against the live semantics tree"
    );
    assert!(
        projection_source.contains("pub(crate) fn perform_custom_action(")
            && projection_source.contains("pub(crate) fn element_ids("),
        "resolving an accessibility id and running its action are platform-neutral and belong outside the JNI boundary"
    );
}

/// The writer's half of the owned row's order id.
///
/// Nothing in CI compiles or runs `CranposeBilling.java` -- no app in this
/// workspace enables the `playbilling` feature -- so the decoder's tests are
/// the only executable coverage the wire has, and they would keep passing with
/// the Java side of the field deleted: `order_id()` would simply return `None`
/// on every Android device, forever, which is also what a legitimately absent
/// order id looks like.
#[test]
fn the_play_billing_bridge_sends_the_order_id_that_granted_each_entitlement() {
    let java_source = workspace_source(
        "crates/cranpose/android/java-billing/dev/cranpose/android/CranposeBilling.java",
    );

    assert!(
        java_source.contains("purchase.getOrderId()"),
        "the bridge must read Play's order id; the product id is what the app already knew"
    );
    assert!(
        java_source.contains("escape(orderId)"),
        "the order id must be escaped onto the owned row like every other field: the row is \
         tab separated and nothing in Play's format forbids a tab"
    );

    // The two maps are one fact split in half. Refilling `owned` without
    // refilling `orders` in the same breath leaves an order id outliving the
    // purchase that produced it -- a paper trail pointing at the wrong sale.
    let apply = java_source
        .split("private int apply(")
        .nth(1)
        .expect("the snapshot bridge should apply purchase lists in one place");
    let apply = apply
        .split("\n    private")
        .next()
        .expect("a method body is delimited by the next member");
    assert!(
        apply.contains("owned.clear()") && apply.contains("orders.clear()"),
        "ownership and its order ids must be replaced together, or an order id survives the \
         purchase it belongs to"
    );
}

#[test]
fn android_native_input_is_drained_on_input_available_event() {
    let source = crate_source("src/android.rs");

    assert!(
        source.contains("MainEvent::InputAvailable")
            && source.contains("drain_android_input_events(")
            && source.contains("push_pending_inputs_from_android_event(")
            && source.contains("android_activity::InputStatus::Handled"),
        "Android NativeActivity input must be drained from MainEvent::InputAvailable so every input event reaches finish_event before the platform ANR timeout"
    );
    assert!(
        !source.contains("println!(\n                                                    \"[TOUCH]")
            && !source.contains("println!(\"[TOUCH]"),
        "Android input acknowledgement must not perform synchronous stdout logging in the event-finish path"
    );
}

#[test]
fn android_host_window_layout_is_dispatched_on_java_ui_thread() {
    let runtime_source = crate_source("src/android.rs");
    let java_source = workspace_source(
        "crates/cranpose/android/java/dev/cranpose/android/CranposeOverlayWindow.java",
    );

    assert!(
        runtime_source.contains("setActivityWindowLayout")
            && runtime_source.contains("find_android_overlay_class")
            && !runtime_source.contains("jni_str!(\"setLayout\")"),
        "Android host-window layout requests must go through the Java bridge instead of touching Window.setLayout from android_main"
    );
    assert!(
        java_source.contains("setActivityWindowLayout")
            && java_source.contains("activity.runOnUiThread")
            && java_source.contains("activity.getWindow().setLayout"),
        "Android Activity window layout changes must execute on the Java UI thread"
    );
}

#[test]
fn platform_drivers_set_density_through_app_shell() {
    for path in ["src/android.rs", "src/desktop.rs", "src/web.rs"] {
        let source = crate_source(path);
        assert!(
            !source.contains("cranpose_ui::set_density("),
            "{path} must update density through AppShell so the per-shell AppContext owns the value"
        );
    }
}

#[test]
fn web_primary_pointer_stream_is_captured_until_release_or_cancel() {
    let source = crate_source("src/web.rs");

    assert!(
        source.contains("set_pointer_capture(event.pointer_id())"),
        "web pointer-down must capture the pointer so selection handles keep ownership outside the canvas"
    );
    assert!(
        source
            .matches("release_pointer_capture(event.pointer_id())")
            .count()
            >= 2,
        "web pointer-up and pointer-cancel must both release canvas pointer capture"
    );
}

#[test]
fn android_cancel_terminates_the_primary_pointer_stream() {
    let source = crate_source("src/android.rs");

    assert!(
        source.contains("MotionAction::Cancel")
            && source.contains("PendingInput::PointerCancel")
            && source.contains("shell.cancel_gesture()"),
        "Android ACTION_CANCEL must reach AppShell::cancel_gesture instead of leaving a selection handle captured"
    );
}

#[test]
fn desktop_frame_cap_deadline_is_option_checked() {
    let source = crate_source("src/desktop.rs");

    assert!(
        !source.contains("native frame cap deadline should exist"),
        "desktop frame pacing should carry frame-cap deadlines through Option instead of panicking"
    );
}

#[test]
fn desktop_x11_client_is_app_owned() {
    let source = crate_source("src/desktop.rs");

    assert!(
        source.contains("native_window_platform_probe: NativeWindowPlatformProbe")
            && source.contains("struct NativeWindowPlatformProbe"),
        "desktop runtime should own native-window platform probing inside App"
    );
    assert!(
        !source.contains("static X11_WINDOW_CLIENT")
            && !source.contains("fn with_x11_window_client<R>"),
        "X11 connection probing must not live in a process/thread-local cache"
    );
}

#[test]
fn ios_backend_is_wired_without_aliasing_desktop() {
    // The cranpose iOS feature is wired to a real winit-based backend: it is no
    // longer reserved, and it does not alias the desktop feature.
    let cranpose_manifest = crate_source("Cargo.toml");
    assert!(
        !cranpose_manifest.contains("ios = []"),
        "cranpose ios feature must be wired to the real backend, not reserved"
    );
    assert!(
        !cranpose_manifest.contains("ios = [\"desktop\"]"),
        "ios must not alias the desktop feature"
    );

    // The facade exposes the backend module instead of an unavailable stub.
    let facade = crate_source("src/lib.rs");
    assert!(
        facade.contains("pub mod ios;"),
        "cranpose must expose the iOS backend module"
    );
    assert!(
        !facade.contains("backend and is unavailable"),
        "the iOS-unavailable compile_error must be gone"
    );

    // The backend drives its own winit UIKit event loop (a real surface, not a
    // reuse of the desktop multi-window runtime).
    let ios = crate_source("src/ios.rs");
    assert!(
        ios.contains("ApplicationHandler") && ios.contains("winit"),
        "ios backend should drive its own winit event loop"
    );

    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");

    // The demo advertises an iOS app feature and ships the iOS entry binary.
    let demo_manifest = std::fs::read_to_string(workspace_dir.join("apps/desktop-demo/Cargo.toml"))
        .expect("failed to read desktop-demo manifest");
    assert!(
        demo_manifest
            .lines()
            .any(|line| line.trim_start().starts_with("ios =")),
        "desktop-demo should advertise an iOS app feature"
    );
    assert!(
        demo_manifest.contains("name = \"cranpose-ios\""),
        "desktop-demo should declare the cranpose-ios binary"
    );

    // The iOS build script builds the ios feature instead of failing.
    let build_script =
        std::fs::read_to_string(workspace_dir.join("apps/ios-demo/ios/build-app.sh"))
            .expect("failed to read ios build script");
    assert!(
        build_script.contains("--features ios"),
        "ios build script should build the ios feature"
    );
}

#[test]
fn wgpu_backend_features_are_target_specific() {
    for manifest in [
        "crates/cranpose/Cargo.toml",
        "crates/cranpose-render/wgpu/Cargo.toml",
    ] {
        let source = workspace_source(manifest);
        assert!(
            !source.contains(
                "[target.'cfg(all(not(target_arch = \"wasm32\"), not(target_os = \"android\")))'.dependencies]"
            ),
            "{manifest} must not use one broad native WGPU backend dependency for every desktop OS"
        );

        let linux = manifest_section(
            &source,
            "[target.'cfg(all(target_os = \"linux\", not(target_arch = \"wasm32\")))'.dependencies]",
        );
        assert!(
            linux.contains("\"vulkan\"")
                && !linux.contains("\"gles\"")
                && !linux.contains("\"dx12\"")
                && !linux.contains("\"metal\""),
            "{manifest} Linux WGPU backend set should hardcode Vulkan only; GLES is opt-in via backend-gles"
        );

        let android = manifest_section(
            &source,
            "[target.'cfg(target_os = \"android\")'.dependencies]",
        );
        assert!(
            android.contains("\"vulkan\"")
                && !android.contains("\"gles\"")
                && !android.contains("\"dx12\"")
                && !android.contains("\"metal\""),
            "{manifest} Android WGPU backend set should hardcode Vulkan only; GLES comes from the android feature enabling backend-gles"
        );

        let windows = manifest_section(
            &source,
            "[target.'cfg(target_os = \"windows\")'.dependencies]",
        );
        assert!(
            windows.contains("\"dx12\"")
                && !windows.contains("\"metal\"")
                && !windows.contains("\"gles\"")
                && !windows.contains("\"vulkan\""),
            "{manifest} Windows WGPU backend set should be DX12 only"
        );

        let macos = manifest_section(
            &source,
            "[target.'cfg(target_os = \"macos\")'.dependencies]",
        );
        assert!(
            macos.contains("\"metal\"")
                && !macos.contains("\"dx12\"")
                && !macos.contains("\"gles\"")
                && !macos.contains("\"vulkan\""),
            "{manifest} macOS WGPU backend set should be Metal only"
        );
    }

    let render_wgpu = workspace_source("crates/cranpose-render/wgpu/Cargo.toml");
    assert!(
        render_wgpu.contains("backend-gles = [\"wgpu/gles\", \"naga/glsl-out\"]"),
        "cranpose-render-wgpu must expose the GLES fallback as backend-gles (wgpu/gles + naga/glsl-out)"
    );

    let facade = workspace_source("crates/cranpose/Cargo.toml");
    assert!(
        facade.contains("renderer-wgpu-gles = ["),
        "cranpose must expose renderer-wgpu-gles for the desktop GLES fallback"
    );
    let android_feature_start = facade
        .find("android = [")
        .expect("cranpose android feature is missing");
    let android_feature = &facade[android_feature_start..];
    let android_feature = &android_feature[..android_feature
        .find(']')
        .expect("cranpose android feature array is unterminated")];
    assert!(
        android_feature.contains("cranpose-render-wgpu?/backend-gles"),
        "the cranpose android feature must keep the GLES fallback enabled on Android"
    );
}

#[test]
fn render_state_has_no_process_global_fallback() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-ui/src/render_state.rs"))
            .expect("failed to read render_state.rs");

    assert!(
        !source.contains("OnceLock<RenderState>"),
        "render_state fallback must not be a process-global RenderState"
    );
    assert!(
        source.contains("fn require_current_app_context(operation: &str) -> Rc<AppContext>")
            && source.contains("panic!(\"{operation} requires an active AppContext\")")
            && !source.contains("static UNIT_TEST_APP_CONTEXT")
            && !source.contains("Box::leak(Box::new(AppContext::new()))")
            && !source.contains("cfg(any(test, feature = \"test-helpers\"))]\nfn require_current_app_context_without_scope")
            && !source.contains("cfg(not(any(test, feature = \"test-helpers\")))]\nfn require_current_app_context_without_scope")
            && !source.contains("with_fallback_render_state")
            && !source.contains("FALLBACK_"),
        "render_state must route production runtime access through the active AppContext without hidden fallback state"
    );
}

fn manifest_section<'a>(source: &'a str, header: &str) -> &'a str {
    let start = source
        .find(header)
        .unwrap_or_else(|| panic!("manifest section `{header}` is missing"));
    let tail = &source[start + header.len()..];
    let end = tail.find("\n[").unwrap_or(tail.len());
    &tail[..end]
}

#[test]
fn fps_monitor_runtime_state_is_shell_owned() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-app-shell/src/fps_monitor.rs"))
            .expect("failed to read fps_monitor.rs");

    assert!(
        source.contains("pub(crate) struct FpsMonitor"),
        "fps monitoring state should be owned by an AppShell field"
    );
    assert!(
        !source.contains("static FPS_TRACKER") && !source.contains("static RECOMPOSITION_COUNT"),
        "fps monitor counters must not be authoritative process state"
    );
    assert!(
        !source.contains("PUBLISHED_STATS")
            && !source.contains("pub fn fps_stats()")
            && !source.contains("pub fn current_fps()"),
        "public FPS snapshots must come from the owning AppShell, not from process-global publication"
    );
}

#[test]
fn fps_monitor_counts_presented_frames_not_shell_updates() {
    let shell_frame = workspace_source("crates/cranpose-app-shell/src/shell_frame.rs");
    let app_shell = workspace_source("crates/cranpose-app-shell/src/lib.rs");
    let desktop = workspace_source("crates/cranpose/src/desktop.rs");

    assert!(
        !shell_frame.contains("record_frame_work"),
        "AppShell update processing must not mutate presented-frame FPS stats"
    );
    assert!(
        app_shell.contains("pub fn record_presented_frame"),
        "AppShell should expose an explicit presented-frame sampling boundary"
    );
    assert!(
        desktop.contains("record_presented_frame"),
        "desktop presentation paths should record FPS after real redraws"
    );
}

#[test]
fn render_hit_diagnostics_are_scene_owned() {
    let source = workspace_source("crates/cranpose-render/common/src/graph_scene.rs");

    assert!(
        source.contains("pub struct RenderDiagnostics")
            && source.contains("live_modifier_slice_lookup_miss_count"),
        "render hit diagnostics should be represented as retained scene diagnostics"
    );
    assert!(
        !source.contains("LIVE_MODIFIER_SLICE_LOOKUP_MISS_COUNT")
            && !source.contains("AtomicUsize"),
        "render hit diagnostics must not use process-global counters"
    );
}

#[test]
fn pointer_input_task_registry_is_app_context_owned() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let pointer_input_source = std::fs::read_to_string(
        workspace_dir.join("crates/cranpose-ui/src/modifier/pointer_input.rs"),
    )
    .expect("failed to read pointer_input.rs");
    let render_state_source =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-ui/src/render_state.rs"))
            .expect("failed to read render_state.rs");

    assert!(
        !pointer_input_source.contains("static POINTER_INPUT_TASKS"),
        "pointer input task wakeups must not use a module-local task table"
    );
    assert!(
        render_state_source.contains("pointer_input_tasks:")
            && render_state_source.contains("register_pointer_input_task")
            && render_state_source.contains("request_pointer_input_task_poll")
            && render_state_source.contains("context.enter(||")
            && render_state_source
                .contains("context.pointer_input_tasks.request_poll(task_id, owner)"),
        "pointer input task wakeups should run inside the owning AppContext"
    );
}

#[test]
fn fling_velocity_diagnostics_are_app_context_owned() {
    let scroll_source = workspace_source("crates/cranpose-ui/src/modifier/scroll.rs");
    let render_state_source = workspace_source("crates/cranpose-ui/src/render_state.rs");
    let desktop_source = crate_source("src/desktop.rs");

    assert!(
        !scroll_source.contains("LAST_FLING_VELOCITY")
            && !scroll_source.contains("This global state means parallel tests could interfere"),
        "fling velocity diagnostics must not use process-global test state"
    );
    assert!(
        render_state_source.contains("last_fling_velocity_bits")
            && render_state_source.contains("record_last_fling_velocity")
            && render_state_source.contains("debug_last_fling_velocity")
            && render_state_source.contains("debug_reset_last_fling_velocity"),
        "fling velocity diagnostics should be stored on the owning AppContext"
    );
    assert!(
        desktop_source.contains("GetLastFlingVelocity")
            && desktop_source.contains("ResetLastFlingVelocity")
            && desktop_source
                .contains("app.debug_enter_app_context(cranpose_ui::debug_last_fling_velocity)")
            && desktop_source.contains(
                "app.debug_enter_app_context(cranpose_ui::debug_reset_last_fling_velocity)"
            ),
        "desktop robots should query fling diagnostics through the app-thread robot channel"
    );
}

#[test]
fn text_measurer_installation_requires_app_context() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let render_state_source =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-ui/src/render_state.rs"))
            .expect("failed to read render_state.rs");
    let text_measure_source =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-ui/src/text/measure.rs"))
            .expect("failed to read text measure source");

    assert!(
        render_state_source.contains("text: crate::text::measure::TextService::new()"),
        "AppContext should create its own text service instead of cloning fallback text setup"
    );
    assert!(
        render_state_source.contains("panic!(\"set_text_measurer requires an active AppContext\")"),
        "public text measurer installation should require an active AppContext"
    );
    assert!(
        !text_measure_source.contains("fallback_text_measurer_snapshot")
            && !text_measure_source.contains("set_fallback_text_measurer"),
        "fallback text service must not be a mutable setup path for future AppContexts"
    );
}

#[test]
fn render_text_hyphenation_dictionaries_are_measurer_owned() {
    let source = workspace_source("crates/cranpose-render/common/src/text_hyphenation.rs");

    assert!(
        source.contains("pub struct HyphenationDictionaryStore"),
        "hyphenation dictionaries should live in an explicit store owned by the text measurer"
    );
    assert!(
        !source.contains("static DICTIONARIES")
            && !source.contains("OnceLock<RwLock<HashMap<Language, Standard>>>")
            && !source.contains("fn dictionaries() -> &'static"),
        "hyphenation dictionaries must not be retained in process-global mutable state"
    );
}

#[test]
fn wasm_framework_sources_use_browser_safe_time() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source_roots = [
        "crates/cranpose-core/src",
        "crates/cranpose-runtime-std/src",
        "crates/cranpose-app-shell/src",
        "crates/cranpose-ui/src",
        "crates/cranpose-foundation/src",
        "crates/cranpose-render/common/src",
        "crates/cranpose-render/wgpu/src",
        "crates/cranpose-platform/web/src",
    ];
    let source_files = ["crates/cranpose/src/web.rs"];
    let mut offenders = Vec::new();

    for root in source_roots {
        for path in rust_sources(&workspace_dir.join(root)) {
            collect_forbidden_time_source_offenders(workspace_dir, &path, &mut offenders);
        }
    }
    for file in source_files {
        collect_forbidden_time_source_offenders(
            workspace_dir,
            &workspace_dir.join(file),
            &mut offenders,
        );
    }

    assert!(
        offenders.is_empty(),
        "wasm-delivered framework code must use web_time for clocks; found unsupported std time in:\n{}",
        offenders.join("\n")
    );
}

#[test]
fn wasm_time_source_detection_catches_std_time_import_shapes() {
    let cases = [
        ("direct", "use std::time::Instant;\n"),
        ("alias", "use std::time::Instant as StdInstant;\n"),
        (
            "grouped_multiline",
            "use std::time::{\n    Duration,\n    Instant,\n};\n",
        ),
        (
            "nested_group",
            "use std::{collections::HashMap, time::{Duration, SystemTime}};\n",
        ),
        (
            "qualified_now",
            "fn tick() { let _now = std::time::Instant::now(); }\n",
        ),
        (
            "qualified_type",
            "fn tick(now: std::time::SystemTime) { let _ = now; }\n",
        ),
    ];

    for (name, source) in cases {
        let mut offenders = Vec::new();
        collect_forbidden_time_source_offenders_from_source(
            Path::new(name),
            source,
            &mut offenders,
        );
        assert_eq!(
            offenders.len(),
            1,
            "{name} should report exactly one std::time offender, got {offenders:?}"
        );
    }
}

#[test]
fn wasm_time_source_detection_allows_duration_and_web_time() {
    let mut offenders = Vec::new();

    collect_forbidden_time_source_offenders_from_source(
        Path::new("allowed"),
        "\
use std::time::Duration;
use web_time::Instant;

fn tick() {
    let _delay = Duration::from_millis(16);
    let _now = Instant::now();
}
",
        &mut offenders,
    );

    assert!(
        offenders.is_empty(),
        "Duration and web_time::Instant should remain valid in wasm framework code: {offenders:?}"
    );
}

#[test]
fn unsafe_code_stays_in_reviewed_platform_boundary_modules() {
    let crate_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let source_dir = crate_dir.join("src");
    let allowed = [
        // The display-shape read behind the renderer's visible-region cull:
        // one `dlsym`-resolved `AConfiguration_getScreenRound` call (the
        // symbol is API 30+, so it must not be linked) and the call through
        // it.
        "android_display.rs",
        // The entry-point macro: the `#[no_mangle]` in the expansion it writes
        // is the symbol `NativeActivity` resolves after loading the library.
        "android_entry.rs",
        // The display refresh-rate vote: `dlsym`/`dlopen` resolution of the
        // `ANativeWindow_setFrameRate*` NDK symbols and the calls through
        // them, mirroring how HWUI votes the panel's frame rate.
        "android_frame_rate.rs",
        // The ADPF hint session: dlsym-resolved APerformanceHint_* calls and
        // the sessions they manage; absent symbols degrade to a no-op.
        "android_perf_hint.rs",
        "android_frame_telemetry.rs",
        "android_jni.rs",
        "android_accessibility.rs",
        // Camera and host JNI calls stay behind the same reviewed activity
        // boundary as the other Android services.
        "android_camera.rs",
        "android_host.rs",
        // The media JNI surface: the exported symbols `CranposeMedia` pushes
        // playback state, position, focus and lock-screen buttons through.
        "android_media.rs",
        "android_services.rs",
        "android_surface.rs",
        "android_file_picker.rs",
        // The Play Billing bridge: the exported symbols
        // `dev.cranpose.android.CranposeBilling` calls back through. Decoding
        // what they carry lives in safe Rust next door, in
        // android_purchase_wire.rs.
        "android_purchases.rs",
        "android_text_input.rs",
        // One `AChoreographer_postFrameCallback64` and the callback it posts,
        // which is how the frame loop learns when the display is ready for the
        // next frame.
        "android_vsync.rs",
        "android_writable_folder.rs",
        // The process readings every application that watches its own
        // footprint would otherwise write for itself: `getrusage`, `sysconf`,
        // `mallopt` and `os_proc_available_memory`, each behind one contract.
        "process_info.rs",
        "ios_file_picker.rs",
        "ios_uri_handler.rs",
        "ios_clipboard.rs",
        "ios_share_sheet.rs",
        "ios_image_picker.rs",
        "ios_notifier.rs",
        "ios_writable_folder.rs",
        "ios_camera.rs",
        // AVAudioPlayer, the audio-session interruption observer and the
        // MediaPlayer remote commands, behind the same reviewed boundary as
        // the other iOS services.
        "ios_media.rs",
        "ios_keyboard.rs",
        "ios_back_gesture.rs",
        "ios_background.rs",
        "ios_host.rs",
        "ios_accessibility.rs",
        "desktop_accessibility.rs",
    ];
    let mut offenders = Vec::new();

    for path in rust_sources(&source_dir) {
        let relative = path
            .strip_prefix(&source_dir)
            .expect("source path should be under src");
        let file_name = relative
            .file_name()
            .and_then(|name| name.to_str())
            .expect("source file should have a UTF-8 name");
        if allowed.contains(&file_name) {
            continue;
        }

        let source = std::fs::read_to_string(&path).expect("failed to read cranpose source file");
        if source_has_unsafe_boundary_escape(&source) {
            offenders.push(relative.display().to_string());
        }
    }

    assert!(
        offenders.is_empty(),
        "unsafe code must stay in reviewed platform boundary modules; found in {offenders:?}"
    );
}

#[test]
fn android_surface_boundary_returns_typed_errors() {
    let source = crate_source("src/android_surface.rs");

    assert!(
        source.contains("enum AndroidSurfaceError")
            && source.contains("Result<wgpu::Surface<'static>, AndroidSurfaceError>"),
        "Android WGPU surface creation should expose a typed error from the unsafe boundary"
    );
    assert!(
        !source.contains(".expect("),
        "Android WGPU surface creation must not panic inside the unsafe boundary"
    );
}

#[test]
fn android_gpu_initialization_returns_typed_errors() {
    let runtime_source = crate_source("src/android.rs");
    let surface_source = crate_source("src/android_surface.rs");

    assert!(
        !runtime_source.contains(".expect(\"Failed to find suitable adapter\")")
            && !runtime_source.contains(".expect(\"Failed to create device\")"),
        "Android GPU initialization should return typed adapter/device errors instead of panicking"
    );
    assert!(
        surface_source.contains("RequestAdapter(#[from] wgpu::RequestAdapterError)")
            && surface_source.contains("RequestDevice(#[from] wgpu::RequestDeviceError)"),
        "Android GPU initialization errors should be represented in AndroidSurfaceError"
    );
}

#[test]
fn desktop_native_window_gpu_context_absence_returns_launch_error() {
    let desktop_source = crate_source("src/desktop.rs");
    let launcher_source = crate_source("src/app_launcher.rs");

    assert!(
        !desktop_source.contains("native windows require an initialized desktop GPU context"),
        "native peer-window creation should return LaunchError when the desktop GPU context is unavailable"
    );
    assert!(
        launcher_source.contains("GpuContextUnavailable"),
        "LaunchError should represent missing desktop GPU context explicitly"
    );
}

#[test]
fn desktop_launch_content_unavailable_returns_launch_error() {
    let desktop_source = crate_source("src/desktop.rs");
    let launcher_source = crate_source("src/app_launcher.rs");

    assert!(
        !desktop_source.contains("content already taken"),
        "desktop startup should return LaunchError when the content closure is unavailable"
    );
    assert!(
        desktop_source.contains("LaunchError::ContentUnavailable")
            && launcher_source.contains("ContentUnavailable"),
        "LaunchError should represent an unavailable desktop content closure explicitly"
    );
}

#[test]
fn desktop_run_wrappers_do_not_repanic_typed_launch_errors() {
    let desktop_source = crate_source("src/desktop.rs");
    let launcher_source = crate_source("src/app_launcher.rs");

    assert!(
        launcher_source.contains("fn exit_after_launch_error")
            && launcher_source.contains("std::process::exit(1)"),
        "desktop run wrappers should share an explicit process-exit boundary for launch failures"
    );
    assert!(
        !launcher_source.contains("panic!(\"desktop launch failed")
            && !desktop_source.contains("panic!(\"failed to launch desktop app"),
        "desktop run wrappers should not turn typed LaunchError values back into panics"
    );
    assert!(
        launcher_source.contains("exit_after_launch_error(\"desktop launch failed\", error)")
            && desktop_source.contains(
                "crate::app_launcher::exit_after_launch_error(\"desktop launch failed\", error)"
            ),
        "AppLauncher::run, AppLauncher::run_windows, and desktop::run should use the same launch-error exit path"
    );
}

#[test]
fn wasm_runtime_scheduler_is_single_threaded() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let platform =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-core/src/platform.rs"))
            .expect("failed to read platform.rs");
    let runtime =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-core/src/runtime.rs"))
            .expect("failed to read runtime.rs");
    let std_runtime =
        std::fs::read_to_string(workspace_dir.join("crates/cranpose-runtime-std/src/lib.rs"))
            .expect("failed to read cranpose-runtime-std");

    assert!(
        platform.contains(
            "#[cfg(not(target_arch = \"wasm32\"))]\npub trait RuntimeScheduler: Send + Sync"
        ) && platform.contains("#[cfg(target_arch = \"wasm32\")]\npub trait RuntimeScheduler"),
        "RuntimeScheduler must keep Send+Sync on native and avoid fake Sync on wasm"
    );
    assert!(
        runtime.contains("runtime_id: RuntimeId")
            && runtime.contains("REGISTERED_RUNTIMES.with")
            && runtime.contains("#[cfg(target_arch = \"wasm32\")]\n    fn wake_by_ref"),
        "wasm task wakers should route by runtime id instead of storing a Send+Sync scheduler"
    );
    assert!(
        std_runtime.contains("RefCell<Option<Box<dyn Fn() + 'static>>>")
            && std_runtime.contains("pub fn set_frame_waker(&self, waker: impl Fn() + 'static)"),
        "wasm frame wakers should not require Send or Sync"
    );
}

#[test]
fn workspace_ffi_boundaries_are_explicit() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source_roots = ["crates", "apps", "xtask"];
    let allowed = [
        // The display-shape read behind the renderer's visible-region cull:
        // one `dlsym`-resolved `AConfiguration_getScreenRound` call (the
        // symbol is API 30+, so it must not be linked) and the call through
        // it.
        "crates/cranpose/src/android_display.rs",
        // The entry-point macro: one `#[no_mangle]` in the expansion it writes,
        // which is the symbol `NativeActivity` resolves after loading the
        // library. It replaced the same attribute in every application.
        "crates/cranpose/src/android_entry.rs",
        // The display refresh-rate vote: `dlsym`/`dlopen` resolution of the
        // `ANativeWindow_setFrameRate*` NDK symbols and the calls through
        // them, mirroring how HWUI votes the panel's frame rate.
        "crates/cranpose/src/android_frame_rate.rs",
        "crates/cranpose/src/android_perf_hint.rs",
        "crates/cranpose/src/android_frame_telemetry.rs",
        "crates/cranpose/src/android_jni.rs",
        "crates/cranpose/src/android_accessibility.rs",
        // Camera and host JNI calls stay behind the same reviewed activity
        // boundary as the other Android services.
        "crates/cranpose/src/android_camera.rs",
        "crates/cranpose/src/android_host.rs",
        // The media JNI surface: the exported symbols `CranposeMedia` pushes
        // playback state, position, focus and lock-screen buttons through.
        "crates/cranpose/src/android_media.rs",
        "crates/cranpose/src/android_services.rs",
        "crates/cranpose/src/android_surface.rs",
        "crates/cranpose/src/android_file_picker.rs",
        // The Play Billing bridge: the exported symbols
        // `dev.cranpose.android.CranposeBilling` calls back through, and
        // nothing else. Decoding the payloads they carry lives in safe Rust in
        // android_purchase_wire.rs, which is built and tested on the host.
        "crates/cranpose/src/android_purchases.rs",
        "crates/cranpose/src/android_text_input.rs",
        // One `AChoreographer_postFrameCallback64` and the callback it posts,
        // which is how the frame loop learns when the display is ready for the
        // next frame.
        "crates/cranpose/src/android_vsync.rs",
        "crates/cranpose/src/android_writable_folder.rs",
        // The process readings every application that watches its own
        // footprint would otherwise write for itself: `getrusage`, `sysconf`,
        // `mallopt` and `os_proc_available_memory`, each behind one contract.
        "crates/cranpose/src/process_info.rs",
        "crates/cranpose/src/ios_file_picker.rs",
        "crates/cranpose/src/ios_uri_handler.rs",
        "crates/cranpose/src/ios_clipboard.rs",
        "crates/cranpose/src/ios_share_sheet.rs",
        "crates/cranpose/src/ios_image_picker.rs",
        "crates/cranpose/src/ios_notifier.rs",
        "crates/cranpose/src/ios_writable_folder.rs",
        "crates/cranpose/src/ios_camera.rs",
        // AVAudioPlayer, the audio-session interruption observer and the
        // MediaPlayer remote commands, behind the same reviewed boundary as
        // the other iOS services.
        "crates/cranpose/src/ios_media.rs",
        "crates/cranpose/src/ios_keyboard.rs",
        "crates/cranpose/src/ios_back_gesture.rs",
        "crates/cranpose/src/ios_background.rs",
        "crates/cranpose/src/ios_host.rs",
        "crates/cranpose/src/ios_accessibility.rs",
        "crates/cranpose/src/desktop_accessibility.rs",
        // The StoreKit 2 bridge: `extern "C"` declarations for the Swift shim
        // plus the callback it invokes. The crate root denies unsafe code and
        // opts this one module back in by name.
        "crates/cranpose-storekit/src/apple.rs",
        // The audio engine's two boundaries: the lock-free queue that carries
        // commands to the real-time thread, and the AAudio callback that turns
        // the device's raw output pointer into a slice. The crate root denies
        // unsafe code and opts these back in by name.
        "crates/cranpose-audio/src/ring.rs",
        "crates/cranpose-audio/src/backend/aaudio.rs",
        // The renderer's fixed frame worker pool: lending frame-local borrows
        // to persistent parked workers cannot be expressed safely in std (the
        // problem rayon exists for). The unsafety is two pointer wrappers
        // whose invariants the pool's completion barrier enforces; the crate
        // root denies unsafe code and opts this one module back in by name.
        "crates/cranpose-render/wgpu/src/worker_pool.rs",
        // The pipeline disk cache: one wgpu create_pipeline_cache call,
        // unsafe because seeding data is trusted; the module writes that
        // data itself from get_data, keys the file by adapter identity,
        // and asks wgpu to validate the header besides (fallback: true).
        "crates/cranpose-render/wgpu/src/pipeline_disk_cache.rs",
        // The shape-run entry borrows its DrawPrimitive, whose TYPE is !Sync
        // (the Text variant holds Rc) even though the constructor only ever
        // admits the Sync-payload shape variants. The module is kept tiny so
        // the constructor invariant and the two manual Send/Sync impls stay
        // on one screen; the crate root denies unsafe code and opts this one
        // module back in by name.
        "crates/cranpose-render/wgpu/src/run_entry.rs",
        // The stage executor's spare-capacity map_fill: chunks write map
        // results straight into the output vec's reserved capacity, which
        // std vectors cannot express safely. The unsafety lives in the
        // constructor-limited spare_fill module — claim flags turn a
        // double-filled chunk into a panic, per-chunk watermarks bound the
        // unwind path's drops — and the crate root denies unsafe code and
        // opts this one module back in by name.
        "crates/cranpose-render/wgpu/src/stage_executor.rs",
    ];
    let guard_source = Path::new("crates/cranpose/tests/platform_scheduling_static.rs");
    let mut offenders = Vec::new();

    for root in source_roots {
        for path in rust_sources(&workspace_dir.join(root)) {
            let relative = path
                .strip_prefix(workspace_dir)
                .expect("source path should be under workspace");
            if relative == guard_source {
                continue;
            }
            let relative_display = relative.display().to_string();
            if allowed.contains(&relative_display.as_str()) {
                continue;
            }

            let source = std::fs::read_to_string(&path).expect("failed to read source file");
            if source_has_unsafe_boundary_escape(&source) {
                offenders.push(relative_display);
            }
        }
    }

    assert!(
        offenders.is_empty(),
        "workspace unsafe/FFI boundary code must stay in reviewed boundary modules; found in {offenders:?}"
    );
}

#[test]
fn unsafe_blocks_have_nearby_safety_invariants() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let boundary_modules = [
        "crates/cranpose/src/android_jni.rs",
        "crates/cranpose/src/android_surface.rs",
        "crates/cranpose/src/ios_accessibility.rs",
        "crates/cranpose-audio/src/ring.rs",
        "crates/cranpose-audio/src/backend/aaudio.rs",
        "crates/cranpose-render/wgpu/src/pipeline_disk_cache.rs",
        // The exported `android_main` symbol, written once by the framework's
        // `android_main!` macro rather than once per application.
        "crates/cranpose/src/android_entry.rs",
    ];
    let mut offenders = Vec::new();

    for module in boundary_modules {
        let source = std::fs::read_to_string(workspace_dir.join(module))
            .unwrap_or_else(|err| panic!("failed to read {module}: {err}"));
        offenders.extend(
            unsafe_lines_without_safety_invariant(&source)
                .into_iter()
                .map(|line| format!("{module}:{line}")),
        );
    }

    assert!(
        offenders.is_empty(),
        "unsafe blocks must include a nearby SAFETY invariant:\n{}",
        offenders.join("\n")
    );
}

#[test]
fn workspace_sources_do_not_cfg_on_robot_app_feature() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source_roots = ["crates", "apps"];
    let cfg_feature = ["cfg(feature = \"", "robot-app", "\")"].concat();
    let cfg_feature_tight = ["cfg(feature=\"", "robot-app", "\")"].concat();
    let cfg_attr_feature = ["cfg_attr(feature = \"", "robot-app", "\""].concat();
    let cfg_attr_feature_tight = ["cfg_attr(feature=\"", "robot-app", "\""].concat();
    let blocked_patterns = [
        cfg_feature,
        cfg_feature_tight,
        cfg_attr_feature,
        cfg_attr_feature_tight,
    ];
    let guard_source = Path::new("crates/cranpose/tests/platform_scheduling_static.rs");
    let mut offenders = Vec::new();

    for root in source_roots {
        for path in rust_sources(&workspace_dir.join(root)) {
            let relative = path
                .strip_prefix(workspace_dir)
                .expect("source path should be under workspace");
            if relative == guard_source {
                continue;
            }
            let source = std::fs::read_to_string(&path)
                .unwrap_or_else(|err| panic!("failed to read {}: {err}", relative.display()));
            for (line_number, line) in source.lines().enumerate() {
                if blocked_patterns
                    .iter()
                    .any(|pattern| line.contains(pattern))
                {
                    offenders.push(format!("{}:{}", relative.display(), line_number + 1));
                }
            }
        }
    }

    assert!(
        offenders.is_empty(),
        "runtime/source behavior must not be gated on the desktop robot-app feature:\n{}",
        offenders.join("\n")
    );
}

#[test]
fn crate_roots_deny_unsafe_code() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let roots = workspace_crate_roots(workspace_dir);

    let missing = roots
        .iter()
        .filter_map(|path| {
            let relative = path
                .strip_prefix(workspace_dir)
                .expect("crate root should live under workspace");
            let source = std::fs::read_to_string(path)
                .unwrap_or_else(|err| panic!("failed to read {}: {err}", relative.display()));
            (!source.contains("#![deny(unsafe_code)]")).then(|| relative.display().to_string())
        })
        .collect::<Vec<_>>();

    assert!(
        !roots.is_empty(),
        "workspace crate root discovery found no roots"
    );
    assert!(
        missing.is_empty(),
        "crate roots must deny unsafe code; missing in {missing:?}"
    );
}

#[test]
fn workspace_sources_avoid_half_state_language() {
    let cranpose_dir = Path::new(env!("CARGO_MANIFEST_DIR"));
    let workspace_dir = cranpose_dir
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under workspace crates directory");
    let source_roots = ["crates", "apps", "docs"];
    let single_files = ["README.md"];
    let blocked_terms = [
        ("TO", "DO:"),
        ("TO", "DO!("),
        ("FIX", "ME"),
        ("leg", "acy"),
        ("old ", "way"),
        ("when ", "implemented"),
        ("migra", "tion"),
        ("work", "around"),
        ("backward ", "compat"),
        ("backwards ", "compat"),
    ]
    .map(|(left, right)| format!("{left}{right}").to_lowercase());
    let guard_source = Path::new("crates/cranpose/tests/platform_scheduling_static.rs");
    let mut offenders = Vec::new();

    for root in source_roots {
        for path in text_sources(&workspace_dir.join(root)) {
            let relative = path
                .strip_prefix(workspace_dir)
                .expect("source path should be under workspace");
            if relative == guard_source {
                continue;
            }
            collect_blocked_language_offenders(
                workspace_dir,
                relative,
                &blocked_terms,
                &mut offenders,
            );
        }
    }
    for file in single_files {
        collect_blocked_language_offenders(
            workspace_dir,
            Path::new(file),
            &blocked_terms,
            &mut offenders,
        );
    }

    assert!(
        offenders.is_empty(),
        "workspace text should describe the current architecture directly; found prohibited half-state wording:\n{}",
        offenders.join("\n")
    );
}

fn source_has_unsafe_boundary_escape(source: &str) -> bool {
    source.lines().any(|line| {
        let trimmed = line.trim();
        if trimmed.starts_with("//") {
            return false;
        }
        (trimmed.contains("unsafe") || trimmed.contains("#[no_mangle]"))
            && trimmed != "#![deny(unsafe_code)]"
    })
}

fn unsafe_lines_without_safety_invariant(source: &str) -> Vec<usize> {
    let lines = source.lines().collect::<Vec<_>>();
    lines
        .iter()
        .enumerate()
        .filter_map(|(index, line)| {
            if !line_requires_safety_invariant(line) {
                return None;
            }
            let start = index.saturating_sub(3);
            let has_safety = lines[start..index]
                .iter()
                .any(|previous| previous.trim_start().starts_with("// SAFETY:"));
            (!has_safety).then_some(index + 1)
        })
        .collect()
}

fn line_requires_safety_invariant(line: &str) -> bool {
    let trimmed = line.trim_start();
    if trimmed.starts_with("//") || trimmed.starts_with("#![") || trimmed.starts_with("#[") {
        return false;
    }

    trimmed.contains("unsafe {")
        || trimmed.contains("unsafe{")
        || trimmed.starts_with("unsafe fn ")
        || trimmed.contains(" unsafe fn ")
        || trimmed.starts_with("unsafe impl ")
        || trimmed.contains(" unsafe impl ")
}

fn collect_blocked_language_offenders(
    workspace_dir: &Path,
    relative: &Path,
    blocked_terms: &[String],
    offenders: &mut Vec<String>,
) {
    let path = workspace_dir.join(relative);
    let source = std::fs::read_to_string(&path)
        .unwrap_or_else(|err| panic!("failed to read {}: {err}", relative.display()));
    for (line_number, line) in source.lines().enumerate() {
        let lower = line.to_lowercase();
        if let Some(term) = blocked_terms
            .iter()
            .find(|term| lower.contains(term.as_str()))
        {
            offenders.push(format!(
                "{}:{}: contains `{}`",
                relative.display(),
                line_number + 1,
                term
            ));
        }
    }
}

fn collect_forbidden_time_source_offenders(
    workspace_dir: &Path,
    path: &Path,
    offenders: &mut Vec<String>,
) {
    let relative = path
        .strip_prefix(workspace_dir)
        .expect("source path should be under workspace");
    let source = std::fs::read_to_string(path)
        .unwrap_or_else(|err| panic!("failed to read {}: {err}", relative.display()));

    collect_forbidden_time_source_offenders_from_source(relative, &source, offenders);
}

fn collect_forbidden_time_source_offenders_from_source(
    relative: &Path,
    source: &str,
    offenders: &mut Vec<String>,
) {
    let mut pending_use = String::new();
    let mut pending_use_start_line = 0;

    for (index, line) in source.lines().enumerate() {
        let line_number = index + 1;
        let Some(code) = rust_code_before_line_comment(line) else {
            continue;
        };
        let trimmed = code.trim_start();
        if trimmed.is_empty() || trimmed.starts_with("#![") || trimmed.starts_with("#[") {
            continue;
        }

        if !pending_use.is_empty() {
            pending_use.push(' ');
            pending_use.push_str(trimmed);
            if trimmed.contains(';') {
                if let Some(reason) = forbidden_std_time_import_reason(&pending_use) {
                    offenders.push(format!(
                        "{}:{}: {reason}",
                        relative.display(),
                        pending_use_start_line
                    ));
                }
                pending_use.clear();
                pending_use_start_line = 0;
            }
            continue;
        }

        if starts_use_statement(trimmed) {
            pending_use_start_line = line_number;
            pending_use.push_str(trimmed);
            if trimmed.contains(';') {
                if let Some(reason) = forbidden_std_time_import_reason(&pending_use) {
                    offenders.push(format!(
                        "{}:{}: {reason}",
                        relative.display(),
                        pending_use_start_line
                    ));
                }
                pending_use.clear();
                pending_use_start_line = 0;
            }
            continue;
        }

        let normalized = rust_path_source(trimmed);
        if let Some(fragment) = forbidden_std_time_path_fragment(&normalized) {
            offenders.push(format!(
                "{}:{}: uses `{fragment}`",
                relative.display(),
                line_number
            ));
        }
    }

    if !pending_use.is_empty() {
        if let Some(reason) = forbidden_std_time_import_reason(&pending_use) {
            offenders.push(format!(
                "{}:{}: {reason}",
                relative.display(),
                pending_use_start_line
            ));
        }
    }
}

fn rust_code_before_line_comment(line: &str) -> Option<&str> {
    let trimmed = line.trim_start();
    if trimmed.starts_with("//") || trimmed.starts_with("///") || trimmed.starts_with("//!") {
        return None;
    }

    line.split_once("//")
        .map(|(before_comment, _)| before_comment)
        .or(Some(line))
}

fn starts_use_statement(trimmed: &str) -> bool {
    trimmed.starts_with("use ")
        || trimmed.starts_with("pub use ")
        || (trimmed.starts_with("pub(") && trimmed.contains(" use "))
}

fn forbidden_std_time_import_reason(statement: &str) -> Option<&'static str> {
    let normalized = rust_path_source(statement);

    if forbidden_std_time_path_fragment(&normalized).is_some() {
        return Some("imports unsupported std::time::Instant/SystemTime");
    }
    if std_time_group_contains_forbidden_member(&normalized) {
        return Some("imports unsupported std::time::Instant/SystemTime");
    }
    if std_nested_group_contains_forbidden_time_member(&normalized) {
        return Some("imports unsupported std::time::Instant/SystemTime");
    }

    None
}

fn forbidden_std_time_path_fragment(normalized: &str) -> Option<&'static str> {
    if normalized.contains("std::time::Instant") {
        return Some("std::time::Instant");
    }
    if normalized.contains("std::time::SystemTime") {
        return Some("std::time::SystemTime");
    }

    None
}

fn std_time_group_contains_forbidden_member(normalized: &str) -> bool {
    group_contents_after(normalized, "std::time::{").is_some_and(contains_forbidden_time_member)
}

fn std_nested_group_contains_forbidden_time_member(normalized: &str) -> bool {
    group_contents_after(normalized, "std::{").is_some_and(|std_group| {
        std_group.contains("time::Instant")
            || std_group.contains("time::SystemTime")
            || group_contents_after(std_group, "time::{")
                .is_some_and(contains_forbidden_time_member)
    })
}

fn contains_forbidden_time_member(group: &str) -> bool {
    rust_path_segment_exists(group, "Instant") || rust_path_segment_exists(group, "SystemTime")
}

fn rust_path_segment_exists(source: &str, segment: &str) -> bool {
    let mut remaining = source;
    while let Some(offset) = remaining.find(segment) {
        let before = remaining[..offset].chars().next_back();
        let after = remaining[offset + segment.len()..].chars().next();
        if before.is_none_or(|ch| !rust_identifier_char(ch))
            && after.is_none_or(|ch| !rust_identifier_char(ch))
        {
            return true;
        }
        remaining = &remaining[offset + segment.len()..];
    }
    false
}

fn rust_identifier_char(ch: char) -> bool {
    ch == '_' || ch.is_ascii_alphanumeric()
}

fn group_contents_after<'a>(source: &'a str, prefix: &str) -> Option<&'a str> {
    let start = source.find(prefix)? + prefix.len();
    let mut depth = 1usize;

    for (offset, ch) in source[start..].char_indices() {
        match ch {
            '{' => depth += 1,
            '}' => {
                depth -= 1;
                if depth == 0 {
                    return Some(&source[start..start + offset]);
                }
            }
            _ => {}
        }
    }

    Some(&source[start..])
}

fn rust_path_source(source: &str) -> String {
    source.chars().filter(|ch| !ch.is_whitespace()).collect()
}

fn text_sources(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    collect_text_sources(root, &mut out);
    out
}

fn collect_text_sources(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in std::fs::read_dir(dir).expect("failed to read source directory") {
        let path = entry.expect("failed to read source directory entry").path();
        if path.is_dir() {
            let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
                continue;
            };
            if matches!(name, "target" | ".git" | ".gradle" | "build") {
                continue;
            }
            collect_text_sources(&path, out);
            continue;
        }
        let extension = path.extension().and_then(|extension| extension.to_str());
        if matches!(extension, Some("rs" | "md" | "toml" | "sh")) {
            out.push(path);
        }
    }
}

fn rust_sources(root: &Path) -> Vec<PathBuf> {
    let mut out = Vec::new();
    collect_rust_sources(root, &mut out);
    out
}

fn workspace_crate_roots(workspace_dir: &Path) -> Vec<PathBuf> {
    let mut roots = Vec::new();
    for source_root in ["crates", "apps", "xtask"] {
        for path in rust_sources(&workspace_dir.join(source_root)) {
            if is_crate_root_source(&path) {
                roots.push(path);
            }
        }
    }
    roots
}

/// Every store backend has to announce news, not only wake the loop.
///
/// `observe_store_news` exists because `take_event`/`store_state` are polling
/// APIs and an idle app has no frame loop to poll from. A backend that only
/// calls `wake_native_loop()` leaves the app to notice on some later frame it
/// may never run: measured on a watch app, zero CPU jiffies over ten seconds on
/// the screen showing a price, so a purchase approved while sitting there would
/// never have been seen. iOS announced from the day the listener landed and
/// Android did not, which is the asymmetry this pins down -- one backend
/// growing a new decode path and forgetting to tell anyone is the same bug
/// again.
#[test]
fn every_store_backend_tells_the_app_rather_than_leaving_it_to_ask() {
    let android = crate_source("src/android_purchases.rs");
    let apple = workspace_source("crates/cranpose-storekit/src/apple.rs");

    for (backend, source) in [("android", &android), ("apple", &apple)] {
        assert!(
            source.contains("note_store_news()"),
            "the {backend} store backend must announce news through note_store_news()"
        );
    }

    // Both JNI entry points, not just whichever one was noticed first: a
    // snapshot and an event are separate ways for the store to have news.
    for entry_point in [
        "Java_dev_cranpose_android_CranposeBilling_nativeBillingSnapshot",
        "Java_dev_cranpose_android_CranposeBilling_nativeBillingEvent",
    ] {
        let body = android
            .split(entry_point)
            .nth(1)
            .unwrap_or_else(|| panic!("{entry_point} should exist in android_purchases.rs"));
        let body = body
            .split("pub extern \"system\"")
            .next()
            .expect("an entry point body should be delimited by the next one");
        assert!(
            body.contains("note_store_news()"),
            "{entry_point} decodes store news and must announce it, not only wake the loop"
        );
    }
}

#[test]
fn storekit_bridge_exposes_listener_liveness_and_rebuilds_it() {
    let apple = workspace_source("crates/cranpose-storekit/src/apple.rs");
    let swift = workspace_source("crates/cranpose-storekit/swift/storekit.swift");
    assert!(apple.contains("cranpose_storekit_is_connected"));
    assert!(apple.contains("fn is_connected(&self) -> bool"));
    assert!(swift.contains("cranpose_storekit_is_connected"));
    assert!(swift.contains("_listenerActive"));
    assert!(swift.contains("_listenerActive = false"));
    assert!(swift.contains("if !_listenerActive"));
}

#[test]
fn android_service_registration_replaces_the_relaunch_waker() {
    let services = crate_source("src/android_services.rs");
    assert!(services.contains("LOOP_WAKER.get_or_init"));
    assert!(services.contains("*waker = Some(app.create_waker())"));
    assert!(!services.contains("let _ = LOOP_WAKER.set"));
}

/// The Gradle task that runs `cargo ndk` must declare the directory it writes
/// as an output.
///
/// The `.so` lands in a directory the Android plugin has already been told to
/// read as `jniLibs`, and the merge/package tasks depend on the cargo task, so
/// the ordering looks right. It is not enough: a task that writes files outside
/// its declared outputs leaves Gradle's file-system snapshot of that directory
/// untouched, so the packaging tasks downstream check a pre-cargo snapshot,
/// report UP-TO-DATE, and build the APK around the PREVIOUS run's library.
///
/// Nothing about that is visible from the build log — it says BUILD SUCCESSFUL
/// — and nothing is visible on device either, beyond code behaving as it did
/// one build ago. It costs whole debugging sessions: a fix verified on the host
/// "does not reproduce" on the phone or the watch, which reads as a
/// platform-specific defect and sends the search into the framework. Run the
/// build twice and the symptom evaporates, which makes it look intermittent on
/// top of that.
///
/// `outputs.upToDateWhen { false }` does not cover this. It decides whether the
/// cargo task itself re-runs; it says nothing about what the task changed.
///
/// One Gradle plugin registers that task for every Cranpose application, so
/// this is asserted once, where it is written.
#[test]
fn the_gradle_plugin_declares_the_jni_library_directory_cargo_writes() {
    let plugin = workspace_source(CRANPOSE_GRADLE_PLUGIN);

    assert!(
        plugin.contains("jniLibs.directories.add(nativeOutput.absolutePath)"),
        "the plugin must point the Android source sets at the directory cargo-ndk writes"
    );
    assert!(
        plugin.contains("outputs.dir(nativeOutput)"),
        "the cargo-ndk task must declare the directory it writes as its output, or Gradle \
         keeps a stale snapshot of the jniLibs directory and the APK ships the previous \
         build's .so"
    );
    assert!(
        plugin.contains("outputs.upToDateWhen { false }"),
        "the cargo-ndk task declares an output directory, so it also needs \
         outputs.upToDateWhen {{ false }} or Gradle will skip the cargo build whenever that \
         directory happens to be unchanged"
    );

    // `mergeJniLibFolders` collects the source directories and `mergeNativeLibs`
    // collects the libraries inside them; both read the directory cargo writes,
    // so both have to wait for it. Wiring only one is what Gradle reports as an
    // implicit dependency once the output is declared above.
    assert!(
        plugin.contains("task.name.contains(\"NativeLibs\")")
            && plugin.contains("task.name.contains(\"JniLibFolders\")"),
        "the cargo build must be wired to mergeJniLibFolders as well as mergeNativeLibs -- \
         both consume the directory it writes"
    );
}

/// No application re-implements the native build the plugin owns.
///
/// A hand-rolled `cargo ndk` task in an application's build file is how the
/// stale-`.so` failure above comes back: the fix lives in the plugin, and a
/// copy that predates it keeps shipping the previous build.
#[test]
fn android_applications_build_their_native_library_through_the_plugin() {
    for relative in ANDROID_APPLICATION_BUILD_FILES {
        let source = workspace_source(relative);
        assert!(
            source.contains("id(\"dev.cranpose.android\")"),
            "{relative} must apply the Cranpose Gradle plugin rather than configuring an \
             Android application by hand"
        );
        assert!(
            !source.contains("cargo ndk"),
            "{relative} runs cargo ndk itself; the plugin owns the native build, the ABIs, \
             the Cargo profiles and the output declaration that keeps the APK from shipping \
             a stale library"
        );
        assert!(
            !source.contains("jniLibs.directories.add"),
            "{relative} points a source set at the native output itself; the plugin does \
             that, together with declaring the task output that keeps it fresh"
        );
    }
}

/// The activity, its launcher entry and the `android.app.lib_name` metadata are
/// the framework's contract with `NativeActivity`. An application that declares
/// its own copy silently owns a contract it cannot see change.
#[test]
fn android_applications_do_not_declare_the_framework_activity() {
    for relative in ANDROID_APPLICATION_MANIFESTS {
        let manifest = strip_xml_comments(&workspace_source(relative));
        assert!(
            !manifest.contains("<activity"),
            "{relative} declares an activity; the Cranpose library contributes the activity, \
             its launcher filter and its lib_name metadata to every application's manifest"
        );
        assert!(
            !manifest.contains("android.app.lib_name"),
            "{relative} names the cdylib itself; the plugin supplies that name from \
             cranpose {{ cargoPackage }} so it cannot drift from what Cargo builds"
        );
    }
}

/// `web.rs` compiles only for `wasm32`, so nothing in `cargo test` links it —
/// reading the source is the only guard available on the host, and the
/// alternative is finding out in a browser. This contract regressed silently
/// once already: the wheel listener grew its own copy of the desktop's policy,
/// inverted, and never offered the wheel to rotary at all.
#[test]
fn the_browser_host_shares_the_wheel_policy() {
    let web = crate_source("src/web.rs");

    assert!(
        web.contains("app_mut.wheel_scrolled(wheel)"),
        "the browser wheel listener must go through the shell's shared wheel policy, \
         so zoom, rotary and scroll mean the same thing they do on every other host"
    );
    assert!(
        !web.contains("app_mut.pointer_scrolled("),
        "the browser host must not reach past wheel_scrolled to the scroll step: that \
         skips rotary and re-opens the sign question the shared policy settles"
    );
}

/// The same unreachable-source problem for the clipboard: with no bridge
/// installed the in-tree selection menu's Copy reaches an in-process clipboard
/// that nothing outside the page can read, and every platform but the browser
/// had one.
#[test]
fn the_browser_host_installs_a_platform_clipboard() {
    assert!(
        crate_source("src/web.rs").contains("crate::web_clipboard::install("),
        "the browser host must install a platform clipboard, or the in-tree selection \
         menu's Copy/Cut never leave the page"
    );
}

fn is_crate_root_source(path: &Path) -> bool {
    let Some(file_name) = path.file_name().and_then(|name| name.to_str()) else {
        return false;
    };
    if !matches!(file_name, "lib.rs" | "main.rs") {
        return false;
    }
    path.parent()
        .and_then(Path::file_name)
        .and_then(|name| name.to_str())
        == Some("src")
}

fn collect_rust_sources(dir: &Path, out: &mut Vec<PathBuf>) {
    for entry in std::fs::read_dir(dir).expect("failed to read cranpose source directory") {
        let path = entry.expect("failed to read source directory entry").path();
        if path.is_dir() {
            collect_rust_sources(&path, out);
        } else if path.extension().and_then(|extension| extension.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

/// Density, the viewport, the platform's fonts and the log tag are all things
/// an application needs and none of them are things it should discover for
/// itself: each answer sits behind a different platform API, and a call site
/// that reaches for one is wrong on the target it did not write.
///
/// Every host therefore publishes its surface the same way, and the launcher
/// resolves the font directory and the log tag, so no application repeats any
/// of it.
#[test]
fn every_host_reports_its_surface_the_same_way() {
    for (relative, host) in [
        ("src/android.rs", "Android"),
        ("src/desktop.rs", "the desktop"),
        ("src/ios.rs", "iOS"),
        ("src/web_host_surface.rs", "the browser"),
    ] {
        let source = crate_source(relative);
        assert!(
            source.contains("publish_host_surface_size("),
            "{host} must publish its surface size, or `host_density` and \
             `rememberHostSurfaceSize` answer for every target but this one"
        );
    }
}

/// The framework owns where a platform keeps its fonts, so an application never
/// names a system path and never draws in the wrong typeface on the target it
/// did not name one for.
#[test]
fn the_launcher_resolves_the_platform_font_directory_itself() {
    let launcher = crate_source("src/app_launcher.rs");
    assert!(
        launcher.contains("crate::system_font_directory()"),
        "with_system_fonts must resolve the platform's font directory rather than \
         asking the application for a path"
    );
    assert!(
        crate_source("src/host_environment.rs").contains("ANDROID_SYSTEM_FONT_DIR"),
        "the resolver must name Android's directory rather than leaving the app to"
    );
}

/// An application that wants its own name on its log lines had to initialise the
/// platform logger before the framework did and hope the ordering held; the tag
/// is a launcher setting instead.
#[test]
fn the_android_host_takes_its_log_tag_from_the_launcher() {
    let android = crate_source("src/android.rs");
    assert!(
        android.contains("settings.log_tag.as_deref().unwrap_or(DEFAULT_LOG_TAG)"),
        "the Android host must log under the tag the application named"
    );
    assert!(
        !android.contains("\"ComposeRS\""),
        "the framework is Cranpose; a stale name in logcat sends anyone reading \
         them looking for the wrong project"
    );
}

/// No application writes the Android entry point by hand.
///
/// It cost every application the same four lines — an `unsafe_code` allowance
/// for the export attribute, a `#[no_mangle]` it must not misspell, a
/// dependency on `android_activity` for nothing but a parameter type, and a
/// `target_os` guard — none of which is about the application. It is one macro
/// now, and the `#[no_mangle]` lives in one reviewed module rather than in
/// every consumer.
#[test]
fn applications_declare_their_android_entry_through_the_macro() {
    let workspace = Path::new(env!("CARGO_MANIFEST_DIR"))
        .parent()
        .and_then(Path::parent)
        .expect("cranpose crate should live under the workspace crates directory");

    let mut offenders = Vec::new();
    let mut declarations = 0usize;
    for root in ["apps"] {
        let mut sources = Vec::new();
        collect_rust_sources(&workspace.join(root), &mut sources);
        for path in sources {
            let source = std::fs::read_to_string(&path).expect("failed to read application source");
            let relative = path
                .strip_prefix(workspace)
                .expect("source should live under the workspace")
                .display()
                .to_string();
            if source.contains("cranpose::android_main!") {
                declarations += 1;
            }
            if source.contains("pub fn android_main(") || source.contains("fn android_main(") {
                offenders.push(relative);
            }
        }
    }

    assert!(
        offenders.is_empty(),
        "an application must declare its entry point with `cranpose::android_main!` rather \
         than exporting the symbol itself; found in {offenders:?}"
    );
    assert!(
        declarations >= 2,
        "expected the demo and the standalone starter to declare entry points, saw \
         {declarations}"
    );
}

/// An application update is the one download that can replace the application,
/// so what arrives is checked against what the release feed promised *before*
/// it reaches the platform installer.
///
/// Android's own signature check still runs afterwards and catches a package
/// signed by someone else. It does not catch one that arrived corrupted, or one
/// swapped for a differently-signed build the device would happily install as a
/// new application. Committing the session first and finding out afterwards is
/// not a check.
#[test]
fn the_android_installer_verifies_a_package_before_committing_it() {
    let java =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeActivity.java");

    let install = java
        .split("public void cranposeInstallUpdate(")
        .nth(1)
        .expect("the Android installer entry point");
    let commit = install
        .find("session.commit(")
        .expect("the installer must commit a session");
    let verify = install
        .find("digest.digest()")
        .expect("the installer must compute the package's digest");
    assert!(
        verify < commit,
        "the digest must be checked before the session is committed, or the check \
         happens after the package is already on its way to being installed"
    );
    assert!(
        install.contains("does not match its digest"),
        "a mismatch must fail the install rather than being logged and ignored"
    );
    assert!(
        java.contains("throw new IOException(\"unsupported package digest algorithm: \""),
        "a digest this platform cannot compute must fail rather than being skipped: a \
         check nobody performs reads as a package that was verified"
    );
    assert!(
        !install.contains("digest != null"),
        "there is no unverified path through the installer: a package reaches it with a \
         digest or it does not reach it at all"
    );
}

/// The framework computes a digest one way, so no platform's installer can
/// compute it differently and disagree with the one the release feed published.
#[test]
fn the_framework_owns_one_package_digest() {
    let update = workspace_source("crates/cranpose-services/src/app_update.rs");
    assert!(
        update.contains("pub struct DigestVerifier"),
        "the framework must own a package verifier rather than leaving each platform \
         installer to write its own"
    );
    assert!(
        update.contains("pub fn install_app_update(package: &UpdatePackage)"),
        "an install must take the package the feed described — its size and digest \
         included — rather than a bare URL nothing can be checked against"
    );
    let install = update
        .split("pub fn install_app_update(package: &UpdatePackage)")
        .nth(1)
        .expect("the install entry point");
    assert!(
        install.contains("AppUpdateError::Unverifiable"),
        "a package the framework cannot check must be refused: this is the one download \
         that replaces the application, and a feed that publishes no digest is a feed to \
         fix rather than a check to skip"
    );
}

/// A camera preview is the highest-rate path in the framework, so what it does
/// per frame is worth pinning down.
///
/// Routing frames through the filesystem — JPEG-compress on the Java side,
/// write to the cache directory, rename, read back, decode — costs an encode, a
/// write, a rename, a read and a decode on every single frame, which is a bill
/// only a preview capped at fifteen frames a second can pay. Waiting for a
/// still the same way means sleeping in twenty-millisecond steps until a marker
/// file appears, on whichever thread asked for it. This test pins down that
/// neither happens.
#[test]
fn the_android_camera_pushes_frames_rather_than_writing_them_to_files() {
    let camera =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeCamera.java");
    let activity =
        workspace_source("crates/cranpose/android/java/dev/cranpose/android/CranposeActivity.java");

    assert!(
        camera.contains("CranposeActivity.onCameraFrame("),
        "preview frames must be pushed to native code rather than left in a file to be found"
    );
    assert!(
        !camera.contains("compressToJpeg"),
        "a preview frame must not be JPEG-encoded to cross the language boundary"
    );
    for name in ["preview.jpg", "capture.jpg", "capture.ok"] {
        assert!(
            !camera.contains(name) && !activity.contains(name),
            "the camera must not transport {name} through the filesystem"
        );
    }
    assert!(
        !activity.contains("Thread.sleep(20)"),
        "a still must arrive rather than be waited for in a sleep loop"
    );
    assert!(
        camera.contains("CranposeActivity.onCameraFrameDropped()"),
        "a frame the device produced while the previous one was in flight must be counted, \
         so a detector that falls behind falls behind by frames rather than by memory"
    );
}

/// The framework's camera contract has no method that hands back a frame or a
/// picture, because both would mean waiting: a poll returns whatever was there
/// and a blocking capture stops whoever asked for as long as the device takes.
#[test]
fn the_camera_service_is_published_to_rather_than_polled() {
    let camera = workspace_source("crates/cranpose-services/src/camera.rs");
    assert!(
        !camera.contains("fn latest_frame(&self)"),
        "a camera backend must publish frames, not answer polls for them"
    );
    assert!(
        !camera.contains("fn capture_still(&self)"),
        "a still must be asked for and arrive, not be returned by a call that waits"
    );
    assert!(
        camera.contains("pub fn publish_camera_frame(")
            && camera.contains("fn request_still(&self)"),
        "the contract is publish-a-frame and ask-for-a-still"
    );
}

/// Every media backend the framework ships, so a contract test covers all of
/// them rather than whichever one was written last.
const MEDIA_BACKENDS: [&str; 4] = [
    "crates/cranpose-media/src/desktop.rs",
    "crates/cranpose/src/android_media.rs",
    "crates/cranpose/src/ios_media.rs",
    "crates/cranpose/src/web_media.rs",
];

/// A media player that is asked "where are you now?" every frame does that work
/// whether or not anything moved, and learns about a failure only by noticing
/// that the position stopped. The contract is the other way round: the backend
/// publishes, and a screen reacts.
#[test]
fn the_media_service_is_published_to_rather_than_polled() {
    let media = workspace_source("crates/cranpose-services/src/media.rs");
    assert!(
        !media.contains("fn position(&self)") && !media.contains("fn state(&self)"),
        "a media backend must publish where it is and what it is doing, not answer polls for them"
    );
    assert!(
        media.contains("pub fn publish_playback_state(")
            && media.contains("pub fn publish_playback_progress("),
        "the contract is publish-what-happened"
    );
    for backend in MEDIA_BACKENDS {
        let source = workspace_source(backend);
        assert!(
            source.contains("publish_playback_state"),
            "{backend} must publish what it is doing"
        );
    }
}

/// A control the device will not honour is worse than a control that is not
/// there: the user presses it and nothing happens. Every backend states what it
/// can do so a screen can leave out the rest.
#[test]
fn every_media_backend_states_what_it_can_do() {
    for backend in MEDIA_BACKENDS {
        let source = workspace_source(backend);
        assert!(
            source.contains("fn capabilities(&self)"),
            "{backend} must report its capabilities rather than let a screen assume them"
        );
    }
}

/// An equalizer has the bands its implementation has: ten octave bands where
/// the framework builds the filters, whatever the device offers where the
/// platform owns the effect, and none at all on a backend with nowhere to put
/// one. Every backend has to say which of those it is, because a screen draws
/// as many controls as there are bands.
#[test]
fn every_media_backend_states_the_equalizer_it_has() {
    for backend in MEDIA_BACKENDS {
        let source = workspace_source(backend);
        assert!(
            source.contains("equalizer:"),
            "{backend} must state whether it has an equalizer in its capabilities"
        );
        // A backend that claims one has to be able to report its bands.
        if source.contains("equalizer: false") {
            continue;
        }
        assert!(
            source.contains("fn equalizer_bands(&self)"),
            "{backend} claims an equalizer but never reports the bands it has"
        );
        assert!(
            source.contains("fn set_equalizer(&self"),
            "{backend} claims an equalizer but never applies a curve"
        );
    }
}

/// Ducking and forgetting to un-duck, or resuming after a phone call that was
/// never paused for, is the same bug written once per application. The policy
/// lives in the framework; a backend only reports what the platform told it.
#[test]
fn the_audio_focus_policy_lives_in_the_framework() {
    let media = workspace_source("crates/cranpose-services/src/media.rs");
    assert!(
        media.contains("pub fn publish_audio_focus(") && media.contains("PAUSED_BY_FOCUS"),
        "the framework decides what a lost focus means for playback, and remembers whether it \
         was the one that paused"
    );
    for backend in MEDIA_BACKENDS {
        let source = workspace_source(backend);
        for decision in ["pause_media(", "stop_media(", "play_media("] {
            assert!(
                !source.contains(decision),
                "{backend} must publish what the device did and leave `{decision}` to the \
                 framework's one policy"
            );
        }
    }
}

/// Media that carries on with the app off screen is the one service Android
/// requires a typed foreground service for, and `dataSync` — what the
/// background-work lease starts — is not that type.
#[test]
fn android_media_declares_the_foreground_service_it_needs() {
    let manifest = workspace_source("android/cranpose-android-media/src/main/AndroidManifest.xml");
    assert!(
        manifest.contains("android:foregroundServiceType=\"mediaPlayback\""),
        "playback that outlives the surface needs a mediaPlayback service"
    );
    assert!(
        manifest.contains("android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK"),
        "the mediaPlayback service needs its own permission"
    );
    let plugin = workspace_source(
        "android/cranpose-gradle-plugin/src/main/kotlin/dev/cranpose/gradle/CranposeAndroidPlugin.kt",
    );
    assert!(
        plugin.contains("\"media\","),
        "an application asks for the media service by name, so the plugin must know it"
    );
}

/// A permission an application writes into its own manifest is a permission the
/// framework's module system cannot leave out of an application that does not
/// use the service. Applications ask by service name; the module contributes
/// the permission.
#[test]
fn applications_ask_for_platform_permissions_by_service() {
    for relative in ANDROID_APPLICATION_MANIFESTS {
        let manifest = strip_xml_comments(&workspace_source(relative));
        for permission in [
            "android.permission.VIBRATE",
            "android.permission.POST_NOTIFICATIONS",
            "android.permission.CAMERA",
            "android.permission.FOREGROUND_SERVICE",
            "android.permission.SYSTEM_ALERT_WINDOW",
        ] {
            assert!(
                !manifest.contains(permission),
                "{relative} declares {permission}; a Cranpose application asks for the service \
                 that needs it through `cranpose {{ services }}` instead"
            );
        }
    }
}

/// `CranposeBilling` is the one framework class that needs the Play Billing
/// library. It is packaged by the service module that carries the permission,
/// so an application that sells something adds a service name — not a source
/// directory pointing into the framework's tree and a third-party dependency.
#[test]
fn the_framework_packages_its_own_billing_java() {
    let module = workspace_source("android/cranpose-android-billing/build.gradle.kts");
    assert!(
        module.contains("crates/cranpose/android/java-billing"),
        "the billing module must package the framework's billing class"
    );
    assert!(
        module.contains("com.android.billingclient:billing"),
        "the billing module must bring the library that class compiles against"
    );
    for relative in ANDROID_APPLICATION_BUILD_FILES {
        let source = workspace_source(relative);
        assert!(
            !source.contains("java-billing"),
            "{relative} must not point a source set at the framework's billing sources"
        );
    }
}

/// Sharing a file out needs a content provider, because a `file://` URI has
/// been refused since Android 7. The provider is the framework's own class, so
/// the framework's manifest declares it -- an application that shares a file
/// writes nothing, and two Cranpose applications installed together do not
/// collide over one authority.
#[test]
fn the_framework_declares_the_provider_its_own_sharing_needs() {
    let library = workspace_source("android/cranpose-android/src/main/AndroidManifest.xml");
    assert!(
        library.contains("dev.cranpose.android.CranposeShareProvider"),
        "the library manifest must declare the provider that serves shared files"
    );
    assert!(
        library.contains("${applicationId}.cranpose.share"),
        "the share provider authority must be derived from the application id"
    );
    for relative in ANDROID_APPLICATION_MANIFESTS {
        let manifest = strip_xml_comments(&workspace_source(relative));
        assert!(
            !manifest.contains("CranposeShareProvider"),
            "{relative} declares the framework's share provider; the library declares it"
        );
    }
}

/// Installing a downloaded package is a framework capability, and Android
/// refuses the installer session without a permission for it. It rides on its
/// own service module rather than the library, so an application that never
/// updates itself does not ask to install packages.
#[test]
fn installing_an_update_asks_for_its_permission_through_a_service() {
    let module = workspace_source("android/cranpose-android-update/src/main/AndroidManifest.xml");
    assert!(
        module.contains("android.permission.REQUEST_INSTALL_PACKAGES"),
        "the update module must contribute the permission PackageInstaller requires"
    );
    let library = workspace_source("android/cranpose-android/src/main/AndroidManifest.xml");
    assert!(
        !library.contains("REQUEST_INSTALL_PACKAGES"),
        "every Cranpose application would ask to install packages; keep it in the update module"
    );
    for relative in ANDROID_APPLICATION_MANIFESTS {
        let manifest = strip_xml_comments(&workspace_source(relative));
        assert!(
            !manifest.contains("REQUEST_INSTALL_PACKAGES"),
            "{relative} declares REQUEST_INSTALL_PACKAGES; add the `update` service instead"
        );
    }
}

/// The architectures a release carries are stated once, in `releaseAbis`. An
/// application that ships one APK per architecture says only that it does: the
/// plugin writes the same list into the split, so a split can never name an
/// architecture the native build never produced a library for.
#[test]
fn the_plugin_drives_abi_splits_from_the_architectures_it_builds() {
    let plugin = workspace_source(
        "android/cranpose-gradle-plugin/src/main/kotlin/dev/cranpose/gradle/CranposeAndroidPlugin.kt",
    );
    assert!(
        plugin.contains("split.include(*releaseAbis.toTypedArray())"),
        "the plugin must write the release architectures into an enabled ABI split"
    );
    for relative in ANDROID_APPLICATION_BUILD_FILES {
        let source = workspace_source(relative);
        assert!(
            !source.contains("abiFilters"),
            "{relative} sets abiFilters; the plugin constrains packaging to what it builds"
        );
    }
}

/// Every service module the plugin knows how to add must exist and be built, or
/// an application naming it gets a resolution failure instead of a permission.
#[test]
fn every_service_the_plugin_offers_has_a_module() {
    let plugin = workspace_source(
        "android/cranpose-gradle-plugin/src/main/kotlin/dev/cranpose/gradle/CranposeAndroidPlugin.kt",
    );
    let settings = workspace_source("android/settings.gradle.kts");
    let known = plugin
        .split("val KNOWN_SERVICES = setOf(")
        .nth(1)
        .and_then(|rest| rest.split(')').next())
        .expect("the plugin should list the services it knows");
    let services: Vec<&str> = known
        .split(',')
        .map(|entry| entry.trim().trim_matches('"'))
        .filter(|entry| !entry.is_empty())
        .collect();
    assert!(
        services.len() >= 5,
        "the plugin should know several services, found {services:?}"
    );
    for service in services {
        let module = format!("cranpose-android-{service}");
        assert!(
            settings.contains(&format!("include(\":{module}\")")),
            "the plugin offers `{service}` but {module} is not part of the Android build"
        );
        assert!(
            workspace_path(&format!("android/{module}/src/main/AndroidManifest.xml")).is_file(),
            "{module} must contribute a manifest"
        );
    }
}