autumn-cli 0.10.0

CLI tool for the Autumn web framework
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
//! `autumn generate tauri-mobile` — scaffold a Tauri **mobile** wrapper that
//! runs the autumn server in-process (issue #1507, Option B).
//!
//! Mobile sandboxes (iOS and Android) forbid spawning child processes, so the
//! desktop **sidecar model** (`autumn generate tauri`) cannot ship on mobile:
//! there is no `externalBin`, no staging script, and no supervised server
//! binary here. Instead the Autumn Axum server runs on a **background thread
//! inside the app process itself**, spawned from `tauri::Builder::default()
//! .setup(...)` in the generated `src-tauri/src/lib.rs`, and the webview loads
//! the app from `http://127.0.0.1:<port>` once a `/health` poll confirms the
//! server is up. The database is a **remote Postgres** reached over the device
//! network; the template pins conservative pool defaults (small pool, short
//! connect timeout) tuned for flaky mobile networks.
//!
//! Because the server must be callable as a library (routes are registered
//! explicitly in the app's `main()`), the generator also performs an anchored
//! extraction of the stock `src/main.rs` into `src/lib.rs::serve()`, shrinking
//! `main.rs` to a thin caller. When `main.rs` was customised and the anchor no
//! longer matches, the extraction is skipped with a warning pointing at the
//! manual steps in `docs/guide/tauri-mobile-in-process.md`.
//!
//! # `--offline-sync` (issue #1508, Option C)
//!
//! With [`TauriMobileOptions::offline_sync`] the scaffold becomes
//! local-first: app data lives in a `SyncStore`-backed `SQLite` database in
//! the app sandbox (the shell exports its path as `AUTUMN_SYNC__DB_PATH`),
//! a background `SyncEngine` syncs it with the remote deployment's `/sync`
//! endpoints (`AUTUMN_SYNC__REMOTE_URL`; plus an immediate pass on
//! `RunEvent::Resumed`), and the app crate gains a default `offline-sync`
//! feature and a `/sync` router mounted in the extracted `serve()` — only
//! when the app's resolved config has a database URL (e.g.
//! `AUTUMN_DATABASE__URL`), so the same binary boots fully offline on a
//! device and serves sync on the server, and only when `SYNC_TOKEN` is set
//! (fail closed: the mount is wrapped in a generated bearer-token check the
//! device matches via `AUTUMN_SYNC__TOKEN`; without the secret `/sync`
//! stays unmounted instead of open). Without the flag the emitted
//! scaffold is byte-identical to the plain #1507 output.
//! See `docs/guide/tauri-mobile-offline-sync.md`.
//!
//! # Generated files
//!
//! ```text
//! src-tauri/
//!   tauri.conf.json          — Tauri v2 config (no externalBin, no sidecar)
//!   Cargo.toml               — mobile shell crate: staticlib/cdylib/rlib,
//!                               depends on the app crate via path = ".."
//!   build.rs                 — calls tauri_build::build()
//!   src/main.rs              — desktop-dev entry: calls lib::run()
//!   src/lib.rs               — in-process lifecycle: free loopback port, env
//!                               config, server thread, /health poll, webview
//!   icons/*                  — placeholder icons so builds succeed out of the box
//!   .gitignore               — /target /gen
//! src/lib.rs                 — (app crate) extracted `pub async fn serve()`
//! src/main.rs                — (app crate) rewritten as a thin serve() caller
//! ```

use std::path::Path;

use super::emit::Plan;
use super::{GenerateError, ensure_project_root, read_or_empty};

// ── Public API ────────────────────────────────────────────────────────────────

/// Options for [`plan_tauri_mobile`].
#[derive(Debug, Clone, Copy, Default)]
pub struct TauriMobileOptions {
    /// Wire local-first offline storage + background sync (issue #1508):
    /// a `SyncStore`-backed `SQLite` database in the app sandbox, a background
    /// `SyncEngine` against `AUTUMN_SYNC__REMOTE_URL`, and the server-side
    /// `/sync` router in the extracted app crate (feature `offline-sync` on
    /// `autumn-web`).
    pub offline_sync: bool,
}

/// Compute the file actions for `autumn generate tauri-mobile`, honouring
/// `opts` (`--offline-sync`).
///
/// # Errors
/// Returns [`GenerateError::NotInProject`] when not at a project root, or
/// [`GenerateError::Config`] if `Cargo.toml` is missing `[package].name`.
pub fn plan_tauri_mobile(
    project_root: &Path,
    opts: TauriMobileOptions,
) -> Result<Plan, GenerateError> {
    ensure_project_root(project_root)?;

    let AppMeta {
        package_name,
        version: package_version,
        lib_ident,
        lib_src_path,
        has_embed_assets,
    } = read_app_meta(project_root)?;
    let mut plan = Plan::new(project_root);
    let tauri = project_root.join("src-tauri");
    // The shell's own autumn-web dependency (offline sync only) must mirror
    // the app crate's actual dependency SOURCE — version, path, or git — so
    // cargo unifies the two dependency edges into one crate instance (see
    // [`shell_autumn_web_dep`]).
    let autumn_web_dep = opts
        .offline_sync
        .then(|| shell_autumn_web_dep(project_root, &mut plan));

    if !has_embed_assets {
        plan.warn(
            "the app's Cargo.toml declares no `embed-assets` feature — the mobile \
             shell will link the app WITHOUT embedded assets, so static files \
             (CSS, htmx, widgets JS) will 404 on a device. Add \
             `embed-assets = [\"autumn-web/embed-assets\"]` under [features] and \
             re-run with --force (see docs/guide/tauri-mobile-in-process.md)."
                .to_owned(),
        );
    }

    // Core Tauri project files
    plan.create(
        tauri.join("tauri.conf.json"),
        render_mobile_tauri_conf(&package_name, &package_version),
    );
    plan.create(
        tauri.join("Cargo.toml"),
        render_mobile_cargo_toml(&package_name, has_embed_assets, autumn_web_dep.as_ref()),
    );
    plan.create(tauri.join("build.rs"), render_mobile_build_rs());
    plan.create(
        tauri.join("src").join("main.rs"),
        render_mobile_main_rs(&package_name),
    );
    plan.create(
        tauri.join("src").join("lib.rs"),
        render_mobile_lib_rs(&package_name, &lib_ident, opts.offline_sync),
    );

    // Icons — reuse the PWA icon when the user already ran `autumn generate pwa`.
    let icons_dir = tauri.join("icons");
    let pwa_icon_src = project_root.join("static").join("icons").join("icon.svg");
    if pwa_icon_src.is_file() {
        let contents = std::fs::read_to_string(&pwa_icon_src).map_err(GenerateError::Io)?;
        plan.create_if_absent(icons_dir.join("icon.svg"), contents);
    } else {
        plan.create_if_absent(icons_dir.join("icon.svg"), render_placeholder_icon_svg());
    }
    // Placeholder raster icons so `cargo tauri build` works immediately.
    // Replace with proper icons by running: cd src-tauri && cargo tauri icon icons/icon.svg
    plan.create_bytes(icons_dir.join("32x32.png"), PLACEHOLDER_PNG);
    plan.create_bytes(icons_dir.join("128x128.png"), PLACEHOLDER_PNG);
    plan.create_bytes(icons_dir.join("128x128@2x.png"), PLACEHOLDER_PNG);
    plan.create_bytes(icons_dir.join("icon.png"), PLACEHOLDER_PNG);
    plan.create_bytes(icons_dir.join("icon.ico"), PLACEHOLDER_ICO);
    plan.create_bytes(icons_dir.join("icon.icns"), PLACEHOLDER_ICNS);

    plan.create(tauri.join(".gitignore"), render_mobile_gitignore());

    // App-crate lib extraction so the shell can call `<app_lib>::serve()`
    // in-process.
    plan_lib_extraction(
        project_root,
        &lib_ident,
        &lib_src_path,
        opts.offline_sync,
        &mut plan,
    );

    // App-crate offline-sync feature (Cargo.toml edit, offline sync only).
    if opts.offline_sync {
        plan_app_offline_sync_feature(project_root, &mut plan);
    }

    Ok(plan)
}

// ── Mixed-mode guard (mirrors generate/tauri.rs, issue #1506) ─────────────────

/// Refuse to scaffold the mobile in-process shell on top of another Tauri
/// mode's `src-tauri/`.
///
/// `autumn generate tauri` (desktop sidecar), `autumn generate tauri
/// --remote-url` (mobile thin client), and `autumn generate tauri-mobile`
/// (mobile in-process) all write to `src-tauri/`, but their file sets only
/// partially overlap — `--force` would overwrite the shared files and leave
/// the other mode's leftovers behind, some of which actively break the
/// mobile build: Tauri CLI merges stale desktop `tauri.<platform>.conf.json`
/// overlays on top of `tauri.conf.json` (re-running the sidecar staging
/// scripts), and loads every capability file under `src-tauri/capabilities/`
/// (stale thin-client grants fail `tauri-build` validation against the
/// in-process shell crate, which compiles none of those plugins). `--force`
/// means "overwrite within the same mode", never "silently mix modes", so
/// this check runs regardless of `--force`.
///
/// Called only for `autumn generate` — never for `autumn destroy`, which is
/// the documented remedy and must keep working on a mixed tree.
///
/// # Errors
/// Returns [`GenerateError::Config`] naming the conflicting marker file and
/// the matching `autumn destroy tauri [--remote-url <URL>]` command to run
/// first.
pub fn ensure_no_other_mode_scaffold(project_root: &Path) -> Result<(), GenerateError> {
    let tauri = project_root.join("src-tauri");
    let first_existing = |markers: &[&str]| -> Option<String> {
        markers
            .iter()
            .find(|m| tauri.join(m).is_file())
            .map(|m| format!("src-tauri/{m}"))
    };
    if let Some(marker) = first_existing(&super::tauri::DESKTOP_MARKERS) {
        return Err(GenerateError::Config(format!(
            "src-tauri/ already contains a desktop (sidecar) Tauri scaffold \
             ({marker} exists); refusing to scaffold the mobile in-process \
             shell on top of it — stale per-OS tauri.*.conf.json overlays \
             would keep running the sidecar staging scripts on every `cargo \
             tauri build`. Run `autumn destroy tauri` first, then re-run \
             `autumn generate tauri-mobile`. --force only overwrites files \
             within the same mode; it never mixes modes."
        )));
    }
    if let Some(marker) = first_existing(&super::tauri::THIN_CLIENT_MARKERS) {
        return Err(GenerateError::Config(format!(
            "src-tauri/ already contains a mobile thin-client Tauri scaffold \
             ({marker} exists); refusing to scaffold the mobile in-process \
             shell on top of it — Tauri loads every capability file under \
             src-tauri/capabilities/, so the stale thin-client grants would \
             fail validation against the in-process shell crate. Run `autumn \
             destroy tauri --remote-url <URL>` (the URL the thin client was \
             generated with) first, then re-run `autumn generate \
             tauri-mobile`. --force only overwrites files within the same \
             mode; it never mixes modes."
        )));
    }
    Ok(())
}

/// Human-readable prerequisites message printed after a successful scaffold,
/// honouring `opts` (`--offline-sync` swaps the remote-connection step).
pub fn render_mobile_prerequisites(opts: TauriMobileOptions) -> String {
    // Step 3 is where the app meets the network: a direct remote-Postgres
    // connection by default, the background sync engine under --offline-sync
    // (where the device needs no database connection at all).
    let connect_step = if opts.offline_sync {
        "3. Point the background sync engine at your remote deployment:\n\
         edit src-tauri/src/lib.rs and set AUTUMN_SYNC__REMOTE_URL to the\n\
         /sync mount of your deployed app (see the commented block in run()).\n\
         Deploy the SAME app with AUTUMN_DATABASE__URL set so it serves the\n\
         /sync endpoints. They are mounted FAIL CLOSED: set SYNC_TOKEN on the\n\
         deployment (a long random secret) and deliver the same secret to\n\
         devices as AUTUMN_SYNC__TOKEN, or /sync stays unmounted. The\n\
         device itself needs no database connection; read\n\
         docs/guide/tauri-mobile-offline-sync.md for the offline walkthrough.\n"
    } else {
        "3. Point the app at your remote Postgres database:\n\
         edit src-tauri/src/lib.rs and set AUTUMN_DATABASE__URL (see the\n\
         commented example in run()).\n"
    };
    format!(
        "\
Required prerequisites for building the mobile app:\n\
\n\
  1. Tauri CLI:\n\
       cargo install tauri-cli --version '^2'\n\
\n\
  2. Mobile toolchain:\n\
       iOS:     Xcode + iOS simulators (macOS only), then:\n\
                  cd src-tauri && cargo tauri ios init\n\
       Android: Android Studio / SDK + NDK (set ANDROID_HOME, NDK_HOME), then:\n\
                  cd src-tauri && cargo tauri android init\n\
\n\
{connect_step}\
\n\
  4. Develop or build:\n\
       cd src-tauri && cargo tauri ios dev        (or: cargo tauri ios build)\n\
       cd src-tauri && cargo tauri android dev    (or: cargo tauri android build)\n\
       Note: Android release builds block cleartext HTTP (incl. 127.0.0.1) by\n\
       default — permit loopback via a network_security_config.xml (see the\n\
       docs page below).\n\
\n\
  The server runs IN-PROCESS on a background thread — mobile sandboxes forbid\n\
  sidecar processes, so this scaffold intentionally has no externalBin and no\n\
  staging scripts.  Read docs/guide/tauri-mobile-in-process.md for mobile\n\
  sandboxing restrictions, remote-Postgres pool tuning for flaky networks,\n\
  security notes, and App Store guideline compliance notes.\n\
\n\
  Replace the placeholder icons before shipping:\n\
       cd src-tauri && cargo tauri icon icons/icon.svg\n"
    )
}

// ── Package metadata helper ───────────────────────────────────────────────────

/// App-crate metadata the mobile generator needs from `Cargo.toml`.
struct AppMeta {
    /// `[package].name`, verbatim — used for the shell crate name, the bundle
    /// identifier, the display title, and the path-dependency key.
    package_name: String,
    /// `[package].version`, with workspace inheritance resolved.
    version: String,
    /// The **library crate identifier** all generated `serve()` call sites
    /// use: `[lib].name` when the app sets one, otherwise `[package].name`
    /// with dashes replaced by underscores (Cargo's default lib target name).
    lib_ident: String,
    /// The **library target source file**, relative to the project root:
    /// `[lib].path` when the app sets one, otherwise `src/lib.rs` (Cargo's
    /// default). The `serve()` extraction must target this file — a newly
    /// created `src/lib.rs` would be ignored by Cargo when `[lib].path`
    /// points elsewhere.
    lib_src_path: String,
    /// Whether the app declares an `embed-assets` feature.
    has_embed_assets: bool,
}

/// Reads [`AppMeta`] from the app's `Cargo.toml`.
///
/// A deliberately small, self-contained reader: the mobile shell has no
/// sidecar, so — unlike the desktop generator — it needs no binary-target or
/// dependency-key resolution. `version` resolves workspace inheritance
/// (`version.workspace = true`) against the app's effective workspace root.
/// `lib_ident` honors a custom `[lib] name = "…"`: Cargo exposes the library
/// crate to the app binary and to path dependents under that name, so the
/// generated `<lib_ident>::serve()` calls must use it — the dash-to-underscore
/// package name would not compile for those projects. `lib_src_path` honors a
/// custom `[lib] path = "…"` the same way: Cargo compiles THAT file as the
/// library target and ignores a stray `src/lib.rs`.
/// `has_embed_assets` is `true` when the app declares an `embed-assets`
/// feature (the stock scaffold always does) — the mobile shell enables it on
/// the app dependency so CSS/JS/static assets are compiled into the binary
/// (a mobile app has no working directory to serve `static/` from).
fn read_app_meta(project_root: &Path) -> Result<AppMeta, GenerateError> {
    let cargo_path = project_root.join("Cargo.toml");
    let content = std::fs::read_to_string(&cargo_path).map_err(GenerateError::Io)?;
    let doc: toml::Value = toml::from_str(&content)
        .map_err(|e| GenerateError::Config(format!("failed to parse Cargo.toml: {e}")))?;
    let pkg = doc
        .get("package")
        .ok_or_else(|| GenerateError::Config("Cargo.toml missing [package].name".to_owned()))?;
    let name = pkg
        .get("name")
        .and_then(|n| n.as_str())
        .map(str::to_owned)
        .ok_or_else(|| GenerateError::Config("Cargo.toml missing [package].name".to_owned()))?;

    let version = match pkg.get("version") {
        Some(toml::Value::String(s)) => s.clone(),
        Some(toml::Value::Table(t))
            if t.get("workspace").and_then(toml::Value::as_bool) == Some(true) =>
        {
            resolve_workspace_version(project_root).unwrap_or_else(|| "0.1.0".to_owned())
        }
        _ => "0.1.0".to_owned(),
    };

    let has_embed_assets = doc
        .get("features")
        .and_then(|f| f.get("embed-assets"))
        .is_some();

    let lib_ident = doc
        .get("lib")
        .and_then(|l| l.get("name"))
        .and_then(|n| n.as_str())
        .map_or_else(|| name.replace('-', "_"), str::to_owned);

    let lib_src_path = doc
        .get("lib")
        .and_then(|l| l.get("path"))
        .and_then(|p| p.as_str())
        .map_or_else(|| "src/lib.rs".to_owned(), str::to_owned);

    Ok(AppMeta {
        package_name: name,
        version,
        lib_ident,
        lib_src_path,
        has_embed_assets,
    })
}

/// The `[workspace.package] version` of the app's EFFECTIVE workspace root
/// — the member's own `[workspace]`, the target of an explicit
/// `[package] workspace = "…"` pointer, or the nearest non-excluding
/// ancestor (the same single root resolution the dependency-value,
/// dep-key, and patch lookups use, so all the walks agree). An
/// ancestor-only walk would miss a pointer target that is not an ancestor
/// and silently fall back to "0.1.0" — stamping the generated
/// tauri.conf.json (the mobile BUNDLE version) with the wrong release
/// number and breaking upgrade/store flows. Returns `None` when the root
/// declares no `[workspace.package] version`.
fn resolve_workspace_version(project_root: &Path) -> Option<String> {
    let root = effective_workspace_root(project_root);
    let content = std::fs::read_to_string(root.join("Cargo.toml")).ok()?;
    let doc = toml::from_str::<toml::Value>(&content).ok()?;
    doc.get("workspace")?
        .get("package")?
        .get("version")?
        .as_str()
        .map(str::to_owned)
}

/// The shell's own `autumn-web` dependency (offline sync only), mirroring
/// the app crate's **actual** dependency source.
///
/// The shell manifest declares its own `[workspace]`, so it inherits neither
/// the app's `[patch.crates-io]` overrides nor a parent workspace's
/// dependency table. A registry-only `autumn-web = { version = … }` edge
/// would therefore compile the shell against a DIFFERENT framework source
/// than the app for path/git/workspace-dep users — or fail outright while
/// the `offline-sync` feature is not published on crates.io. This struct
/// carries the mirrored edge (and, for patched registry deps, a mirrored
/// `[patch.crates-io]` section).
struct ShellAutumnWebDep {
    /// The full `autumn-web = { … }` line for the shell's `[dependencies]`.
    dep_entry: String,
    /// A mirrored `[patch.crates-io]` section (trailing part of the
    /// manifest), when the app's manifest — or an ancestor workspace root —
    /// patches `autumn-web` with a path/git override.
    patch_entry: Option<String>,
}

/// Lexically compute `target` relative to `dir` — no filesystem access, so
/// neither path needs to exist. `.`/`..` components are folded first;
/// returns `None` when the paths cannot be lexically related (different
/// roots/prefixes, or a `..` chain that escapes them).
fn lexical_relative(target: &Path, dir: &Path) -> Option<std::path::PathBuf> {
    use std::path::Component;
    fn normalize(p: &Path) -> Option<Vec<Component<'_>>> {
        let mut out: Vec<Component<'_>> = Vec::new();
        for component in p.components() {
            match component {
                Component::CurDir => {}
                Component::ParentDir => match out.last() {
                    Some(Component::Normal(_)) => {
                        out.pop();
                    }
                    // `..` above the root (or of a bare relative path)
                    // cannot be folded lexically.
                    _ => return None,
                },
                other => out.push(other),
            }
        }
        Some(out)
    }
    let target = normalize(target)?;
    let dir = normalize(dir)?;
    // Roots/prefixes must match for a relative walk to exist at all.
    if target.first() != dir.first() {
        return None;
    }
    let common = target
        .iter()
        .zip(dir.iter())
        .take_while(|(a, b)| a == b)
        .count();
    let mut relative = std::path::PathBuf::new();
    for _ in common..dir.len() {
        relative.push("..");
    }
    for component in &target[common..] {
        relative.push(component.as_os_str());
    }
    if relative.as_os_str().is_empty() {
        relative.push(".");
    }
    Some(relative)
}

/// Render the `path = "…"` or `git = "…"[, rev/branch/tag = "…"]` source part
/// of a dependency (or patch) table, adjusted so it stays valid when written
/// into `src-tauri/Cargo.toml`:
///
/// - ROOTED paths the USER wrote are kept as-is — they never resolve
///   relative to a manifest directory, so re-anchoring them would change
///   their meaning. Rooted is deliberately [`Path::has_root`], not
///   `is_absolute`: on Windows a Unix-style `/src/framework` path has a
///   root but no drive prefix, so `is_absolute` returns false there and
///   the path would fall into the relative branches below and come out
///   mangled (`..//src/framework`) — the same manifest must produce the
///   same shell edge on every platform,
/// - paths relative to the app's own manifest gain a `../` prefix
///   (`src-tauri/` sits one level below the project root),
/// - paths declared in an ancestor manifest (workspace root) are resolved
///   against that manifest's directory and then re-relativized against the
///   generated `src-tauri/` — `src-tauri/Cargo.toml` is a CHECKED-IN file,
///   so baking the generating machine's absolute path into it would break
///   every other checkout (teammates, CI); the absolute form is only a
///   fallback when no lexical relative path exists.
///
/// Emitted paths always use forward slashes (valid on Windows too, and the
/// generator's convention). Returns `None` when the table names neither a
/// path nor a git source.
fn dep_source_from_table(
    table: &toml::value::Table,
    manifest_dir: &Path,
    project_root: &Path,
) -> Option<String> {
    if let Some(path) = table.get("path").and_then(toml::Value::as_str) {
        let adjusted = if Path::new(path).has_root() {
            path.replace('\\', "/")
        } else if manifest_dir == project_root {
            // Same backslash normalization as the other branches: a
            // Windows-separated relative path written into the app's
            // manifest would otherwise land in src-tauri/Cargo.toml as an
            // invalid TOML basic-string escape (`\a`, `\v`) — or, where it
            // happens to escape cleanly, as a checked-in platform-specific
            // path.
            format!("../{}", path.replace('\\', "/"))
        } else {
            let target = manifest_dir.join(path);
            let src_tauri = project_root.join("src-tauri");
            lexical_relative(&target, &src_tauri)
                .unwrap_or(target)
                .display()
                .to_string()
                .replace('\\', "/")
        };
        return Some(format!("path = \"{adjusted}\""));
    }
    if let Some(git) = table.get("git").and_then(toml::Value::as_str) {
        use std::fmt::Write as _;
        let mut source = format!("git = \"{git}\"");
        for key in ["rev", "branch", "tag"] {
            if let Some(v) = table.get(key).and_then(toml::Value::as_str) {
                let _ = write!(source, ", {key} = \"{v}\"");
            }
        }
        return Some(source);
    }
    None
}

/// A dependency table's explicit `default-features` setting, honoring the
/// pre-2021 `default_features` spelling cargo still accepts. `None` when the
/// table doesn't set it.
fn table_default_features(table: &toml::value::Table) -> Option<bool> {
    ["default-features", "default_features"]
        .iter()
        .find_map(|key| table.get(*key).and_then(toml::Value::as_bool))
}

/// Resolve the app's `autumn-web` dependency VALUE, following
/// `workspace = true` inheritance to the `[workspace.dependencies]` table of
/// the app's EFFECTIVE workspace root. Returns the value, the
/// directory of the manifest that declared it (relative `path` sources
/// resolve against that directory), and — for workspace-inherited deps — the
/// MEMBER-level `default-features` setting, which the resolved workspace
/// table would otherwise erase (Cargo lets the member re-enable defaults a
/// workspace entry disabled, so the member-level value must survive
/// resolution).
fn resolve_app_autumn_web_value(
    project_root: &Path,
) -> (Option<toml::Value>, std::path::PathBuf, Option<bool>) {
    let parse = |dir: &Path| -> Option<toml::Value> {
        toml::from_str(&read_or_empty(&dir.join("Cargo.toml"))).ok()
    };
    let doc = parse(project_root);
    // Resolve by PACKAGE, not by key: apps may rename the dependency
    // (`autumn = { package = "autumn-web", ... }`), and a hard-coded
    // `autumn-web` lookup would miss it (same convention as the desktop
    // generator's `resolve_dep_key`).
    let dep_key = doc.as_ref().map_or_else(
        || "autumn-web".to_owned(),
        |d| super::tauri::resolve_dep_key(project_root, d, "autumn-web"),
    );
    let dep = doc
        .as_ref()
        .and_then(|d| d.get("dependencies")?.get(&dep_key))
        .cloned();
    if let Some(toml::Value::Table(t)) = &dep
        && t.get("workspace").and_then(toml::Value::as_bool) == Some(true)
    {
        // Capture the member-level default-features BEFORE the member table
        // is replaced by the workspace entry.
        let member_default_features = table_default_features(t);
        // Workspace-inherited: Cargo resolves `workspace = true` against
        // the [workspace.dependencies] table of exactly ONE manifest — the
        // app's EFFECTIVE workspace root (the member's own [workspace],
        // the target of an explicit `package.workspace = "…"` pointer, or
        // the nearest non-excluding ancestor root). Reuse the same root
        // resolution the [patch.crates-io] mirroring uses, so both walks
        // agree: a plain ancestor scan would never find a pointer target
        // that is not an ancestor, and — worse — could stop at a NEARER
        // manifest's [workspace.dependencies] entry that a pointer
        // deliberately skips past, mirroring a framework source the app
        // never builds against.
        let root = effective_workspace_root(project_root);
        if let Some(v) = parse(&root)
            .as_ref()
            .and_then(|doc| doc.get("workspace")?.get("dependencies")?.get(&dep_key))
            .cloned()
        {
            // Relative `path` sources in the returned value resolve
            // against the ROOT manifest's directory — the caller's
            // re-relativization (dep_source_from_table) computes from it,
            // and lexical_relative folds any `..` a pointer target
            // carries.
            return (Some(v), root, member_default_features);
        }
        return (None, project_root.to_path_buf(), member_default_features);
    }
    (dep, project_root.to_path_buf(), None)
}

/// Find a `[patch.crates-io]` override of the `autumn-web` PACKAGE — the
/// literal `autumn-web` key or a renamed entry
/// (`autumn_web_local = { package = "autumn-web", … }`) — in the app's
/// manifest or the nearest ancestor's (patches only apply from a workspace
/// root, but the app may be a workspace member). Returns the mirrored
/// `[patch.crates-io]` section for the shell manifest (entry key and
/// `package` rename preserved), warning when a patch exists but cannot be
/// represented.
fn mirror_autumn_web_patch(project_root: &Path, plan: &mut Plan) -> Option<String> {
    // Cargo only honors the [patch] tables of the EFFECTIVE workspace root
    // (member-local [patch] tables are ignored, with a cargo warning), so
    // mirror exclusively from that manifest: copying a member-local patch
    // would make the shell compile a framework checkout the app itself
    // never uses.
    let root = effective_workspace_root(project_root);

    // A member-local framework patch is skipped — tell the user why, since
    // "my patch wasn't mirrored" is otherwise mystifying.
    if root != project_root && autumn_web_patch_entry(project_root).is_some() {
        plan.warn(format!(
            "Cargo ignores [patch] tables outside the workspace root, so the \
             [patch.crates-io] override of autumn-web in the app's own \
             Cargo.toml was NOT mirrored into src-tauri/Cargo.toml (only the \
             patch table of {} applies). Move the patch to the workspace \
             root if the app should build against it.",
            root.join("Cargo.toml").display(),
        ));
    }

    let (key, value) = autumn_web_patch_entry(&root)?;
    let table = value.as_table();
    let source = table.and_then(|t| dep_source_from_table(t, &root, project_root));
    let Some(source) = source else {
        plan.warn(
            "the app's [patch.crates-io] override of autumn-web could not \
             be mirrored into src-tauri/Cargo.toml (only path and git \
             patches are supported). The shell declares its own \
             [workspace], so the app's patch does NOT apply there — copy \
             your [patch.crates-io] section into src-tauri/Cargo.toml \
             yourself or the shell will build against the crates.io \
             registry version of autumn-web."
                .to_owned(),
        );
        return None;
    };
    // Mirror the whole entry: original key plus its `package` rename, so
    // the emitted section patches exactly what the root's does.
    let package_part = table
        .and_then(|t| t.get("package"))
        .and_then(toml::Value::as_str)
        .map_or_else(String::new, |package| format!("package = \"{package}\", "));
    Some(format!(
        "\n[patch.crates-io]\n\
         # Mirrors the app's [patch.crates-io] override of autumn-web: the shell\n\
         # declares its own [workspace], so the app's patch would otherwise NOT\n\
         # apply here and the shell would compile a different framework source.\n\
         {key} = {{ {package_part}{source} }}\n"
    ))
}

/// The `[patch.crates-io]` entry of `dir`'s manifest that patches the
/// `autumn-web` PACKAGE — matched by effective package, not by key: a
/// renamed patch (`autumn_web_local = { package = "autumn-web", … }`) is
/// just as valid as the literal `autumn-web` key, and skipping it would
/// leave the shell on the crates.io registry while the app builds the
/// patched source (same resolve-by-package convention as the dependency
/// lookup).
fn autumn_web_patch_entry(dir: &Path) -> Option<(String, toml::Value)> {
    toml::from_str::<toml::Value>(&read_or_empty(&dir.join("Cargo.toml")))
        .ok()
        .as_ref()
        .and_then(|doc| doc.get("patch")?.get("crates-io")?.as_table())
        .and_then(|table| {
            table.iter().find(|(key, value)| {
                key.as_str() == "autumn-web"
                    || value
                        .as_table()
                        .and_then(|t| t.get("package"))
                        .and_then(toml::Value::as_str)
                        == Some("autumn-web")
            })
        })
        .map(|(key, value)| (key.clone(), value.clone()))
}

/// The app's EFFECTIVE workspace root: the single manifest directory whose
/// `[patch]` tables Cargo honors and whose `[workspace.dependencies]` table
/// `workspace = true` inheritance resolves against (shared by the patch
/// mirroring, the dependency-value resolution, and the desktop generator's
/// renamed-dep key lookup, so all the walks agree). For the app at
/// `project_root` this is:
///
/// - the app itself when its manifest declares `[workspace]` (own root) or
///   no enclosing workspace exists (standalone),
/// - the target of an explicit `package.workspace = "…"` pointer,
/// - otherwise the nearest ancestor manifest declaring `[workspace]` whose
///   `workspace.exclude` does NOT cover the app's directory (exact relative
///   path OR any ancestor directory of it, matched by whole path
///   components — Cargo treats exclude entries as directory prefixes, so
///   `exclude = ["examples"]` excludes `examples/mobile` but never
///   `examples-extra/mobile`; glob patterns are not expanded — the cheap
///   rule). An EXCLUDING ancestor does not stop the walk: exclusion at one
///   level only removes the app from THAT workspace, not from an outer
///   workspace's membership, so the walk continues upward (Cargo reports
///   the outer root as `workspace_root` for e.g. repo-root
///   `members = ["mid/app"]` with `mid` excluding `app`). Only when no
///   non-excluding ancestor root exists is the app standalone.
///
/// Full `members` glob verification is deliberately skipped: a nearest
/// ancestor root that does not include the member is a broken workspace
/// Cargo itself rejects.
pub fn effective_workspace_root(project_root: &Path) -> std::path::PathBuf {
    let parse = |dir: &Path| -> Option<toml::Value> {
        toml::from_str(&read_or_empty(&dir.join("Cargo.toml"))).ok()
    };
    let doc = parse(project_root);
    if doc.as_ref().is_some_and(|d| d.get("workspace").is_some()) {
        return project_root.to_path_buf();
    }
    if let Some(pointer) = doc
        .as_ref()
        .and_then(|d| d.get("package")?.get("workspace"))
        .and_then(toml::Value::as_str)
    {
        return project_root.join(pointer);
    }
    let mut dir = project_root.parent();
    while let Some(d) = dir {
        if let Some(workspace) = parse(d)
            .as_ref()
            .and_then(|doc| doc.get("workspace").cloned())
        {
            let excluded = workspace
                .get("exclude")
                .and_then(toml::Value::as_array)
                .is_some_and(|entries| {
                    // Cargo treats exclude entries as DIRECTORY PREFIXES: a
                    // package anywhere under an excluded dir is excluded
                    // (root `exclude = ["examples"]` excludes
                    // examples/mobile). `Path::starts_with` compares whole
                    // components, so "examples" matches examples/mobile but
                    // never examples-extra/mobile. Glob patterns are still
                    // not expanded (the sanctioned cheap rule) — a literal
                    // component comparison simply never matches them.
                    let relative = lexical_relative(project_root, d);
                    entries.iter().filter_map(toml::Value::as_str).any(|entry| {
                        relative
                            .as_deref()
                            .is_some_and(|relative| relative.starts_with(Path::new(entry)))
                    })
                });
            if !excluded {
                return d.to_path_buf();
            }
            // An excluding ancestor doesn't make the app standalone:
            // exclusion only removes the app from THIS workspace, not from
            // an outer workspace's membership. Keep walking — an outer root
            // (e.g. repo root with `members = ["mid/app"]` while `mid`
            // excludes `app`) is the one Cargo binds the app to.
        }
        dir = d.parent();
    }
    project_root.to_path_buf()
}

/// Compute the shell's `autumn-web` dependency (offline sync only), mirroring
/// the app crate's actual dependency source — see [`ShellAutumnWebDep`]:
///
/// - **path/git deps** (direct or workspace-inherited) are copied onto the
///   shell edge, with relative paths recomputed for `src-tauri/`,
/// - **registry (version) deps** keep the app's version requirement, plus a
///   mirrored `[patch.crates-io]` section when the app patches `autumn-web`,
/// - anything unrepresentable falls back to this CLI's version (the value
///   `autumn new` scaffolds) with a loud warning telling the user to edit
///   the shell manifest by hand.
fn shell_autumn_web_dep(project_root: &Path, plan: &mut Plan) -> ShellAutumnWebDep {
    let (dep_value, manifest_dir, member_default_features) =
        resolve_app_autumn_web_value(project_root);

    // `default-features = false` must survive the mirroring: cargo unifies
    // features per dependency EDGE, so a shell edge without it would
    // re-enable the framework's default features across the whole src-tauri
    // build even though the app opted out. For workspace-inherited deps the
    // MEMBER-level setting wins when present — that mirrors Cargo's
    // re-enable rule (member `default-features = true` over a workspace
    // `false`); for member `false` over workspace defaults-on Cargo today
    // IGNORES the member key with a warning slated to become a hard error,
    // and we honor the written opt-out instead — harmless either way, since
    // the app's own edge still carries the workspace value and cargo
    // unifies the edges by union. Otherwise the resolved (workspace or
    // direct) table's setting applies.
    let resolved_default_features = match &dep_value {
        Some(toml::Value::Table(t)) => table_default_features(t),
        _ => None,
    };
    // With defaults off, `offline-sync` needs a backend (#2605). Name
    // `postgres`, as `db` did before.
    let (default_features_part, shell_features) =
        if member_default_features.or(resolved_default_features) == Some(false) {
            (
                "default-features = false, ",
                r#""offline-sync", "postgres""#,
            )
        } else {
            ("", r#""offline-sync""#)
        };

    // Path/git sources are mirrored directly onto the shell's edge.
    if let Some(toml::Value::Table(t)) = &dep_value
        && let Some(source) = dep_source_from_table(t, &manifest_dir, project_root)
    {
        let version_part = t
            .get("version")
            .and_then(toml::Value::as_str)
            .map_or_else(String::new, |v| format!("version = \"{v}\", "));
        return ShellAutumnWebDep {
            dep_entry: format!(
                "autumn-web = {{ {version_part}{source}, \
                 {default_features_part}features = [{shell_features}] }}"
            ),
            patch_entry: None,
        };
    }

    // Registry requirement: keep the app's version and mirror any
    // [patch.crates-io] override of autumn-web into the shell manifest.
    let version = match &dep_value {
        Some(toml::Value::String(s)) => Some(s.clone()),
        Some(toml::Value::Table(t)) => t
            .get("version")
            .and_then(toml::Value::as_str)
            .map(str::to_owned),
        _ => None,
    };
    // An alternate-registry selection must survive the mirroring too: a
    // bare version requirement would make the shell workspace resolve
    // autumn-web from crates.io — failing outright for private registries,
    // or silently compiling a different framework. `registry` only combines
    // with version deps (Cargo rejects it on path/git sources, and member
    // manifests cannot override it on workspace-inherited entries), so
    // reading it from the RESOLVED table covers both direct and
    // workspace-inherited shapes.
    let registry_part = match &dep_value {
        Some(toml::Value::Table(t)) => t
            .get("registry")
            .and_then(toml::Value::as_str)
            .map_or_else(String::new, |registry| {
                format!("registry = \"{registry}\", ")
            }),
        _ => String::new(),
    };
    let registry_entry = |req: &str| {
        format!(
            "autumn-web = {{ version = \"{req}\", \
             {registry_part}{default_features_part}features = [{shell_features}] }}"
        )
    };
    let Some(version) = version else {
        plan.warn(format!(
            "could not determine the app's autumn-web dependency source — the \
             shell's src-tauri/Cargo.toml falls back to the crates.io registry \
             (autumn-web = \"{}\"), which may be a DIFFERENT framework source \
             than the app builds against (and may lack the offline-sync \
             feature). Edit the autumn-web entry in src-tauri/Cargo.toml to \
             match your app's source — path, git, or version (see \
             docs/guide/tauri-mobile-offline-sync.md).",
            env!("CARGO_PKG_VERSION"),
        ));
        return ShellAutumnWebDep {
            dep_entry: registry_entry(env!("CARGO_PKG_VERSION")),
            patch_entry: None,
        };
    };
    let patch_entry = mirror_autumn_web_patch(project_root, plan);
    ShellAutumnWebDep {
        dep_entry: registry_entry(&version),
        patch_entry,
    }
}

// ── App-crate offline-sync feature (Cargo.toml edit) ──────────────────────────

/// Plan the app-crate `Cargo.toml` edit for `--offline-sync`: declare
/// `offline-sync = ["autumn-web/offline-sync"]` and put it in the `default`
/// feature set, so a plain `cargo run` server deployment of the same app
/// mounts the `/sync` endpoints the device syncs against.
///
/// Anchored + idempotent, following the `plan_lib_extraction` discipline: a
/// manifest that already declares the feature is left untouched (silent
/// `--force` re-runs), and a customised manifest gets a warning with the
/// manual steps instead of a guessed edit. Like the `main.rs` extraction,
/// this is an [`super::emit::Action::Modify`] that `autumn destroy` never
/// reverses — the extracted `serve()` keeps compiling either way (its sync
/// code is gated on the feature).
/// The app's own `[features]` reachable from `start` by following
/// own-crate feature edges (`start` itself included). Entries containing
/// `/` or `:` are dependency features (`dep/feat`, `dep?/feat`,
/// `dep:name`) — they cannot enable an own-crate feature, so they are
/// never followed. This one walk backs BOTH feature checks below
/// (default-enablement and dep-propagation), so the two can never
/// diverge on graph semantics.
fn reachable_own_features(
    features: &toml::value::Table,
    start: &str,
) -> std::collections::HashSet<String> {
    let mut visited = std::collections::HashSet::new();
    let mut stack = vec![start.to_owned()];
    while let Some(name) = stack.pop() {
        if !visited.insert(name.clone()) {
            continue;
        }
        if let Some(entries) = features.get(&name).and_then(toml::Value::as_array) {
            for entry in entries.iter().filter_map(toml::Value::as_str) {
                if !entry.contains('/') && !entry.contains(':') {
                    stack.push(entry.to_owned());
                }
            }
        }
    }
    visited
}

/// Whether the manifest's `default` feature set enables `offline-sync`,
/// directly or transitively through other features of THIS crate.
fn offline_sync_enabled_by_default(features: &toml::value::Table) -> bool {
    features.contains_key("offline-sync")
        && reachable_own_features(features, "default").contains("offline-sync")
}

/// Whether the app's existing `offline-sync` feature actually enables the
/// framework's feature on the `dep_key` dependency edge — a
/// `{dep_key}/offline-sync` (or weak `{dep_key}?/offline-sync`) entry,
/// directly or transitively through other own-crate features.
///
/// This matters because the extracted `serve()` compiles its sync code under
/// `#[cfg(feature = "offline-sync")]` while the code it calls
/// (`autumn_web::sync`) only exists when the DEPENDENCY's feature is on: a
/// declaration like `offline-sync = []` satisfies the cfg but leaves the
/// dependency compiled without its sync module — a guaranteed build
/// failure.
fn offline_sync_feature_propagates(features: &toml::value::Table, dep_key: &str) -> bool {
    let strong = format!("{dep_key}/offline-sync");
    let weak = format!("{dep_key}?/offline-sync");
    reachable_own_features(features, "offline-sync")
        .iter()
        .any(|name| {
            features
                .get(name)
                .and_then(toml::Value::as_array)
                .is_some_and(|entries| {
                    entries
                        .iter()
                        .filter_map(toml::Value::as_str)
                        .any(|entry| entry == strong || entry == weak)
                })
        })
}

#[allow(clippy::too_many_lines)] // one linear anchored-edit policy, clearest unsplit
fn plan_app_offline_sync_feature(project_root: &Path, plan: &mut Plan) {
    const FEATURES_ANCHOR: &str = "[features]\n";
    const DEFAULT_ANCHOR: &str = "default = [\"flash\"]\n";

    let cargo_path = project_root.join("Cargo.toml");
    let content = read_or_empty(&cargo_path);
    let doc = toml::from_str::<toml::Value>(&content).ok();
    // Cargo feature syntax names the DEPENDENCY KEY, not the package: a
    // renamed dep (`autumn = { package = "autumn-web", ... }`) must be
    // referenced as `autumn/offline-sync` — `autumn-web/offline-sync` would
    // be rejected by cargo as an unknown dependency.
    let dep_key = doc.as_ref().map_or_else(
        || "autumn-web".to_owned(),
        |doc| super::tauri::resolve_dep_key(project_root, doc, "autumn-web"),
    );
    let feature_line = format!("offline-sync = [\"{dep_key}/offline-sync\"]\n");
    // Detect an existing feature via the PARSED [features] table (the same
    // source of truth the graph checks below read), never a
    // substring scan: `offline-sync=[]` (no spaces) or a multiline array
    // would slip past a textual `"offline-sync = ["` check into the
    // fresh-insert branch below, which would then write a DUPLICATE
    // `offline-sync` key under [features] — a manifest cargo rejects.
    let features = doc
        .as_ref()
        .and_then(|doc| doc.get("features"))
        .and_then(toml::Value::as_table);
    if let Some(features) = features.filter(|f| f.contains_key("offline-sync")) {
        // The feature exists — but "wired" requires two more things, each
        // patched with the same anchored discipline as the fresh edit
        // (byte-precise anchor or a loud warning, never a guessed rewrite
        // of a customised manifest):
        //
        // 1. It must PROPAGATE to the dependency — include
        //    `{dep_key}/offline-sync`, directly or transitively through
        //    other own-crate features. serve()'s sync code compiles under
        //    #[cfg(feature = "offline-sync")] but calls autumn_web::sync,
        //    which only exists when the DEPENDENCY's feature is on, so a
        //    non-propagating declaration (e.g. `offline-sync = []`) is a
        //    guaranteed build failure.
        // 2. `default` must enable it: the extracted serve() mounts /sync
        //    behind the cfg, and the documented flow assumes a plain
        //    `cargo run` deployment serves those endpoints. A defined but
        //    non-default feature would ship a mobile client whose server
        //    never mounts /sync.
        let mut edited = content;
        let mut changed = false;
        let default_ok = offline_sync_enabled_by_default(features);
        let propagation_ok = if offline_sync_feature_propagates(features, &dep_key) {
            true
        } else {
            // The one unambiguous anchored shape: an EMPTY declaration
            // gains exactly the dep entry. Any other non-propagating array
            // is a customised feature we refuse to guess at.
            const EMPTY_DECL: &str = "offline-sync = []\n";
            if edited.contains(EMPTY_DECL) {
                edited = edited.replacen(EMPTY_DECL, &feature_line, 1);
                changed = true;
                true
            } else {
                false
            }
        };
        if !propagation_ok {
            // The default edit below is deliberately GATED on propagation:
            // adding a broken `offline-sync` to `default` would turn a
            // previously-compiling default build into a guaranteed build
            // failure. So when propagation could not be fixed here, warn
            // about BOTH steps and touch nothing.
            let default_note = if default_ok {
                String::new()
            } else {
                " `default` was deliberately left untouched too — enabling \
                 the broken feature by default would break every plain \
                 `cargo build` — so after fixing the feature array, also \
                 add `offline-sync` to the `default` set (or run the \
                 server deployment with `--features offline-sync`)."
                    .to_owned()
            };
            plan.warn(format!(
                "Cargo.toml declares an `offline-sync` feature, but it \
                 doesn't enable `{dep_key}/offline-sync` (directly or \
                 through another feature of this crate), so the sync \
                 code in serve() would compile against an autumn-web \
                 built WITHOUT its sync module — a guaranteed build \
                 failure. Add \"{dep_key}/offline-sync\" to your \
                 `offline-sync` feature array.{default_note} \
                 (see docs/guide/tauri-mobile-offline-sync.md)"
            ));
        } else if !default_ok {
            if edited.contains(DEFAULT_ANCHOR) {
                edited = edited.replacen(
                    DEFAULT_ANCHOR,
                    "default = [\"flash\", \"offline-sync\"]\n",
                    1,
                );
                changed = true;
            } else {
                plan.warn(
                    "Cargo.toml declares an `offline-sync` feature, but `default` \
                     doesn't enable it and the default line doesn't match the \
                     stock scaffold — add `offline-sync` to the `default` feature \
                     set yourself (or run the server deployment with `--features \
                     offline-sync`), or the deployed app will never mount the \
                     /sync endpoints the device syncs against \
                     (see docs/guide/tauri-mobile-offline-sync.md)."
                        .to_owned(),
                );
            }
        }
        if changed {
            plan.modify(cargo_path, edited);
        }
        return;
    }
    if !content.contains(FEATURES_ANCHOR) || !content.contains(DEFAULT_ANCHOR) {
        plan.warn(format!(
            "Cargo.toml doesn't match the stock scaffold layout — skipping the \
             automatic offline-sync feature edit. Add \
             `offline-sync = [\"{dep_key}/offline-sync\"]` under [features] \
             yourself and include it in `default` (or build with \
             `--features offline-sync`), so the server-side /sync endpoints \
             compile (see docs/guide/tauri-mobile-offline-sync.md)."
        ));
        return;
    }
    let edited = content
        .replacen(
            DEFAULT_ANCHOR,
            "default = [\"flash\", \"offline-sync\"]\n",
            1,
        )
        .replacen(
            FEATURES_ANCHOR,
            &format!(
                "[features]\n\
                 # Offline sync (autumn generate tauri-mobile --offline-sync): local\n\
                 # SyncStore storage plus the server-side /sync router in serve(). In\n\
                 # the default set so plain `cargo run` server deployments mount /sync.\n\
                 {feature_line}"
            ),
            1,
        );
    plan.modify(cargo_path, edited);
}

// ── App-crate lib extraction ──────────────────────────────────────────────────

/// The exact prefix of the stock scaffold's entry point (`src/templates/
/// main.rs.tmpl`). The extraction only ever fires when this anchor matches,
/// so a customised `main.rs` is never mangled (same anchored-replacement
/// discipline as `new.rs::inject_managed_pg`).
const MAIN_FN_ANCHOR: &str = "#[autumn_web::main]\nasync fn main() {";

/// What the anchor is rewritten to in the extracted `src/lib.rs`.
const SERVE_FN_HEADER: &str = "\
/// Build and run the Autumn server.
///
/// Extracted from `main()` by `autumn generate tauri-mobile` so the Tauri
/// mobile shell (src-tauri/) can run the server in-process on a background
/// thread. The `main.rs` binary still calls this on desktop.
pub async fn serve() {";

/// The stock scaffold's final `AppBuilder::run` call — the anchor after
/// which nothing may run, so the `--offline-sync` mounting is inserted
/// immediately before it (same anchored-edit discipline as
/// [`MAIN_FN_ANCHOR`]).
const RUN_CALL_ANCHOR: &str = "    app\n        .run()\n        .await;";

/// The `--offline-sync` call inserted into `serve()` before
/// [`RUN_CALL_ANCHOR`].
const SYNC_MOUNT_CALL: &str = r#"    // Offline sync (issue #1508): mount the /sync endpoints when a database
    // is configured; on a device (no database configured) this is a no-op —
    // the app boots fully offline as a sync CLIENT (see src-tauri/src/lib.rs).
    #[cfg(feature = "offline-sync")]
    let app = mount_offline_sync(app).await;

"#;

/// The `--offline-sync` server-side mounting helper appended to the
/// extracted `src/lib.rs`.
const SYNC_MOUNT_HELPER: &str = r#"
/// Mount the offline-sync server endpoints (`POST /sync/push`, `GET /sync/pull`).
///
/// Added by `autumn generate tauri-mobile --offline-sync`. The endpoints
/// trust `device_id` as sent, and anyone who can reach them can read and
/// write every synced row — so the mount FAILS CLOSED: `/sync` is mounted
/// only when BOTH hold:
///
/// - the app's resolved configuration has a database URL: the REMOTE
///   deployment of this app (the one with Postgres) serves `/sync` for
///   every device, while the same code running in-process on a phone has
///   no database and syncs as a client instead (see
///   `src-tauri/src/lib.rs`);
/// - `SYNC_TOKEN` is set to a non-empty secret: `/sync` is then wrapped in
///   the bearer-token check in `require_sync_auth` below (devices send the
///   matching secret via `AUTUMN_SYNC__TOKEN` — see
///   `src-tauri/src/lib.rs`). Without it the endpoints are NOT mounted —
///   never exposed open — and a startup warning explains how to enable
///   them. Apps with their own authentication can swap the token check in
///   `require_sync_auth` for it; keep the replacement fail closed.
///
/// REQUIRED before shipping: serve these endpoints over HTTPS only — the
/// bearer token and every synced row travel in these requests. See
/// docs/guide/tauri-mobile-offline-sync.md.
///
/// MULTI-USER apps additionally need per-user data partitioning: the
/// `server::router` call below is SINGLE-TENANT — every authenticated
/// device reads and writes one shared "global" scope. Swap it for
/// `server::scoped_router` and have your auth middleware insert an
/// `autumn_web::sync::SyncScope` derived from the authenticated user (the
/// scope is derived server-side and never client-supplied) — see the
/// "Scope data per user" section of the guide.
#[cfg(feature = "offline-sync")]
async fn mount_offline_sync(app: autumn_web::app::AppBuilder) -> autumn_web::app::AppBuilder {
    use std::sync::Arc;

    use autumn_web::reexports::{axum, tokio};
    use autumn_web::sync::{LwwResolver, PgSyncBackend, server};

    // Diagnostics below use stderr: this helper runs BEFORE AppBuilder::run()
    // installs the tracing subscriber, so tracing events here would be lost.
    //
    // The database URL is resolved through the SAME layered configuration
    // the app itself boots with (autumn.toml, profile files, and the
    // AUTUMN_DATABASE__URL / AUTUMN_DATABASE__PRIMARY_URL env overrides) —
    // not from one raw env var. Caveat: a custom loader installed via
    // `with_config_loader` is NOT consulted here; deployments that must
    // serve /sync need their database URL visible to AutumnConfig::load().
    let database_url = match autumn_web::config::AutumnConfig::load() {
        Ok(config) => config.database.effective_primary_url().map(str::to_owned),
        Err(e) => {
            eprintln!("offline-sync: config load failed ({e}); /sync not mounted");
            return app;
        }
    };
    let Some(database_url) = database_url else {
        eprintln!(
            "offline-sync: no database is configured — running as a \
             sync client only; the remote deployment serves /sync"
        );
        return app;
    };
    // FAIL CLOSED: a database is configured, so this process is the sync
    // SERVER — but without a shared secret the endpoints would be open to
    // anyone who can reach them. Refuse to mount rather than expose them.
    if !std::env::var("SYNC_TOKEN").is_ok_and(|token| !token.is_empty()) {
        eprintln!(
            "offline-sync: SYNC_TOKEN is not set — /sync NOT mounted (fail \
             closed). Set SYNC_TOKEN to a long random secret to serve /sync \
             behind the generated bearer-token check (devices send the same \
             secret via AUTUMN_SYNC__TOKEN), or replace the token check in \
             require_sync_auth with your app's real authentication — see \
             docs/guide/tauri-mobile-offline-sync.md."
        );
        return app;
    }
    let backend = Arc::new(PgSyncBackend::new(database_url));
    // Idempotent DDL for the sync shadow tables. A temporarily unreachable
    // database must not prevent the app from starting: log and continue —
    // /sync requests fail until the schema exists (restart once the database
    // is reachable, or run the DDL from a deploy step).
    let schema_backend = Arc::clone(&backend);
    match tokio::task::spawn_blocking(move || schema_backend.ensure_schema()).await {
        Ok(Ok(())) => {}
        Ok(Err(e)) => {
            eprintln!("offline-sync: could not ensure the sync schema (/sync will fail): {e}");
        }
        Err(e) => eprintln!("offline-sync: sync schema task failed: {e}"),
    }
    app.nest(
        "/sync",
        server::router(backend, Arc::new(LwwResolver))
            .layer(axum::middleware::from_fn(require_sync_auth)),
    )
}

/// Reject `/sync` requests that don't carry the expected bearer token
/// (`Authorization: Bearer <SYNC_TOKEN>`) — the generated single-tenant
/// default: every device of this deployment shares one secret. Swap the
/// token check for your app's real session/token validation if you have
/// one, and keep the replacement FAIL CLOSED (reject when the check cannot
/// be performed, never fall through to allowing the request).
#[cfg(feature = "offline-sync")]
async fn require_sync_auth(
    request: autumn_web::reexports::axum::extract::Request,
    next: autumn_web::reexports::axum::middleware::Next,
) -> Result<
    autumn_web::reexports::axum::response::Response,
    autumn_web::reexports::axum::http::StatusCode,
> {
    use autumn_web::reexports::axum::http;

    // Fail CLOSED when the server is misconfigured: with an unset/empty
    // SYNC_TOKEN the expected value would be "" and a bare
    // `Authorization: Bearer ` header would authenticate.
    // (mount_offline_sync refuses to mount /sync in that case; this guard
    // keeps the middleware safe even if it is reused elsewhere.)
    let expected = std::env::var("SYNC_TOKEN").unwrap_or_default();
    if expected.is_empty() {
        return Err(http::StatusCode::INTERNAL_SERVER_ERROR);
    }
    let authorized = request
        .headers()
        .get(http::header::AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix("Bearer "))
        // Constant-time comparison: a plain `==` short-circuits on the
        // first differing byte and leaks the secret through timing.
        .is_some_and(|token| autumn_web::sync::server::constant_time_token_eq(token, &expected));
    if authorized {
        Ok(next.run(request).await)
    } else {
        Err(http::StatusCode::UNAUTHORIZED)
    }
}
"#;

/// Plan the anchored extraction of the app's `src/main.rs` into the app's
/// **library target file** (`serve()`), with a graceful skip when the app
/// doesn't match the stock scaffold shape. With `offline_sync`, the
/// extracted `serve()` additionally mounts the server-side sync router
/// (feature-gated, and only when a database is configured — see
/// [`SYNC_MOUNT_HELPER`]).
///
/// `crate_ident` is the app's **library crate identifier** ([`AppMeta::
/// lib_ident`]) — `[lib].name` when set, else the dash-to-underscore package
/// name. `lib_src_path` is the library target's source file ([`AppMeta::
/// lib_src_path`]) — `[lib].path` when set, else `src/lib.rs`: Cargo compiles
/// THAT file as the library, so extracting into a hard-coded `src/lib.rs`
/// would leave the real lib target without `serve()` (and the shell would
/// not compile) while adding an unused stray file.
///
/// Uses `Modify` for `main.rs` (an intentional rewrite, not a collision) and
/// `CreateIfAbsent` for the lib file — so `autumn destroy tauri-mobile`
/// removes the `src-tauri/` shell but leaves the extracted (still fully
/// functional) app lib in place rather than deleting a lib file that
/// `main.rs` now depends on.
fn plan_lib_extraction(
    project_root: &Path,
    crate_ident: &str,
    lib_src_path: &str,
    offline_sync: bool,
    plan: &mut Plan,
) {
    let main_path = project_root.join("src").join("main.rs");
    let lib_path = project_root.join(lib_src_path);
    let main_rs = read_or_empty(&main_path);

    if lib_path.exists() {
        // Re-run after a successful extraction: nothing to do, stay silent —
        // unless this run wants sync mounting and the existing lib lacks it
        // (e.g. the first run had no --offline-sync).
        if main_rs.contains(&format!("{crate_ident}::serve()")) {
            if offline_sync && !read_or_empty(&lib_path).contains("mount_offline_sync") {
                plan.warn(format!(
                    "{lib_src_path} was extracted without --offline-sync — add \
                     the server-side sync mounting yourself: gate a \
                     `mount_offline_sync(app)` call before `.run()` behind \
                     `#[cfg(feature = \"offline-sync\")]` (the full helper is in \
                     docs/guide/tauri-mobile-offline-sync.md)."
                ));
            }
            return;
        }
        plan.warn(format!(
            "{lib_src_path} already exists — skipping the automatic extraction \
             of src/main.rs. The Tauri mobile shell calls \
             `{crate_ident}::serve()`; expose your app as `pub async fn \
             serve()` in {lib_src_path} by hand \
             (see docs/guide/tauri-mobile-in-process.md)."
        ));
        return;
    }

    if !main_rs.contains(MAIN_FN_ANCHOR) {
        plan.warn(format!(
            "src/main.rs doesn't match the stock scaffold layout — skipping the \
             automatic extraction into {lib_src_path}. The Tauri mobile shell \
             calls `{crate_ident}::serve()`; move your `main()` body into a \
             `pub async fn serve()` in {lib_src_path} and call it from `main()` \
             (see docs/guide/tauri-mobile-in-process.md for the exact steps)."
        ));
        return;
    }

    let mut lib_rs = main_rs.replace(MAIN_FN_ANCHOR, SERVE_FN_HEADER);
    if offline_sync {
        if lib_rs.contains(RUN_CALL_ANCHOR) {
            lib_rs = lib_rs.replacen(
                RUN_CALL_ANCHOR,
                &format!("{SYNC_MOUNT_CALL}{RUN_CALL_ANCHOR}"),
                1,
            );
            lib_rs.push_str(SYNC_MOUNT_HELPER);
        } else {
            plan.warn(
                "src/main.rs doesn't end in the stock `app.run().await` shape — \
                 skipping the automatic /sync mounting in the extracted \
                 src/lib.rs. Add it yourself before `.run()` (the full helper \
                 is in docs/guide/tauri-mobile-offline-sync.md)."
                    .to_owned(),
            );
        }
    }
    plan.create_if_absent(lib_path, lib_rs);
    plan.modify(main_path, render_thin_app_main_rs(crate_ident));
}

/// The rewritten app `src/main.rs`: a thin caller of the extracted
/// `lib.rs::serve()`, keeping desktop `cargo run` behavior identical.
fn render_thin_app_main_rs(crate_ident: &str) -> String {
    format!(
        "//! Thin binary entry point — the app itself lives in `src/lib.rs` so the\n\
         //! Tauri mobile shell (`src-tauri/`) can run the server in-process.\n\
         //! Generated by `autumn generate tauri-mobile`.\n\
         \n\
         #[autumn_web::main]\n\
         async fn main() {{\n\
         \x20   {crate_ident}::serve().await;\n\
         }}\n"
    )
}

// ── Content renderers ─────────────────────────────────────────────────────────

fn render_mobile_tauri_conf(package_name: &str, version: &str) -> String {
    // Bundle identifier: reverse-DNS, valid on BOTH stores. Android forbids
    // hyphens in application-id segments (`cargo tauri android init` panics,
    // tauri-apps/tauri#9707) and Apple forbids underscores, so both are
    // stripped — the same normalization as the thin-client generator.
    let identifier = super::tauri::derive_mobile_identifier(package_name);
    // Display title: capitalise first letter of each word; split on both '-'
    // and '_' so kebab-case and snake_case both work.
    let title: String = package_name
        .split(['-', '_'])
        .map(|word| {
            let mut chars = word.chars();
            chars.next().map_or_else(String::new, |c| {
                c.to_uppercase().to_string() + chars.as_str()
            })
        })
        .collect::<Vec<_>>()
        .join(" ");
    // Deliberately NO bundle.externalBin and NO bundle.resources: the mobile
    // model runs the server in-process (mobile sandboxes forbid sidecar
    // processes) and is configured entirely via environment variables set in
    // src/lib.rs — no staged config files.
    format!(
        r#"{{
  "$schema": "https://schema.tauri.app/config/2",
  "productName": "{title}",
  "version": "{version}",
  "identifier": "{identifier}",
  "bundle": {{
    "active": true,
    "targets": "all",
    "icon": [
      "icons/32x32.png",
      "icons/128x128.png",
      "icons/128x128@2x.png",
      "icons/icon.png",
      "icons/icon.ico",
      "icons/icon.icns"
    ]
  }},
  "app": {{
    "security": {{
      "csp": null
    }}
  }}
}}
"#
    )
}

fn render_mobile_cargo_toml(
    package_name: &str,
    has_embed_assets: bool,
    autumn_web_dep: Option<&ShellAutumnWebDep>,
) -> String {
    let shell_name = format!("{package_name}-mobile");
    // Enable the app's `embed-assets` feature so CSS/htmx/static assets are
    // compiled into the binary: a mobile app has no working directory holding
    // a `static/` tree, so disk-served assets would 404 on device.
    let app_dep = if has_embed_assets {
        format!(
            "# The `embed-assets` feature compiles the app's static/ tree (CSS, htmx,\n\
             # widgets JS) into the binary — on a device there is no on-disk static/\n\
             # directory to serve from.\n\
             {package_name} = {{ path = \"..\", features = [\"embed-assets\"] }}"
        )
    } else {
        format!("{package_name} = {{ path = \"..\" }}")
    };
    // Offline sync: the shell itself opens the local SyncStore and runs the
    // background SyncEngine, so it needs autumn-web directly — mirroring the
    // app's own dependency source (version, path, or git) so cargo unifies
    // both edges into one instance.
    let sync_dep = autumn_web_dep.map_or_else(String::new, |dep| {
        format!(
            "\n# Offline sync (issue #1508): the shell opens the local SyncStore and runs\n\
             # the background SyncEngine (autumn_web::sync). The dependency mirrors the\n\
             # app crate's own autumn-web source so cargo unifies both dependency edges.\n\
             {}\n",
            dep.dep_entry
        )
    });
    let patch_section = autumn_web_dep
        .and_then(|dep| dep.patch_entry.as_deref())
        .unwrap_or("");
    format!(
        r#"[package]
name = "{shell_name}"
version = "0.0.1"
edition = "2021"

# Standalone workspace so this crate is independent from the autumn app workspace —
# no change to the root Cargo.toml is needed.
[workspace]

[lib]
# Mobile platforms link the app as a library rather than running a binary:
#   staticlib — iOS (linked into the generated Xcode project)
#   cdylib    — Android (loaded by the generated Android activity)
#   rlib      — lets src/main.rs run the same shell on desktop (cargo tauri dev)
crate-type = ["staticlib", "cdylib", "rlib"]

[build-dependencies]
tauri-build = {{ version = "2", features = [] }}

[dependencies]
tauri = {{ version = "2", features = [] }}
# Runtime for the in-process server thread (see src/lib.rs).
tokio = {{ version = "1", features = ["rt-multi-thread"] }}
getrandom = {{ version = "0.4", features = ["std"] }}
# The autumn app itself — the server runs IN-PROCESS on a background thread
# (mobile sandboxes forbid sidecar processes), so the shell links the app
# crate directly instead of bundling a server binary.
{app_dep}
{sync_dep}
[profile.release]
panic = "abort"
codegen-units = 1
lto = true
opt-level = "s"
strip = true
{patch_section}"#
    )
}

fn render_mobile_build_rs() -> String {
    "fn main() {\n    tauri_build::build()\n}\n".to_owned()
}

fn render_mobile_main_rs(package_name: &str) -> String {
    let lib_name = package_name.replace('-', "_") + "_mobile";
    format!(
        "#![cfg_attr(not(debug_assertions), windows_subsystem = \"windows\")]\n\
         \n\
         // Desktop-dev entry point for the mobile shell; on iOS/Android the\n\
         // platform loads the library through `tauri::mobile_entry_point`.\n\
         fn main() {{\n\
         \x20   {lib_name}::run();\n\
         }}\n"
    )
}

/// `--offline-sync` addition to the shell lib.rs module docs.
const SYNC_LIB_DOC: &str = "\
//!
//! OFFLINE SYNC (--offline-sync): app data lives in a local SyncStore-backed
//! `SQLite` database inside the app sandbox, and a background SyncEngine
//! reconciles it with the remote deployment's /sync endpoints whenever the
//! network allows — the device itself needs NO direct database connection.
//! See docs/guide/tauri-mobile-offline-sync.md.
";

/// `--offline-sync` addition to the env-var block in the shell's `run()`.
const SYNC_ENV_BLOCK: &str = r#"    // ── Offline sync (issue #1508) ──────────────────────────────────────────
    // Local-first data: app state lives in a SyncStore-backed SQLite file in
    // the app sandbox (AUTUMN_SYNC__DB_PATH, exported in setup() once the
    // sandbox path is known) and a background SyncEngine syncs it with your
    // remote Autumn deployment. Point the engine at the remote /sync mount:
    // std::env::set_var(
    //     "AUTUMN_SYNC__REMOTE_URL",
    //     "https://app.example.com/sync",
    // );
    // ... and give it the deployment's SYNC_TOKEN so requests authenticate
    // (sent as `Authorization: Bearer …`; the generated server mount serves
    // /sync ONLY behind that check). Never hard-code a real secret in
    // source — deliver it at runtime from your login/auth flow:
    // std::env::set_var("AUTUMN_SYNC__TOKEN", sync_token);
    // With offline sync the device needs NO direct database connection: leave
    // AUTUMN_DATABASE__URL unset and the in-process server boots without
    // Postgres — the app works fully offline and converges with the remote in
    // the background. Full guide: docs/guide/tauri-mobile-offline-sync.md.
    // ────────────────────────────────────────────────────────────────────────
"#;

/// `--offline-sync` addition to the shell's `setup()` (the sync database
/// path needs the sandbox data dir).
const SYNC_SETUP_BLOCK: &str = r#"    // Offline sync: local-first app data lives in a SyncStore-backed SQLite
    // file inside the sandbox. AUTUMN_SYNC__DB_PATH is exported so the app's
    // routes reach the SAME file the background engine syncs (see
    // start_background_sync below). In your routes, open the store ONCE
    // (e.g. behind a OnceLock) and clone it per use — clones share one
    // connection; repeated SyncStore::open calls pay setup every time.
    let sync_db = data_root.join("sync.db");
    std::env::set_var("AUTUMN_SYNC__DB_PATH", sync_db.to_string_lossy().as_ref());
"#;

/// Render the shell's `src/lib.rs`. `crate_ident` is the app's library crate
/// identifier ([`AppMeta::lib_ident`]) used for the `<crate_ident>::serve()`
/// call — `[lib].name` when the app sets one.
#[allow(clippy::too_many_lines)]
fn render_mobile_lib_rs(package_name: &str, crate_ident: &str, offline_sync: bool) -> String {
    let sync_doc = if offline_sync { SYNC_LIB_DOC } else { "" };
    let sync_env_block = if offline_sync { SYNC_ENV_BLOCK } else { "" };
    let sync_setup = if offline_sync { SYNC_SETUP_BLOCK } else { "" };
    let sync_thread_line = if offline_sync {
        "        start_background_sync(&runtime, sync_db);\n"
    } else {
        ""
    };
    // The offline-sync shell observes run-loop events (RunEvent::Resumed →
    // immediate sync pass), so it must go through build().run(callback); the
    // default shell keeps the simpler run(context).
    let tauri_run_tail = if offline_sync {
        format!(
            r#"    tauri::Builder::default()
        .setup(move |app| setup(app, port))
        .build(tauri::generate_context!())
        .expect("error while building tauri application")
        .run(|_app_handle, event| {{
            // Connectivity-regain trigger: mobile OSes freeze the process
            // (and its timers) in the background, and connectivity usually
            // returns together with the foreground. On resume, kick one
            // immediate sync pass instead of waiting out the background
            // interval/backoff.
            if let tauri::RunEvent::Resumed = event {{
                if let Some((handle, engine)) = SYNC_KICK.get() {{
                    let engine = engine.clone();
                    handle.spawn(async move {{
                        if let Err(e) = engine.sync_once().await {{
                            eprintln!(
                                "[{package_name}] Resume sync failed (next background pass retries): {{e}}"
                            );
                        }}
                    }});
                }}
            }}
        }});"#
        )
    } else {
        r#"    tauri::Builder::default()
        .setup(move |app| setup(app, port))
        .run(tauri::generate_context!())
        .expect("error while running tauri application");"#
            .to_owned()
    };
    let sync_helpers = if offline_sync {
        format!(
            r#"
/// Handle to the background sync engine, set once from the server thread so
/// the tauri run-loop callback can trigger an immediate sync pass on
/// RunEvent::Resumed. Never set when AUTUMN_SYNC__REMOTE_URL is unset
/// (offline-only mode).
static SYNC_KICK: std::sync::OnceLock<(tokio::runtime::Handle, autumn_web::sync::SyncEngine)> =
    std::sync::OnceLock::new();

/// Open the local sync store and spawn the background sync engine on the
/// server runtime (issue #1508). The app keeps working fully offline: local
/// reads and writes always hit the SyncStore, and when
/// AUTUMN_SYNC__REMOTE_URL is configured the engine pushes/pulls every 30 s
/// (exponential backoff while the remote is unreachable), so the app
/// converges automatically when connectivity returns. See
/// docs/guide/tauri-mobile-offline-sync.md.
///
/// MULTI-ACCOUNT apps: this one store file serves the whole installation.
/// If the same device can re-authenticate as a different account, bind the
/// store to the signed-in account with `store.set_identity(user_key)` on
/// every login/logout BEFORE syncing — on an account change it resets the
/// cached rows, pending outbox, and cursor so the next account never sees
/// (or skips past) the previous account's data. Pair it with the server's
/// `scoped_router` — see the guide's "Scope data per user" section.
fn start_background_sync(runtime: &tokio::runtime::Runtime, sync_db: std::path::PathBuf) {{
    let store = match autumn_web::sync::SyncStore::open(&sync_db) {{
        Ok(store) => store,
        Err(e) => {{
            eprintln!("[{package_name}] Failed to open the offline sync store: {{e}}");
            return;
        }}
    }};
    let Ok(remote_url) = std::env::var("AUTUMN_SYNC__REMOTE_URL") else {{
        eprintln!(
            "[{package_name}] AUTUMN_SYNC__REMOTE_URL is not set — running \
             offline-only (local SyncStore, no background sync)."
        );
        return;
    }};
    let mut config = autumn_web::sync::SyncConfig::new(remote_url);
    // The generated server mount serves /sync only behind its SYNC_TOKEN
    // bearer check — send the matching secret (set in run(), ideally
    // delivered by your login/auth flow rather than hard-coded).
    match std::env::var("AUTUMN_SYNC__TOKEN") {{
        Ok(token) if !token.is_empty() => config.bearer_token = Some(token),
        _ => eprintln!(
            "[{package_name}] AUTUMN_SYNC__TOKEN is not set — syncing without \
             credentials. The generated server mount requires its SYNC_TOKEN \
             and will answer 401 until the matching secret is set here (or \
             until you wire your own auth end to end)."
        ),
    }}
    let engine = autumn_web::sync::SyncEngine::new(store, config);
    // spawn_background must be entered from inside the runtime; the returned
    // JoinHandle detaches on drop (dropping never cancels the task).
    let _sync_task =
        runtime.block_on(async {{ engine.spawn_background(std::time::Duration::from_secs(30)) }});
    let _ = SYNC_KICK.set((runtime.handle().clone(), engine));
}}
"#
        )
    } else {
        String::new()
    };
    format!(
        r#"//! Tauri mobile shell for {package_name} — in-process backend + remote Postgres.
//!
//! Mobile sandboxes (iOS and Android) forbid spawning child processes, so the
//! desktop sidecar model cannot work here. Instead the Autumn Axum server runs
//! on a background thread INSIDE this app process:
//!
//!   1. Bind loopback:0 to find a free ephemeral port.
//!   2. Configure the server through environment variables at the top of
//!      run(), before tauri::Builder starts any platform threads.
//!   3. std::thread::spawn a dedicated tokio runtime that block_on()s
//!      {crate_ident}::serve() — the app entry extracted into src/lib.rs by
//!      `autumn generate tauri-mobile`.
//!   4. Poll GET /health in a background thread until the server is ready,
//!      then open the webview at http://127.0.0.1:<port>.
//!
//! The database is a REMOTE Postgres reached over the device network. The env
//! defaults below (small pool, short connect timeout) are tuned for flaky
//! mobile networks — see docs/guide/tauri-mobile-in-process.md for the full
//! rationale, reconnection semantics, security notes, and App Store
//! compliance notes.
{sync_doc}
use std::net::TcpListener;
use tauri::Manager;

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {{
    // 1. Find a free loopback port: bind :0, read the assigned port, then drop
    //    the listener so the in-process server can bind that same address.
    //    (The port is briefly unbound until the server thread claims it — see
    //    the security section of docs/guide/tauri-mobile-in-process.md.)
    let port = {{
        let listener = TcpListener::bind("127.0.0.1:0").expect("failed to bind a loopback port");
        listener
            .local_addr()
            .expect("failed to read the loopback port")
            .port()
    }};

    // 2. Configure the server via environment variables. The server runs in
    //    THIS process, so std::env::set_var is the whole config story — no
    //    staged config files (an autumn.toml in the app repo is NOT read by
    //    this shell). This block runs at the top of run(), BEFORE
    //    tauri::Builder starts platform runtimes: set_var is only sound while
    //    no foreign threads may call getenv concurrently. Only the values
    //    that need the app sandbox path are deferred to setup().
    std::env::set_var("AUTUMN_SERVER__HOST", "127.0.0.1");
    std::env::set_var("AUTUMN_SERVER__PORT", port.to_string());
    // ── Remote Postgres over a mobile network ───────────────────────────────
    // Point the app at your remote database (require TLS in production):
    // std::env::set_var(
    //     "AUTUMN_DATABASE__URL",
    //     "postgres://app_user:PASSWORD@db.example.com:5432/app?sslmode=require",
    // );
    //
    // Conservative pool defaults for flaky mobile networks: a phone gets one
    // user's traffic, so a large server-style pool only holds open sockets
    // that die on every network transition (Wi-Fi ⇄ cellular, backgrounding).
    // The deadpool-backed pool re-checks connections on checkout and
    // re-establishes broken ones automatically, so a small pool recovers
    // faster and wastes fewer half-dead connections.
    std::env::set_var("AUTUMN_DATABASE__POOL_SIZE", "2");
    // Fail fast on NEW connection attempts when the radio is off or asleep.
    // (5 is also the framework default — pinned here so the mobile posture
    // survives future framework default changes.)
    std::env::set_var("AUTUMN_DATABASE__CONNECT_TIMEOUT_SECS", "5");
    // ────────────────────────────────────────────────────────────────────────
{sync_env_block}    // The webview loads the app over plain HTTP on loopback; Secure cookies
    // would be silently dropped by the webview, breaking sessions and CSRF.
    // Loopback never leaves the device — but other apps ON the device can
    // reach it too (see the security section of the docs page).
    std::env::set_var("AUTUMN_SESSION__SECURE", "false");
    // Loopback-only server: accept Host: 127.0.0.1 from the webview even when
    // production config pins trusted hosts to a public domain.
    std::env::set_var("AUTUMN_SECURITY__TRUSTED_HOSTS__HOSTS", "127.0.0.1,localhost");
    // Local blob storage backend rooted in the app sandbox; the root path is
    // set in setup() once the sandbox data dir is known.
    std::env::set_var("AUTUMN_STORAGE__BACKEND", "local");
    std::env::set_var("AUTUMN_STORAGE__ALLOW_LOCAL_IN_PRODUCTION", "true");
    // No load balancer drains connections to an in-process loopback server;
    // skip the prestop grace so shutdown hooks run immediately.
    std::env::set_var("AUTUMN_SERVER__PRESTOP_GRACE_SECS", "0");
    // Profile selection: dev config during `cargo tauri [ios|android] dev`,
    // prod config in release builds. Set explicitly — running serve()
    // in-process bypasses the #[autumn_web::main] entry point that would
    // otherwise bake the release/debug signal into profile detection, so
    // without this a release build would silently run the dev profile.
    if cfg!(debug_assertions) {{
        std::env::set_var("AUTUMN_ENV", "dev");
    }} else {{
        std::env::set_var("AUTUMN_ENV", "prod");
    }}
    // Clear inherited one-off mode flags and desktop-only settings: any of
    // these would make AppBuilder::run() exit before binding the HTTP port
    // (build-static/dump-routes/task modes), bind a Unix socket the health
    // probe can't reach, or attach a foreign managed-Postgres cluster.
    for var in [
        "AUTUMN_PROFILE",
        "AUTUMN_BUILD_STATIC",
        "AUTUMN_DUMP_ROUTES",
        "AUTUMN_LIST_TASKS",
        "AUTUMN_RUN_TASK",
        "AUTUMN_SERVER__UNIX_SOCKET",
        "AUTUMN_SERVE_FORCE_UNIX_SOCKET",
        "AUTUMN_MANAGED_PG_ATTACH_URL",
    ] {{
        std::env::remove_var(var);
    }}

{tauri_run_tail}
}}

fn setup(app: &mut tauri::App, port: u16) -> Result<(), Box<dyn std::error::Error>> {{
    // 3. Per-app data directories (inside the mobile app sandbox). These two
    //    set_var calls are the only ones that must wait for the tauri App
    //    handle (the sandbox path is not known before the Builder runs); they
    //    still execute before the server thread reads the environment.
    let data_root = app.path().app_data_dir()?;
    std::fs::create_dir_all(&data_root)?;
    // Local blob storage in blobs/ (the only writable filesystem location).
    let blobs_dir = data_root.join("blobs");
    std::fs::create_dir_all(&blobs_dir)?;
    std::env::set_var(
        "AUTUMN_STORAGE__LOCAL__ROOT",
        blobs_dir.to_string_lossy().as_ref(),
    );
{sync_setup}    // Per-install signing secret: autumn requires one in prod mode. Generate
    // 32 random bytes on first launch and persist them so sessions survive
    // restarts.
    let signing_secret = load_or_generate_signing_secret(&data_root)?;
    std::env::set_var("AUTUMN_SECURITY__SIGNING_SECRET", &signing_secret);

    // 4. Spawn the Autumn server on a background thread with its own tokio
    //    runtime. tauri's setup() is synchronous and must return quickly, so
    //    the server gets a dedicated OS thread; block_on parks that thread on
    //    the server future for the lifetime of the app. Mobile OSes reclaim
    //    the whole process on exit — there is no separate child to clean up.
    std::thread::spawn(move || {{
        let runtime = tokio::runtime::Builder::new_multi_thread()
            .enable_all()
            .build()
            .expect("failed to build tokio runtime for the in-process autumn server");
{sync_thread_line}        runtime.block_on({crate_ident}::serve());
    }});

    // 5. Poll for server readiness in a background thread so setup() returns
    //    immediately and the Tauri event loop starts (blocking here can
    //    trigger the mobile OS's app-startup watchdog). We probe GET /health —
    //    the cheap readiness endpoint autumn always registers; any HTTP
    //    response proves the server is up and routing.
    let handle = app.handle().clone();
    std::thread::spawn(move || {{
        let addr = std::net::SocketAddr::new(
            std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)),
            port,
        );
        let poll_timeout = std::time::Duration::from_millis(200);
        let mut ready = false;
        // 300 × 200 ms = 60 s. No local Postgres cluster to initialise here
        // (the DB is remote), so startup is fast; 60 s leaves headroom for
        // slow first-launch migrations without hanging a broken install
        // forever behind a blank screen.
        for _ in 0..300 {{
            if let Ok(mut stream) = std::net::TcpStream::connect_timeout(&addr, poll_timeout) {{
                let _ = stream.set_read_timeout(Some(poll_timeout));
                use std::io::{{Read, Write}};
                let req = "GET /health HTTP/1.1\r\nHost: 127.0.0.1\r\nConnection: close\r\n\r\n";
                if stream.write_all(req.as_bytes()).is_ok() {{
                    let mut buf = [0u8; 8];
                    // Any valid HTTP response (200, 404, …) means the server is
                    // up and routing — accept the `HTTP/` prefix regardless of
                    // status.
                    if stream.read(&mut buf).is_ok() && buf.starts_with(b"HTTP/") {{
                        ready = true;
                        break;
                    }}
                }}
            }}
            std::thread::sleep(poll_timeout);
        }}
        if !ready {{
            eprintln!("[{package_name}] Server did not become ready within 60 s.");
            show_startup_error(
                &handle,
                "The app's built-in server did not start in time. This is \
                 usually a configuration problem — for example an unreachable \
                 or misconfigured AUTUMN_DATABASE__URL. Check the device logs \
                 for details.",
            );
            return;
        }}
        if let Err(e) = tauri::WebviewWindowBuilder::new(
            &handle,
            "main",
            tauri::WebviewUrl::External(
                format!("http://127.0.0.1:{{port}}").parse().unwrap(),
            ),
        )
        .title("{package_name}")
        .build()
        {{
            eprintln!("[{package_name}] Failed to open window: {{e}}");
            show_startup_error(&handle, "The app window could not be opened.");
        }}
    }});

    Ok(())
}}
{sync_helpers}
/// Surface a startup failure in a visible window instead of a silent exit or
/// an endless blank screen. Falls back to exiting when even the error window
/// cannot be built. Note: some framework-level startup failures (for example
/// a database bootstrap error) call std::process::exit directly from the
/// server thread and terminate the app before this can render — see the
/// troubleshooting notes in docs/guide/tauri-mobile-in-process.md.
fn show_startup_error(handle: &tauri::AppHandle, message: &str) {{
    let html = format!(
        "<!doctype html><html><head><meta charset=\"utf-8\"></head>\
         <body style=\"font-family:system-ui;margin:2rem\">\
         <h1>{package_name} could not start</h1>\
         <p>{{message}}</p></body></html>"
    );
    let opened = format!("data:text/html,{{}}", percent_encode(&html))
        .parse()
        .ok()
        .and_then(|url| {{
            tauri::WebviewWindowBuilder::new(handle, "startup-error", tauri::WebviewUrl::External(url))
                .title("{package_name}")
                .build()
                .ok()
        }})
        .is_some();
    if !opened {{
        handle.exit(1);
    }}
}}

/// Minimal percent-encoding for embedding the error page in a data: URL
/// (avoids pulling an extra dependency into the shell crate).
fn percent_encode(input: &str) -> String {{
    input
        .bytes()
        .map(|b| match b {{
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {{
                char::from(b).to_string()
            }}
            _ => format!("%{{b:02X}}"),
        }})
        .collect()
}}

/// Generate a 32-byte random signing secret on first launch, persist it to
/// `{{data_root}}/signing_secret.txt`, and return it as a hex string.
/// Autumn requires a signing secret in prod mode to sign session tokens;
/// without one the release build aborts before binding the HTTP port.
fn load_or_generate_signing_secret(
    data_root: &std::path::Path,
) -> Result<String, Box<dyn std::error::Error>> {{
    let path = data_root.join("signing_secret.txt");
    if let Ok(s) = std::fs::read_to_string(&path) {{
        let s = s.trim().to_owned();
        if s.len() >= 32 {{
            return Ok(s);
        }}
    }}
    let mut bytes = [0u8; 32];
    // Propagate RNG failure — an all-zero secret would be trivially guessable.
    getrandom::fill(&mut bytes)?;
    let hex: String = bytes.iter().map(|b| format!("{{b:02x}}")).collect();
    // The app sandbox is private to this app on iOS/Android, but restrict
    // permissions anyway where the platform supports it.
    #[cfg(unix)]
    {{
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        std::fs::OpenOptions::new()
            .write(true).create(true).truncate(true)
            .mode(0o600)
            .open(&path)
            .and_then(|mut f| f.write_all(hex.as_bytes()))?;
    }}
    #[cfg(not(unix))]
    {{
        std::fs::write(&path, &hex)?;
    }}
    Ok(hex)
}}
"#
    )
}

/// Duplicated byte-for-byte from `generate::tauri::render_placeholder_icon_svg`
/// — the desktop generator's placeholder icon is the same SVG, hand-copied
/// when this file was built. Two instances is below Echo's rule of three, so
/// it stays linked rather than merged; see `tests::
/// placeholder_icon_assets_match_between_desktop_and_mobile_tauri_generators`
/// in `generate::mod` for the drift guard.
pub fn render_placeholder_icon_svg() -> String {
    concat!(
        "<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 512 512\">\n",
        "  <!-- Placeholder app icon. Replace with your own, then run:\n",
        "       cargo tauri icon static/icons/icon.svg -->\n",
        "  <rect width=\"512\" height=\"512\" rx=\"64\" fill=\"#4F7942\"/>\n",
        "  <text x=\"256\" y=\"370\" font-size=\"280\" text-anchor=\"middle\"",
        " font-family=\"system-ui\">&#x1F342;</text>\n",
        "</svg>\n",
    )
    .to_owned()
}

fn render_mobile_gitignore() -> String {
    // /gen is where `cargo tauri ios init` / `cargo tauri android init` put
    // the generated Xcode / Gradle projects.
    "/target\n/gen\n".to_owned()
}

// ── Placeholder icon bytes ────────────────────────────────────────────────────
// Duplicated byte-for-byte from `generate::tauri` — the desktop generator's
// PLACEHOLDER_PNG/_ICO/_ICNS are the same bytes, hand-copied when this file
// was built (originally to dodge a merge conflict with tauri.rs's concurrent
// rework, #1506 — that landed long ago). Two instances is below Echo's rule
// of three (see issue #2509), so these stay linked rather than merged into a
// shared `generate::icons` module. Change one, change the other: `tests::
// placeholder_icon_assets_match_between_desktop_and_mobile_tauri_generators`
// in `generate::mod` fails if they drift.
// Minimal valid 1×1 RGBA PNG (autumn green #4F7942, opaque).
pub const PLACEHOLDER_PNG: &[u8] = &[
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, // PNG signature
    0x00, 0x00, 0x00, 0x0d, // IHDR length = 13
    0x49, 0x48, 0x44, 0x52, // "IHDR"
    0x00, 0x00, 0x00, 0x01, // width = 1
    0x00, 0x00, 0x00, 0x01, // height = 1
    0x08, 0x06, 0x00, 0x00, 0x00, // depth=8, colortype=6(RGBA), compress=filter=interlace=0
    0x1f, 0x15, 0xc4, 0x89, // IHDR CRC
    0x00, 0x00, 0x00, 0x0d, // IDAT length = 13
    0x49, 0x44, 0x41, 0x54, // "IDAT"
    0x78, 0x9c, 0x63, 0xf0, 0xaf, 0x74, 0xfa, 0x0f, 0x00, 0x04, 0x2f, 0x02, 0x0a, // deflate
    0x5e, 0x60, 0x4a, 0x2d, // IDAT CRC
    0x00, 0x00, 0x00, 0x00, // IEND length = 0
    0x49, 0x45, 0x4e, 0x44, // "IEND"
    0xae, 0x42, 0x60, 0x82, // IEND CRC
];

// Minimal ICO wrapping the placeholder PNG.
pub const PLACEHOLDER_ICO: &[u8] = &[
    0x00, 0x00, 0x01, 0x00, // ICO header: reserved=0, type=1(ICO)
    0x01, 0x00, // image count = 1
    0x00, 0x00, 0x00, 0x00, // width=0(→256), height=0(→256), palette=0, reserved=0
    0x01, 0x00, 0x20, 0x00, // planes=1, bit_count=32
    0x46, 0x00, 0x00, 0x00, // image data size = 70 bytes
    0x16, 0x00, 0x00, 0x00, // image data offset = 22 (6+16)
    // PNG data (same as PLACEHOLDER_PNG, 70 bytes)
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
    0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf0, 0xaf, 0x74, 0xfa,
    0x0f, 0x00, 0x04, 0x2f, 0x02, 0x0a, 0x5e, 0x60, 0x4a, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
    0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];

// Minimal ICNS container wrapping the placeholder PNG as icp6 (PNG icon).
pub const PLACEHOLDER_ICNS: &[u8] = &[
    0x69, 0x63, 0x6e, 0x73, // "icns" magic
    0x00, 0x00, 0x00, 0x56, // total file size = 86
    0x69, 0x63, 0x70, 0x36, // icon type "icp6" (PNG icon)
    0x00, 0x00, 0x00, 0x4e, // entry size = 78 (8 header + 70 PNG)
    // PNG data (same as PLACEHOLDER_PNG, 70 bytes)
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4,
    0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf0, 0xaf, 0x74, 0xfa,
    0x0f, 0x00, 0x04, 0x2f, 0x02, 0x0a, 0x5e, 0x60, 0x4a, 0x2d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,
    0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];

// ── Unit tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::super::emit::Action;
    use super::*;

    /// Find the planned action targeting the APP crate's `src/<name>` —
    /// as opposed to the shell's `src-tauri/src/<name>`.
    fn app_src_action<'p>(plan: &'p Plan, name: &str) -> Option<&'p Action> {
        plan.actions.iter().find(|a| {
            a.path().ends_with(format!("src/{name}"))
                && !a.path().to_string_lossy().contains("src-tauri")
        })
    }

    fn app_dir(name: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            format!(
                "[package]\nname = \"{name}\"\nversion = \"0.2.3\"\n\n\
                 [features]\nembed-assets = [\"autumn-web/embed-assets\"]\n"
            ),
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        tmp
    }

    /// A minimal stand-in for the stock `main.rs.tmpl` output, carrying the
    /// exact `MAIN_FN_ANCHOR` shape and the template's multi-line
    /// `RUN_CALL_ANCHOR` ending.
    fn stock_main_rs() -> String {
        "use autumn_web::prelude::*;\n\n#[autumn_web::main]\nasync fn main() {\n    \
         let app = autumn_web::app()\n        .routes(routes![]);\n\n    \
         app\n        .run()\n        .await;\n}\n"
            .to_owned()
    }

    #[test]
    fn conf_has_identifier_product_name_and_no_external_bin() {
        let conf = render_mobile_tauri_conf("my-app", "1.2.3");
        let parsed: serde_json::Value = serde_json::from_str(&conf).unwrap();
        // Hyphens are stripped: Android forbids them in application-id
        // segments (`cargo tauri android init` panics on them), Apple
        // forbids underscores — same normalization as the thin client.
        assert_eq!(parsed["identifier"], "com.example.myapp");
        assert_eq!(parsed["productName"], "My App");
        assert_eq!(parsed["version"], "1.2.3");
        assert!(parsed["bundle"].get("externalBin").is_none());
        assert!(parsed["bundle"].get("resources").is_none());
    }

    #[test]
    fn conf_identifier_is_android_and_ios_safe() {
        // Underscores (Apple-forbidden) and hyphens (Android-forbidden) are
        // both stripped from the identifier segment.
        let conf = render_mobile_tauri_conf("my_app", "0.1.0");
        let parsed: serde_json::Value = serde_json::from_str(&conf).unwrap();
        assert_eq!(parsed["identifier"], "com.example.myapp");
        assert_eq!(parsed["productName"], "My App");

        let conf = render_mobile_tauri_conf("my-kebab_mix", "0.1.0");
        let parsed: serde_json::Value = serde_json::from_str(&conf).unwrap();
        assert_eq!(parsed["identifier"], "com.example.mykebabmix");
    }

    #[test]
    fn cargo_toml_is_mobile_library_without_sidecar_plugin() {
        let toml_src = render_mobile_cargo_toml("my-app", true, None);
        assert!(toml_src.contains(r#"crate-type = ["staticlib", "cdylib", "rlib"]"#));
        assert!(
            toml_src.contains(r#"my-app = { path = "..", features = ["embed-assets"] }"#),
            "shell must build the app with embedded assets (no static/ dir on device)"
        );
        assert!(toml_src.contains(r#"name = "my-app-mobile""#));
        assert!(!toml_src.contains("tauri-plugin-shell"));
        // The rendered manifest must be valid TOML.
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");
    }

    #[test]
    fn cargo_toml_omits_embed_assets_when_app_lacks_the_feature() {
        let toml_src = render_mobile_cargo_toml("my-app", false, None);
        assert!(toml_src.contains(r#"my-app = { path = ".." }"#));
        assert!(!toml_src.contains("embed-assets"));
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");
    }

    #[test]
    fn plan_warns_when_app_has_no_embed_assets_feature() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        assert!(
            plan.warnings.iter().any(|w| w.contains("embed-assets")),
            "must warn when the app declares no embed-assets feature, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn lib_rs_spawns_in_process_server_with_pool_defaults() {
        let lib = render_mobile_lib_rs("my-app", "my_app", false);
        assert!(lib.contains("tauri::Builder::default()"));
        assert!(lib.contains(".setup("));
        assert!(lib.contains("std::thread::spawn"));
        assert!(lib.contains("block_on(my_app::serve())"));
        assert!(lib.contains("tauri::mobile_entry_point"));
        // The advertised flaky-network defaults are pinned by VALUE, not just
        // by variable name (comments also name the variables).
        assert!(lib.contains(r#"set_var("AUTUMN_DATABASE__POOL_SIZE", "2")"#));
        assert!(lib.contains(r#"set_var("AUTUMN_DATABASE__CONNECT_TIMEOUT_SECS", "5")"#));
        assert!(lib.contains("AUTUMN_DATABASE__URL"));
        assert!(!lib.contains(".sidecar("));
        assert!(!lib.contains("tauri_plugin_shell"));
    }

    #[test]
    fn lib_rs_pins_prod_profile_in_release_builds() {
        let lib = render_mobile_lib_rs("my-app", "my_app", false);
        // Release builds must run the prod profile: serve() bypasses the
        // #[autumn_web::main] macro that would otherwise mark release builds,
        // so leaving AUTUMN_ENV unset would silently fall back to dev
        // (permissive CORS, debug logging, no fail-fast secret checks).
        assert!(lib.contains(r#"set_var("AUTUMN_ENV", "prod")"#));
        assert!(lib.contains(r#"set_var("AUTUMN_ENV", "dev")"#));
        assert!(
            !lib.contains(r#"remove_var("AUTUMN_ENV")"#),
            "release builds must pin prod explicitly, not unset AUTUMN_ENV"
        );
    }

    #[test]
    fn lib_rs_sets_env_before_tauri_builder_starts() {
        let lib = render_mobile_lib_rs("my-app", "my_app", false);
        // std::env::set_var is only sound before other (platform) threads
        // exist; the static env block must precede tauri::Builder in run().
        let env_pos = lib
            .find(r#"set_var("AUTUMN_ENV""#)
            .expect("template must set AUTUMN_ENV");
        let builder_pos = lib
            .find("tauri::Builder::default()")
            .expect("template must build a tauri app");
        assert!(
            env_pos < builder_pos,
            "the env-var block must run before tauri::Builder::default()"
        );
        // Storage backend must be enabled explicitly: the prod profile
        // defaults storage.backend to \"disabled\".
        assert!(lib.contains(r#"set_var("AUTUMN_STORAGE__BACKEND", "local")"#));
    }

    #[test]
    fn lib_rs_surfaces_startup_failure_in_a_visible_error_page() {
        let lib = render_mobile_lib_rs("my-app", "my_app", false);
        assert!(
            lib.contains("fn show_startup_error("),
            "startup failures must surface a visible error, not a silent exit"
        );
        assert!(lib.contains("data:text/html"));
        // The health-poll timeout path routes through the error page.
        assert!(lib.contains("did not become ready"));
    }

    #[test]
    fn mobile_main_rs_calls_shell_lib() {
        let main = render_mobile_main_rs("my-app");
        assert!(main.contains("my_app_mobile::run();"));
    }

    #[test]
    fn lib_extraction_rewrites_stock_main_and_creates_lib() {
        let tmp = app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();

        let lib_action =
            app_src_action(&plan, "lib.rs").expect("plan must create the app src/lib.rs");
        let Action::CreateIfAbsent { contents, .. } = lib_action else {
            panic!("app lib.rs must be a CreateIfAbsent action, got {lib_action:?}");
        };
        assert!(contents.contains("pub async fn serve()"));
        assert!(!contents.contains("async fn main()"));

        let main_action =
            app_src_action(&plan, "main.rs").expect("plan must rewrite the app src/main.rs");
        let Action::Modify { contents, .. } = main_action else {
            panic!("app main.rs must be a Modify action, got {main_action:?}");
        };
        assert!(contents.contains("my_app::serve().await;"));
        assert!(plan.warnings.is_empty(), "no warnings on the happy path");
    }

    #[test]
    fn lib_extraction_skips_customised_main_with_docs_warning() {
        let tmp = app_dir("my-app");
        std::fs::write(
            tmp.path().join("src/main.rs"),
            "#[tokio::main]\nasync fn main() {}\n",
        )
        .unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();

        assert!(
            app_src_action(&plan, "lib.rs").is_none(),
            "no app lib.rs may be planned when the anchor is missing"
        );
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("tauri-mobile-in-process")),
            "warning must point at the docs page, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn lib_extraction_is_silent_when_already_extracted() {
        let tmp = app_dir("my-app");
        std::fs::write(
            tmp.path().join("src/main.rs"),
            render_thin_app_main_rs("my_app"),
        )
        .unwrap();
        std::fs::write(tmp.path().join("src/lib.rs"), "pub async fn serve() {}\n").unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        assert!(plan.warnings.is_empty());
        assert!(app_src_action(&plan, "main.rs").is_none());
    }

    #[test]
    fn lib_extraction_warns_when_foreign_lib_rs_exists() {
        let tmp = app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();
        std::fs::write(tmp.path().join("src/lib.rs"), "pub fn helper() {}\n").unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("src/lib.rs already exists")),
            "must warn about the pre-existing lib.rs, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn plan_emits_no_sidecar_artifacts() {
        let tmp = app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        for action in &plan.actions {
            let p = action.path().to_string_lossy().replace('\\', "/");
            assert!(
                !p.contains("stage-sidecar"),
                "mobile plan must not stage sidecars: {p}"
            );
        }
    }

    #[test]
    fn read_app_meta_resolves_workspace_version() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n[workspace.package]\nversion = \"9.9.9\"\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(app.join("src")).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion.workspace = true\n",
        )
        .unwrap();

        let meta = read_app_meta(&app).unwrap();
        assert_eq!(meta.package_name, "app");
        assert_eq!(meta.version, "9.9.9");
        assert!(
            !meta.has_embed_assets,
            "no [features] table means no embed-assets feature"
        );
    }

    #[test]
    fn read_app_meta_resolves_workspace_version_through_a_pointer_root() {
        // `[package] workspace = "…"` may name a NON-ANCESTOR root — an
        // ancestor-only walk never reads its [workspace.package] and falls
        // back to "0.1.0", stamping the generated tauri.conf.json (the
        // mobile bundle version) with the wrong release number.
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");
        std::fs::create_dir_all(&ws).unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            "[workspace]\nmembers = []\n[workspace.package]\nversion = \"2.3.4\"\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(app.join("src")).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion.workspace = true\nworkspace = \"../ws\"\n",
        )
        .unwrap();

        let meta = read_app_meta(&app).unwrap();
        assert_eq!(
            meta.version, "2.3.4",
            "the POINTED root's [workspace.package] version must win"
        );
    }

    #[test]
    fn read_app_meta_version_falls_back_without_any_workspace() {
        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"app\"\nversion.workspace = true\n",
        )
        .unwrap();
        let meta = read_app_meta(tmp.path()).unwrap();
        assert_eq!(
            meta.version, "0.1.0",
            "no resolvable workspace version keeps the documented fallback"
        );
    }

    #[test]
    fn read_app_meta_defaults_lib_ident_to_underscored_package_name() {
        let tmp = app_dir("my-app");
        let meta = read_app_meta(tmp.path()).unwrap();
        assert_eq!(meta.lib_ident, "my_app");
    }

    #[test]
    fn read_app_meta_honors_custom_lib_name() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\nname = \"custom_lib\"\n",
        )
        .unwrap();
        let meta = read_app_meta(tmp.path()).unwrap();
        assert_eq!(
            meta.lib_ident, "custom_lib",
            "[lib].name must win over the dash-to-underscore package name"
        );
    }

    #[test]
    fn read_app_meta_honors_custom_lib_path() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\npath = \"src/app_lib.rs\"\n",
        )
        .unwrap();
        let meta = read_app_meta(tmp.path()).unwrap();
        assert_eq!(
            meta.lib_src_path, "src/app_lib.rs",
            "[lib].path must win over the default src/lib.rs"
        );
        // Default when [lib].path is absent.
        let default = app_dir("my-app");
        assert_eq!(
            read_app_meta(default.path()).unwrap().lib_src_path,
            "src/lib.rs"
        );
    }

    #[test]
    fn plan_extracts_serve_into_custom_lib_path() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\npath = \"src/app_lib.rs\"\n\n\
             [features]\nembed-assets = [\"autumn-web/embed-assets\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();

        // serve() lands in the file Cargo actually compiles as the library.
        let lib_action =
            app_src_action(&plan, "app_lib.rs").expect("plan must create the custom-path lib file");
        let Action::CreateIfAbsent { contents, .. } = lib_action else {
            panic!("custom lib file must be a CreateIfAbsent action, got {lib_action:?}");
        };
        assert!(contents.contains("pub async fn serve()"));
        assert!(
            app_src_action(&plan, "lib.rs").is_none(),
            "no stray src/lib.rs may be planned when [lib].path points elsewhere"
        );
        let main_action =
            app_src_action(&plan, "main.rs").expect("plan must rewrite the app src/main.rs");
        let Action::Modify { contents, .. } = main_action else {
            panic!("app main.rs must be a Modify action, got {main_action:?}");
        };
        assert!(contents.contains("my_app::serve().await;"));
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn plan_warns_when_custom_lib_path_file_already_exists() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\npath = \"src/app_lib.rs\"\n\n\
             [features]\nembed-assets = [\"autumn-web/embed-assets\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();
        std::fs::write(tmp.path().join("src/app_lib.rs"), "pub fn helper() {}\n").unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("src/app_lib.rs already exists")),
            "the graceful fallback must name the ACTUAL lib target file, got {:?}",
            plan.warnings
        );
        assert!(
            app_src_action(&plan, "main.rs").is_none(),
            "main.rs must be left untouched on the fallback path"
        );
    }

    #[test]
    fn plan_uses_custom_lib_name_for_all_serve_call_sites() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\nname = \"custom_lib\"\n\n\
             [features]\nembed-assets = [\"autumn-web/embed-assets\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();

        // Shell lib.rs must call custom_lib::serve(), not my_app::serve().
        let shell_lib = plan
            .actions
            .iter()
            .find(|a| {
                a.path()
                    .to_string_lossy()
                    .replace('\\', "/")
                    .ends_with("src-tauri/src/lib.rs")
            })
            .expect("plan must create the shell src/lib.rs");
        let Action::Create { contents, .. } = shell_lib else {
            panic!("shell lib.rs must be a Create action, got {shell_lib:?}");
        };
        assert!(
            contents.contains("block_on(custom_lib::serve())"),
            "shell lib.rs must call the custom [lib] name"
        );
        assert!(
            !contents.contains("my_app::serve()"),
            "shell lib.rs must not call the dash-to-underscore package name"
        );

        // The rewritten app main.rs must call custom_lib::serve() too.
        let main_action =
            app_src_action(&plan, "main.rs").expect("plan must rewrite the app src/main.rs");
        let Action::Modify { contents, .. } = main_action else {
            panic!("app main.rs must be a Modify action, got {main_action:?}");
        };
        assert!(
            contents.contains("custom_lib::serve().await;"),
            "thin main.rs must call the custom [lib] name"
        );
    }

    #[test]
    fn extraction_reruns_silently_with_custom_lib_name() {
        // Re-run detection matches on `<lib_ident>::serve()` — with a custom
        // [lib] name the already-extracted thin main.rs must be recognised.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [lib]\nname = \"custom_lib\"\n\n\
             [features]\nembed-assets = [\"autumn-web/embed-assets\"]\n",
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(
            tmp.path().join("src/main.rs"),
            render_thin_app_main_rs("custom_lib"),
        )
        .unwrap();
        std::fs::write(tmp.path().join("src/lib.rs"), "pub async fn serve() {}\n").unwrap();

        let plan = plan_tauri_mobile(tmp.path(), TauriMobileOptions::default()).unwrap();
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
        assert!(app_src_action(&plan, "main.rs").is_none());
    }

    #[test]
    fn guard_refuses_desktop_leftovers() {
        let tmp = app_dir("my-app");
        let tauri = tmp.path().join("src-tauri");
        std::fs::create_dir_all(&tauri).unwrap();
        std::fs::write(tauri.join("stage-sidecar.sh"), "#!/bin/sh\n").unwrap();

        let err = ensure_no_other_mode_scaffold(tmp.path())
            .unwrap_err()
            .to_string();
        assert!(err.contains("desktop (sidecar)"), "got: {err}");
        assert!(err.contains("src-tauri/stage-sidecar.sh"), "got: {err}");
        assert!(err.contains("autumn destroy tauri"), "got: {err}");
    }

    #[test]
    fn guard_refuses_thin_client_leftovers() {
        let tmp = app_dir("my-app");
        let caps = tmp.path().join("src-tauri").join("capabilities");
        std::fs::create_dir_all(&caps).unwrap();
        std::fs::write(caps.join("remote-app.json"), "{}\n").unwrap();

        let err = ensure_no_other_mode_scaffold(tmp.path())
            .unwrap_err()
            .to_string();
        assert!(err.contains("thin-client"), "got: {err}");
        assert!(
            err.contains("src-tauri/capabilities/remote-app.json"),
            "got: {err}"
        );
        assert!(
            err.contains("autumn destroy tauri --remote-url"),
            "got: {err}"
        );
    }

    #[test]
    fn guard_allows_clean_tree_and_same_mode_regenerate() {
        // No src-tauri/ at all.
        let clean = app_dir("my-app");
        assert!(ensure_no_other_mode_scaffold(clean.path()).is_ok());

        // An existing MOBILE scaffold (same mode) carries none of the other
        // modes' marker files, so a --force regenerate keeps working.
        let mobile = app_dir("my-app");
        let tauri = mobile.path().join("src-tauri");
        std::fs::create_dir_all(tauri.join("src")).unwrap();
        std::fs::write(
            tauri.join("tauri.conf.json"),
            render_mobile_tauri_conf("my-app", "0.1.0"),
        )
        .unwrap();
        std::fs::write(
            tauri.join("Cargo.toml"),
            render_mobile_cargo_toml("my-app", true, None),
        )
        .unwrap();
        std::fs::write(
            tauri.join("src").join("lib.rs"),
            render_mobile_lib_rs("my-app", "my_app", false),
        )
        .unwrap();
        assert!(
            ensure_no_other_mode_scaffold(mobile.path()).is_ok(),
            "same-mode regenerate must not be blocked by the guard"
        );
    }

    #[test]
    fn prerequisites_mention_mobile_toolchains_and_docs() {
        let prereqs = render_mobile_prerequisites(TauriMobileOptions::default());
        assert!(prereqs.contains("tauri-cli"));
        assert!(prereqs.contains("ios"));
        assert!(prereqs.contains("android"));
        assert!(prereqs.contains("tauri-mobile-in-process"));
        assert!(
            !prereqs.contains("AUTUMN_SYNC__REMOTE_URL"),
            "without --offline-sync the prerequisites must not mention sync"
        );
    }

    // ── --offline-sync (issue #1508) ───────────────────────────────────────

    const OFFLINE: TauriMobileOptions = TauriMobileOptions { offline_sync: true };

    /// An app dir whose Cargo.toml matches the stock scaffold's dependency
    /// and feature shape (what `plan_app_offline_sync_feature` anchors on).
    fn stock_app_dir(name: &str) -> TempDir {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            format!(
                "[package]\nname = \"{name}\"\nversion = \"0.2.3\"\n\n\
                 [dependencies]\nautumn-web = \"0.9.1\"\n\n\
                 [features]\ndefault = [\"flash\"]\nflash = [\"autumn-web/flash\"]\n\
                 embed-assets = [\"autumn-web/embed-assets\"]\n"
            ),
        )
        .unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        tmp
    }

    #[test]
    fn offline_cargo_toml_adds_matching_autumn_web_dependency() {
        let mut plan = Plan::new(Path::new("."));
        let tmp = stock_app_dir("my-app");
        let dep = shell_autumn_web_dep(tmp.path(), &mut plan);
        let toml_src = render_mobile_cargo_toml("my-app", true, Some(&dep));
        assert!(
            toml_src.contains(r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#),
            "the shell must depend on autumn-web (offline-sync) at the app's requirement"
        );
        assert!(
            !toml_src.contains("[patch.crates-io]"),
            "an unpatched registry dep must not grow a patch section"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");
        // Without offline sync the dependency (and any sync trace) is absent.
        let no_sync = render_mobile_cargo_toml("my-app", true, None);
        assert!(!no_sync.contains("offline-sync"));
        assert!(!no_sync.contains("autumn-web ="));
    }

    /// Write `deps` verbatim under `[dependencies]` (plus optional extra
    /// top-level TOML) and resolve the shell's autumn-web dependency.
    fn shell_dep_for(deps: &str, extra: &str) -> (ShellAutumnWebDep, Vec<String>) {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            format!(
                "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
                 [dependencies]\n{deps}\n{extra}"
            ),
        )
        .unwrap();
        let mut plan = Plan::new(tmp.path());
        let dep = shell_autumn_web_dep(tmp.path(), &mut plan);
        (dep, plan.warnings)
    }

    #[test]
    fn lexical_relative_handles_ancestors_dotdots_and_foreign_roots() {
        use std::path::Path;
        // Ancestor workspace root → up out of src-tauri/ and the app dir.
        assert_eq!(
            lexical_relative(
                Path::new("/ws/vendor/autumn"),
                Path::new("/ws/app/src-tauri")
            ),
            Some(std::path::PathBuf::from("../../vendor/autumn"))
        );
        // `..` chains in the declared path fold before diffing.
        assert_eq!(
            lexical_relative(
                Path::new("/ws/vendor/../autumn/./core"),
                Path::new("/ws/app/src-tauri")
            ),
            Some(std::path::PathBuf::from("../../autumn/core"))
        );
        // Identical directories resolve to `.`.
        assert_eq!(
            lexical_relative(Path::new("/ws/app"), Path::new("/ws/app")),
            Some(std::path::PathBuf::from("."))
        );
        // Nested target below the base needs no `..` at all.
        assert_eq!(
            lexical_relative(
                Path::new("/ws/app/src-tauri/gen"),
                Path::new("/ws/app/src-tauri")
            ),
            Some(std::path::PathBuf::from("gen"))
        );
        // A `..` escaping the root cannot be folded lexically.
        assert_eq!(
            lexical_relative(Path::new("/../etc"), Path::new("/ws")),
            None
        );
    }

    #[test]
    fn offline_shell_dep_mirrors_path_source_relative_to_src_tauri() {
        let (dep, warnings) = shell_dep_for(
            "autumn-web = { path = \"../autumn\", version = \"0.9.1\" }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", path = "../../autumn", features = ["offline-sync"] }"#,
            "a relative path dep must be recomputed for src-tauri/ (one level deeper)"
        );
        assert!(dep.patch_entry.is_none());
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn offline_shell_dep_normalizes_backslash_relative_paths() {
        // Windows-style separators in the app's OWN manifest (a TOML
        // literal string like path = 'vendor\autumn') must not leak into
        // the generated src-tauri/Cargo.toml: emitted inside a BASIC
        // string they become invalid escapes (\a), and where they happen
        // to escape cleanly they are platform-specific checked-in paths.
        let (dep, warnings) = shell_dep_for(r"autumn-web = { path = 'vendor\autumn' }", "");
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../vendor/autumn", features = ["offline-sync"] }"#,
            "the direct-relative branch must normalize separators"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
        let toml_src = render_mobile_cargo_toml("my-app", true, Some(&dep));
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");

        // Same for a mirrored [patch.crates-io] entry.
        let (dep, warnings) = shell_dep_for(
            "autumn-web = \"0.9.1\"",
            "\n[patch.crates-io]\nautumn-web = { path = 'vendor\\autumn' }\n",
        );
        let patch = dep
            .patch_entry
            .clone()
            .expect("the backslashed patch must still be mirrored");
        assert!(
            patch.contains(r#"autumn-web = { path = "../vendor/autumn" }"#),
            "the patch mirror must normalize separators, got: {patch}"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
        let toml_src = render_mobile_cargo_toml("my-app", true, Some(&dep));
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");

        // Forward-slash input stays byte-identical (regression).
        let (dep, warnings) = shell_dep_for("autumn-web = { path = \"vendor/autumn\" }", "");
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../vendor/autumn", features = ["offline-sync"] }"#,
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn offline_shell_dep_mirrors_absolute_path_source() {
        let (dep, warnings) = shell_dep_for("autumn-web = { path = \"/src/autumn/autumn\" }", "");
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "/src/autumn/autumn", features = ["offline-sync"] }"#,
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn offline_shell_dep_mirrors_git_source_with_rev() {
        let (dep, warnings) = shell_dep_for(
            "autumn-web = { git = \"https://github.com/autumn-foundation/autumn\", rev = \"abc123\" }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { git = "https://github.com/autumn-foundation/autumn", rev = "abc123", features = ["offline-sync"] }"#,
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn offline_shell_dep_preserves_default_features_false() {
        // Feature unification is per dependency edge: a shell edge without
        // `default-features = false` would re-enable the framework's default
        // features across the whole src-tauri build.
        let (dep, warnings) = shell_dep_for(
            "autumn-web = { version = \"0.9.1\", default-features = false, \
             features = [\"maud\"] }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", default-features = false, features = ["offline-sync", "postgres"] }"#,
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // Path deps preserve it too, and the pre-2021 `default_features`
        // spelling cargo still accepts is recognized.
        let (dep, _) = shell_dep_for(
            "autumn-web = { path = \"../autumn\", default_features = false }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../../autumn", default-features = false, features = ["offline-sync", "postgres"] }"#,
        );

        // And an edge that does NOT opt out stays unchanged.
        let (dep, _) = shell_dep_for("autumn-web = { version = \"0.9.1\" }", "");
        assert!(
            !dep.dep_entry.contains("default-features"),
            "got: {}",
            dep.dep_entry
        );
    }

    #[test]
    fn offline_shell_dep_resolves_renamed_dependency_by_package() {
        // Apps may rename the framework dep: the source must be resolved by
        // PACKAGE, and the shell edge is emitted under the real package name.
        let (dep, warnings) = shell_dep_for(
            "autumn = { package = \"autumn-web\", version = \"0.9.1\" }",
            "",
        );
        assert_eq!(
            dep.dep_entry, r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#,
            "a renamed registry dep must still resolve (not fall back)"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        let (dep, warnings) = shell_dep_for(
            "autumn = { package = \"autumn-web\", path = \"../autumn\" }",
            "",
        );
        assert_eq!(
            dep.dep_entry, r#"autumn-web = { path = "../../autumn", features = ["offline-sync"] }"#,
            "a renamed path dep must mirror its source"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");
    }

    #[test]
    fn offline_feature_edit_targets_the_actual_dependency_key() {
        // Cargo feature syntax names the dependency KEY: with a renamed dep
        // the edit must reference `<key>/offline-sync`, or cargo rejects the
        // manifest outright.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn = { package = \"autumn-web\", version = \"0.9.1\" }\n\n\
             [features]\ndefault = [\"flash\"]\nflash = [\"autumn/flash\"]\n\
             embed-assets = [\"autumn/embed-assets\"]\n",
        )
        .unwrap();
        let mut plan = Plan::new(tmp.path());
        plan_app_offline_sync_feature(tmp.path(), &mut plan);
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
        let edited = plan
            .actions
            .iter()
            .find_map(|a| match a {
                Action::Modify { path, contents } if path.ends_with("Cargo.toml") => {
                    Some(contents.clone())
                }
                _ => None,
            })
            .expect("the feature edit must be planned");
        assert!(
            edited.contains(r#"offline-sync = ["autumn/offline-sync"]"#),
            "the feature must reference the RENAMED dependency key, got:\n{edited}"
        );
        assert!(
            !edited.contains(r#"["autumn-web/offline-sync"]"#),
            "the package name is not a valid feature dependency here"
        );
    }

    #[test]
    fn offline_shell_dep_mirrors_crates_io_patch_into_shell_manifest() {
        // The common test-harness / local-development shape: a registry dep
        // plus a [patch.crates-io] path override. The shell is its own
        // [workspace], so the patch must be mirrored explicitly.
        let (dep, warnings) = shell_dep_for(
            "autumn-web = \"0.9.1\"",
            "\n[patch.crates-io]\nautumn-web = { path = \"/src/autumn/autumn\" }\n",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#,
        );
        let patch = dep
            .patch_entry
            .clone()
            .expect("the crates-io patch must be mirrored");
        assert!(patch.contains("[patch.crates-io]"), "got: {patch}");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/autumn/autumn" }"#),
            "got: {patch}"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // And the rendered manifest carries the section and stays valid TOML.
        let toml_src = render_mobile_cargo_toml("my-app", true, Some(&dep));
        assert!(toml_src.contains("[patch.crates-io]"));
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");
    }

    #[test]
    fn offline_shell_dep_default_features_across_workspace_inheritance() {
        // Build a workspace whose root declares the dep, with the member
        // inheriting it via `workspace = true` plus `member_extra` keys.
        fn workspace_dep(workspace_entry: &str, member_extra: &str) -> ShellAutumnWebDep {
            let tmp = TempDir::new().unwrap();
            std::fs::write(
                tmp.path().join("Cargo.toml"),
                format!(
                    "[workspace]\nmembers = [\"app\"]\n\n\
                     [workspace.dependencies]\nautumn-web = {workspace_entry}\n"
                ),
            )
            .unwrap();
            let app = tmp.path().join("app");
            std::fs::create_dir_all(&app).unwrap();
            std::fs::write(
                app.join("Cargo.toml"),
                format!(
                    "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
                     [dependencies]\nautumn-web = {{ workspace = true{member_extra} }}\n"
                ),
            )
            .unwrap();
            let mut plan = Plan::new(&app);
            let dep = shell_autumn_web_dep(&app, &mut plan);
            assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
            dep
        }

        // Member-level opt-out survives resolution even when the workspace
        // entry leaves defaults on (previously erased by the inheritance
        // walk replacing the member table).
        let dep = workspace_dep(r#"{ version = "0.9.1" }"#, ", default-features = false");
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", default-features = false, features = ["offline-sync", "postgres"] }"#,
        );
        // Legacy spelling too.
        let dep = workspace_dep(r#"{ version = "0.9.1" }"#, ", default_features = false");
        assert!(
            dep.dep_entry.contains("default-features = false"),
            "got: {}",
            dep.dep_entry
        );

        // Member sets nothing: the workspace-level value wins.
        let dep = workspace_dep(r#"{ version = "0.9.1", default-features = false }"#, "");
        assert!(
            dep.dep_entry.contains("default-features = false"),
            "workspace-level opt-out must apply, got: {}",
            dep.dep_entry
        );

        // Member re-enables defaults over a workspace opt-out — Cargo's
        // documented inheritance rule.
        let dep = workspace_dep(
            r#"{ version = "0.9.1", default-features = false }"#,
            ", default-features = true",
        );
        assert!(
            !dep.dep_entry.contains("default-features"),
            "a member re-enable must win over the workspace opt-out, got: {}",
            dep.dep_entry
        );

        // Neither side opts out: no default-features on the shell edge.
        let dep = workspace_dep(r#"{ version = "0.9.1" }"#, "");
        assert!(
            !dep.dep_entry.contains("default-features"),
            "got: {}",
            dep.dep_entry
        );
    }

    #[test]
    fn offline_feature_edit_requires_default_enablement() {
        fn manifest(features: &str) -> (TempDir, std::path::PathBuf) {
            let tmp = TempDir::new().unwrap();
            let path = tmp.path().join("Cargo.toml");
            std::fs::write(
                &path,
                format!(
                    "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
                     [dependencies]\nautumn-web = \"0.9.1\"\n\n\
                     [features]\n{features}"
                ),
            )
            .unwrap();
            (tmp, path)
        }
        fn planned_edit(tmp: &TempDir) -> (Option<String>, Vec<String>) {
            let mut plan = Plan::new(tmp.path());
            plan_app_offline_sync_feature(tmp.path(), &mut plan);
            let edit = plan.actions.iter().find_map(|a| match a {
                Action::Modify { contents, .. } => Some(contents.clone()),
                _ => None,
            });
            (edit, plan.warnings)
        }

        // Feature present AND directly in default: wired — untouched,
        // silent (byte-identical, since no action is planned at all).
        let (tmp, _) = manifest(
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(edit.is_none(), "wired manifests must stay untouched");
        assert!(warnings.is_empty(), "got {warnings:?}");

        // Enabled TRANSITIVELY through another default feature: also wired.
        let (tmp, _) = manifest(
            "default = [\"flash\", \"full\"]\nflash = []\n\
             full = [\"offline-sync\"]\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(
            edit.is_none(),
            "transitive default enablement counts as wired"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // A default entry naming only the DEP feature does not enable the
        // crate's own cfg — not wired.
        let (tmp, _) = manifest(
            "default = [\"flash\", \"autumn-web/offline-sync\"]\nflash = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(
            edit.is_some() || !warnings.is_empty(),
            "a dep-feature default entry must not count as wired"
        );

        // Feature present but NOT in default, stock default line: only the
        // default line is edited; the feature is not re-declared.
        let (tmp, _) = manifest(
            "default = [\"flash\"]\nflash = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("the stock default line must gain the feature");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
        assert_eq!(
            edited.matches("offline-sync = [").count(),
            1,
            "the existing feature declaration must not be duplicated:\n{edited}"
        );

        // Feature present, NOT in default, customised default line: loud
        // warning instead of a guessed rewrite; manifest untouched.
        let (tmp, _) = manifest(
            "default = [\"flash\", \"extra\"]\nflash = []\nextra = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(
            edit.is_none(),
            "a customised default line is never rewritten"
        );
        assert!(
            warnings.iter().any(|w| w.contains(
                "`default` \
                 doesn't enable it"
            ) || w.contains("doesn't enable it")),
            "got {warnings:?}"
        );
    }

    #[test]
    fn offline_feature_detection_survives_spacing_and_layout_variants() {
        // Detection must key on the parsed [features] TABLE, not on the
        // exact `offline-sync = [` byte sequence: `offline-sync=[]` (no
        // spaces) or a multiline array are the same manifest to cargo, and
        // a substring miss would route them into the fresh-insert branch —
        // which would write a DUPLICATE `offline-sync` key that cargo
        // rejects outright.
        fn manifest(features: &str) -> TempDir {
            let tmp = TempDir::new().unwrap();
            std::fs::write(
                tmp.path().join("Cargo.toml"),
                format!(
                    "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
                     [dependencies]\nautumn-web = \"0.9.1\"\n\n\
                     [features]\n{features}"
                ),
            )
            .unwrap();
            tmp
        }
        fn planned_edit(tmp: &TempDir) -> (Option<String>, Vec<String>) {
            let mut plan = Plan::new(tmp.path());
            plan_app_offline_sync_feature(tmp.path(), &mut plan);
            let edit = plan.actions.iter().find_map(|a| match a {
                Action::Modify { contents, .. } => Some(contents.clone()),
                _ => None,
            });
            (edit, plan.warnings)
        }

        // No-spaces spelling, already wired: silent no-op, no duplicate.
        let tmp = manifest(
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync=[\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(
            edit.is_none(),
            "`offline-sync=[…]` (no spaces) must be detected as already \
             defined, got:\n{edit:?}"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // No-spaces spelling, not in default: only the stock default line
        // gains the feature — the declaration is not re-inserted.
        let tmp = manifest(
            "default = [\"flash\"]\nflash = []\n\
             offline-sync=[\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("the stock default line must gain the feature");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
        // A duplicated key would fail to parse — the sharpest duplicate check.
        toml::from_str::<toml::Value>(&edited)
            .expect("the edited manifest must stay valid TOML (no duplicate keys)");
        assert_eq!(
            edited.matches("offline-sync=[").count() + edited.matches("offline-sync = [").count(),
            1,
            "the existing declaration must not be duplicated:\n{edited}"
        );

        // Multiline array form, not in default: same — detected, no
        // duplicate declaration inserted.
        let tmp = manifest(
            "default = [\"flash\"]\nflash = []\n\
             offline-sync = [\n    \"autumn-web/offline-sync\",\n]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("the stock default line must gain the feature");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
        toml::from_str::<toml::Value>(&edited)
            .expect("the edited manifest must stay valid TOML (no duplicate keys)");

        // Regression: a manifest WITHOUT the feature still gets the fresh
        // insert (detection must not report false positives either).
        let tmp = manifest("default = [\"flash\"]\nflash = []\n");
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("an absent feature must still be inserted");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"offline-sync = ["autumn-web/offline-sync"]"#),
            "got:\n{edited}"
        );
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
    }

    #[test]
    fn offline_shell_dep_mirrors_alternate_registry_selection() {
        // A private-registry dep must not collapse into a bare crates.io
        // version requirement on the shell edge.
        let (dep, warnings) = shell_dep_for(
            "autumn-web = { version = \"0.9.1\", registry = \"internal\" }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", registry = "internal", features = ["offline-sync"] }"#,
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // Combined with a default-features opt-out, both survive.
        let (dep, _) = shell_dep_for(
            "autumn-web = { version = \"0.9.1\", registry = \"internal\", default-features = false }",
            "",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", registry = "internal", default-features = false, features = ["offline-sync", "postgres"] }"#,
        );

        // Workspace-inherited entries carry their registry key through the
        // inheritance walk (members cannot override it, so the resolved
        // workspace table is authoritative).
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n\n\
             [workspace.dependencies]\n\
             autumn-web = { version = \"0.9.1\", registry = \"internal\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = { workspace = true }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", registry = "internal", features = ["offline-sync"] }"#,
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);

        // No registry key: output stays byte-identical to before.
        let (dep, _) = shell_dep_for("autumn-web = { version = \"0.9.1\" }", "");
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#,
        );
    }

    #[test]
    fn offline_shell_dep_mirrors_renamed_crates_io_patch() {
        // A renamed patch entry is just as valid as the literal key: it
        // must be matched by its `package` field and mirrored whole —
        // key, rename, and source.
        let (dep, warnings) = shell_dep_for(
            "autumn-web = \"0.9.1\"",
            "\n[patch.crates-io]\naw_local = { package = \"autumn-web\", path = \"/src/autumn/autumn\" }\n",
        );
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#,
        );
        let patch = dep
            .patch_entry
            .clone()
            .expect("the renamed patch must be mirrored, not silently dropped");
        assert!(
            patch.contains(r#"aw_local = { package = "autumn-web", path = "/src/autumn/autumn" }"#),
            "the entry must be mirrored whole (key + package + source), got: {patch}"
        );
        assert!(warnings.is_empty(), "got {warnings:?}");

        // And the rendered manifest stays valid TOML.
        let toml_src = render_mobile_cargo_toml("my-app", true, Some(&dep));
        toml::from_str::<toml::Value>(&toml_src).expect("generated Cargo.toml must parse");
    }

    #[test]
    fn offline_shell_dep_mirrors_renamed_patch_from_ancestor_workspace() {
        // The renamed-patch lookup walks ancestor manifests exactly like
        // the literal-key one; a relative patch path declared at the
        // workspace root is absolutized against that root.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n\n\
             [patch.crates-io]\naw_local = { package = \"autumn-web\", path = \"vendor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the ancestor workspace's renamed patch must be mirrored");
        assert!(
            patch
                .contains(r#"aw_local = { package = "autumn-web", path = "../../vendor/autumn" }"#),
            "the mirrored patch path must be relative to src-tauri/, got: {patch}"
        );
        assert!(
            !patch.contains(&tmp.path().display().to_string()),
            "no machine-specific absolute prefix may leak into the manifest"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_member_local_patch_is_skipped_with_a_warning() {
        // Cargo ignores [patch] tables outside the workspace root — a
        // member-local patch must NOT be mirrored (the app never builds
        // against it), and the skip must be explained.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/ignored/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        assert!(
            dep.patch_entry.is_none(),
            "a member-local patch cargo ignores must not be mirrored, got {:?}",
            dep.patch_entry
        );
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("outside the workspace root")),
            "the skip must be explained, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn offline_root_patch_wins_over_a_stale_member_local_one() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/effective/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/stale/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the workspace root's patch must be mirrored");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/effective/autumn" }"#),
            "the EFFECTIVE (root) patch must win, got: {patch}"
        );
        assert!(
            !patch.contains("/src/stale/autumn"),
            "the ignored member-local patch must not leak in: {patch}"
        );
    }

    #[test]
    fn offline_excluded_member_uses_its_own_patch_table() {
        // An ancestor workspace whose `exclude` names the app makes the app
        // standalone: its own patch table is the effective one.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = []\nexclude = [\"app\"]\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/standalone/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("an excluded (standalone) app's own patch must be mirrored");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/standalone/autumn" }"#),
            "got: {patch}"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_exclude_entries_match_as_directory_prefixes() {
        // Cargo treats `workspace.exclude` entries as DIRECTORY PREFIXES: a
        // package anywhere under an excluded dir is excluded and becomes
        // its own workspace. The common layout — root
        // `exclude = ["examples"]` with the app at examples/mobile — must
        // therefore use the APP's own manifest, not adopt the excluding
        // ancestor and mirror its patches.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = []\nexclude = [\"examples\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/ancestor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("examples").join("mobile");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/own/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the prefix-excluded (standalone) app's own patch must be mirrored");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/own/autumn" }"#),
            "got: {patch}"
        );
        assert!(
            !patch.contains("/src/ancestor/autumn"),
            "the excluding ancestor's patch must not leak in: {patch}"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_exclude_prefix_match_respects_component_boundaries() {
        // `exclude = ["examples"]` must NOT exclude examples-extra/mobile —
        // the comparison is whole path components, not a string prefix. The
        // app IS a member of the ancestor workspace, so the ancestor's
        // patch table governs and the member-local one is skipped with the
        // established loud warning.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"examples-extra/mobile\"]\nexclude = [\"examples\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/ancestor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("examples-extra").join("mobile");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/member-local/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the ancestor root's patch must be mirrored for a real member");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/ancestor/autumn" }"#),
            "examples-extra must not be swallowed by the `examples` exclude \
             entry, got: {patch}"
        );
        assert!(
            !patch.contains("/src/member-local/autumn"),
            "the ignored member-local patch must not leak in: {patch}"
        );
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("Cargo ignores [patch] tables outside the workspace root")),
            "the member-local patch skip must warn, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn offline_exclusion_by_an_intermediate_ancestor_walks_to_the_outer_root() {
        // Repo root `members = ["mid/app"]` while `mid` declares its own
        // `[workspace]` excluding `app`: exclusion at the intermediate level
        // only removes the app from MID's workspace, not from the repo
        // root's membership — Cargo reports the repo root as
        // `workspace_root`, so the ROOT's patch table is the effective one.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"mid/app\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/outer/autumn\" }\n",
        )
        .unwrap();
        let mid = tmp.path().join("mid");
        std::fs::create_dir_all(&mid).unwrap();
        std::fs::write(
            mid.join("Cargo.toml"),
            "[workspace]\nmembers = []\nexclude = [\"app\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/intermediate/autumn\" }\n",
        )
        .unwrap();
        let app = mid.join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the OUTER root's patch must be mirrored past the excluding mid");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/outer/autumn" }"#),
            "got: {patch}"
        );
        assert!(
            !patch.contains("/src/intermediate/autumn"),
            "the excluding intermediate's patch must not leak in: {patch}"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_exclusion_with_no_outer_workspace_is_still_standalone() {
        // Regression for the continue-the-walk fix: when the excluding
        // ancestor is the ONLY workspace above the app, the walk finds no
        // outer root and the app remains standalone — its own patch table
        // stays the effective one (the pre-existing behavior).
        let tmp = TempDir::new().unwrap();
        let mid = tmp.path().join("mid");
        std::fs::create_dir_all(&mid).unwrap();
        std::fs::write(
            mid.join("Cargo.toml"),
            "[workspace]\nmembers = []\nexclude = [\"app\"]\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/intermediate/autumn\" }\n",
        )
        .unwrap();
        let app = mid.join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = \"0.9.1\"\n\n\
             [patch.crates-io]\nautumn-web = { path = \"/src/standalone/autumn\" }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        let patch = dep
            .patch_entry
            .expect("the excluded (standalone) app's own patch must be mirrored");
        assert!(
            patch.contains(r#"autumn-web = { path = "/src/standalone/autumn" }"#),
            "got: {patch}"
        );
        assert!(
            !patch.contains("/src/intermediate/autumn"),
            "the excluding ancestor's patch must not leak in: {patch}"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_shell_dep_resolves_workspace_inherited_path_dep() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"app\"]\n\n\
             [workspace.dependencies]\nautumn-web = { path = \"vendor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
             [dependencies]\nautumn-web = { workspace = true }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        // Declared in the workspace root: re-relativized against the
        // generated src-tauri/ — src-tauri/Cargo.toml is checked in, so an
        // absolute path would break every other checkout.
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../../vendor/autumn", features = ["offline-sync"] }"#,
        );
        assert!(
            !dep.dep_entry.contains(&tmp.path().display().to_string()),
            "no machine-specific absolute prefix may leak into the manifest"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_shell_dep_follows_package_workspace_pointer_for_inheritance() {
        // An explicit `[package] workspace = "…"` pointer names the app's
        // workspace root directly — the root need not be an ancestor of the
        // app at all, so an ancestor-only [workspace.dependencies] scan
        // never finds it and --offline-sync would fall back to a bare
        // registry edge instead of mirroring the inherited path source.
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");
        std::fs::create_dir_all(&ws).unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            "[workspace]\nmembers = []\n\n\
             [workspace.dependencies]\nautumn-web = { path = \"vendor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\nworkspace = \"../ws\"\n\n\
             [dependencies]\nautumn-web = { workspace = true }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        // vendor/autumn resolves against the POINTED root (tmp/ws), then
        // re-relativizes against the generated tmp/app/src-tauri/.
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../../ws/vendor/autumn", features = ["offline-sync"] }"#,
        );
        assert!(
            !dep.dep_entry.contains(&tmp.path().display().to_string()),
            "no machine-specific absolute prefix may leak into the manifest"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_shell_dep_pointer_skips_a_nearer_excluding_workspace() {
        // A pointer may deliberately skip PAST a nearer workspace root (the
        // Cargo-legal layout requires that nearer root to exclude the app).
        // The inheritance scan must resolve against the POINTED root, not
        // stop at the nearer manifest's [workspace.dependencies] entry —
        // otherwise the shell mirrors a framework source the app never
        // builds against.
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[workspace]\nmembers = [\"mid/app\"]\n\n\
             [workspace.dependencies]\nautumn-web = { path = \"framework/autumn\" }\n",
        )
        .unwrap();
        let mid = tmp.path().join("mid");
        std::fs::create_dir_all(&mid).unwrap();
        std::fs::write(
            mid.join("Cargo.toml"),
            "[workspace]\nmembers = []\nexclude = [\"app\"]\n\n\
             [workspace.dependencies]\nautumn-web = { path = \"wrong/autumn\" }\n",
        )
        .unwrap();
        let app = mid.join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\nworkspace = \"../..\"\n\n\
             [dependencies]\nautumn-web = { workspace = true }\n",
        )
        .unwrap();
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../../../framework/autumn", features = ["offline-sync"] }"#,
            "the POINTED root's entry must win over the nearer excluding root's"
        );
        assert!(
            !dep.dep_entry.contains("wrong"),
            "the skipped nearer entry must not leak in, got: {}",
            dep.dep_entry
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }

    #[test]
    fn offline_pointer_root_resolves_renamed_inherited_dep_key() {
        // A `[package] workspace = "…"` pointer plus a RENAMED inherited
        // dep: the dep-key resolution must read the pointed root's
        // [workspace.dependencies] to learn that `autumn` is the
        // autumn-web package. An ancestor-only walk misses it: the key
        // mis-resolves to "autumn-web", the member lookup finds no such
        // dependency (falling back to a registry edge), and the feature
        // edit emits `autumn-web/offline-sync` — a spelling cargo rejects
        // for a renamed dependency.
        let tmp = TempDir::new().unwrap();
        let ws = tmp.path().join("ws");
        std::fs::create_dir_all(&ws).unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            "[workspace]\nmembers = []\n\n\
             [workspace.dependencies]\n\
             autumn = { package = \"autumn-web\", path = \"vendor/autumn\" }\n",
        )
        .unwrap();
        let app = tmp.path().join("app");
        std::fs::create_dir_all(&app).unwrap();
        std::fs::write(
            app.join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\nworkspace = \"../ws\"\n\n\
             [dependencies]\nautumn = { workspace = true }\n\n\
             [features]\ndefault = [\"flash\"]\nflash = []\n",
        )
        .unwrap();

        // Shell edge: mirrored from the pointed root — no registry fallback.
        let mut plan = Plan::new(&app);
        let dep = shell_autumn_web_dep(&app, &mut plan);
        assert_eq!(
            dep.dep_entry,
            r#"autumn-web = { path = "../../ws/vendor/autumn", features = ["offline-sync"] }"#,
            "the renamed inherited dep must resolve through the pointed root"
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);

        // Feature entry: names the ALIAS key — the only spelling cargo
        // accepts for a renamed dependency.
        let mut plan = Plan::new(&app);
        plan_app_offline_sync_feature(&app, &mut plan);
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
        let edited = plan
            .actions
            .iter()
            .find_map(|a| match a {
                Action::Modify { contents, .. } => Some(contents.clone()),
                _ => None,
            })
            .expect("the feature edit must be planned");
        assert!(
            edited.contains(r#"offline-sync = ["autumn/offline-sync"]"#),
            "the feature must reference the RENAMED dependency key, got:\n{edited}"
        );
        assert!(
            !edited.contains(r#"["autumn-web/offline-sync"]"#),
            "the package name is not a valid feature dependency here, got:\n{edited}"
        );
    }

    #[test]
    #[allow(clippy::too_many_lines)] // one linear case list, clearest unsplit
    fn offline_feature_wired_check_requires_dep_propagation() {
        // A declared `offline-sync` feature only counts as wired when it
        // actually ENABLES `{dep_key}/offline-sync` (directly or through
        // another own-crate feature): serve()'s sync code compiles under
        // cfg(feature = "offline-sync") but calls autumn_web::sync, which
        // only exists when the dependency's feature is on — so e.g.
        // `offline-sync = []` satisfies the cfg while guaranteeing a build
        // failure.
        fn manifest(deps: &str, features: &str) -> TempDir {
            let tmp = TempDir::new().unwrap();
            std::fs::write(
                tmp.path().join("Cargo.toml"),
                format!(
                    "[package]\nname = \"my-app\"\nversion = \"0.2.3\"\n\n\
                     [dependencies]\n{deps}\n\n\
                     [features]\n{features}"
                ),
            )
            .unwrap();
            tmp
        }
        fn planned_edit(tmp: &TempDir) -> (Option<String>, Vec<String>) {
            let mut plan = Plan::new(tmp.path());
            plan_app_offline_sync_feature(tmp.path(), &mut plan);
            let edit = plan.actions.iter().find_map(|a| match a {
                Action::Modify { contents, .. } => Some(contents.clone()),
                _ => None,
            });
            (edit, plan.warnings)
        }
        const STOCK_DEP: &str = "autumn-web = \"0.9.1\"";

        // Empty declaration, default-enabled: the anchored patch fills in
        // exactly the dep entry; the default line is untouched.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\", \"offline-sync\"]\nflash = []\noffline-sync = []\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("an empty offline-sync declaration must be patched");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"offline-sync = ["autumn-web/offline-sync"]"#),
            "got:\n{edited}"
        );
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "the already-correct default line must stay untouched:\n{edited}"
        );
        toml::from_str::<toml::Value>(&edited).expect("edited manifest must stay valid TOML");

        // Empty declaration AND missing from default: both anchored
        // patches land in one edit.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\"]\nflash = []\noffline-sync = []\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("both fixes must be planned");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"offline-sync = ["autumn-web/offline-sync"]"#)
                && edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
        toml::from_str::<toml::Value>(&edited).expect("edited manifest must stay valid TOML");

        // A non-empty, non-propagating array is a customised feature: loud
        // warning naming the missing entry, never a guessed rewrite.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"flash\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(edit.is_none(), "a customised array is never rewritten");
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("autumn-web/offline-sync")),
            "the warning must name the missing dep entry, got {warnings:?}"
        );

        // Propagating TRANSITIVELY through another own-crate feature:
        // wired, untouched.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"sync-impl\"]\n\
             sync-impl = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(edit.is_none(), "transitive propagation counts as wired");
        assert!(warnings.is_empty(), "got {warnings:?}");

        // The weak dep-feature form propagates too.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"autumn-web?/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(edit.is_none(), "the weak form counts as propagating");
        assert!(warnings.is_empty(), "got {warnings:?}");

        // A RENAMED dep propagates via its alias key — and only via it.
        let tmp = manifest(
            "autumn = { package = \"autumn-web\", version = \"0.9.1\" }",
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"autumn/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(edit.is_none(), "the alias entry counts as propagating");
        assert!(warnings.is_empty(), "got {warnings:?}");
        let tmp = manifest(
            "autumn = { package = \"autumn-web\", version = \"0.9.1\" }",
            "default = [\"flash\", \"offline-sync\"]\nflash = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (_edit, warnings) = planned_edit(&tmp);
        assert!(
            warnings.iter().any(|w| w.contains("autumn/offline-sync")),
            "a package-name entry does not reach the renamed dep's feature, \
             got {warnings:?}"
        );

        // A NON-PROPAGATING feature that is also missing from default must
        // NOT get the default edit: enabling a broken feature by default
        // would turn a previously-compiling `cargo build` into a
        // guaranteed failure. Nothing is edited (stock anchor present or
        // not), and ONE warning covers both required steps.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\"]\nflash = []\n\
             offline-sync = [\"flash\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        assert!(
            edit.is_none(),
            "a broken feature must never be added to `default`, got:\n{edit:?}"
        );
        assert_eq!(warnings.len(), 1, "one warning covers both: {warnings:?}");
        assert!(
            warnings[0].contains("autumn-web/offline-sync")
                && warnings[0].contains("`default` was deliberately left untouched"),
            "the warning must cover the feature fix AND the skipped default \
             edit, got {warnings:?}"
        );

        // Regression (AF): a PROPAGATING feature missing from default
        // still gets the anchored default edit.
        let tmp = manifest(
            STOCK_DEP,
            "default = [\"flash\"]\nflash = []\n\
             offline-sync = [\"autumn-web/offline-sync\"]\n",
        );
        let (edit, warnings) = planned_edit(&tmp);
        let edited = edit.expect("a propagating feature must still be defaulted");
        assert!(warnings.is_empty(), "got {warnings:?}");
        assert!(
            edited.contains(r#"default = ["flash", "offline-sync"]"#),
            "got:\n{edited}"
        );
    }

    #[test]
    fn offline_shell_dep_warns_and_falls_back_when_source_is_unrepresentable() {
        // No autumn-web dependency at all: fall back to the CLI's own version
        // with a loud warning instead of silently inventing a registry edge.
        let (dep, warnings) = shell_dep_for("serde = \"1\"", "");
        assert_eq!(
            dep.dep_entry,
            format!(
                r#"autumn-web = {{ version = "{}", features = ["offline-sync"] }}"#,
                env!("CARGO_PKG_VERSION"),
            ),
        );
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("could not determine the app's autumn-web dependency source")),
            "got {warnings:?}"
        );
    }

    #[test]
    fn offline_shell_dep_warns_when_patch_is_unrepresentable() {
        let (dep, warnings) = shell_dep_for(
            "autumn-web = \"0.9.1\"",
            "\n[patch.crates-io]\nautumn-web = { version = \"0.9.2\" }\n",
        );
        assert!(dep.patch_entry.is_none());
        assert!(
            warnings
                .iter()
                .any(|w| w.contains("[patch.crates-io] override of autumn-web could not")),
            "got {warnings:?}"
        );
    }

    #[test]
    fn offline_lib_rs_wires_store_engine_and_resume_trigger() {
        let lib = render_mobile_lib_rs("my-app", "my_app", true);
        // Local store in the sandbox, exported for the app's routes.
        assert!(lib.contains(r#"let sync_db = data_root.join("sync.db");"#));
        assert!(lib.contains(r#""AUTUMN_SYNC__DB_PATH""#));
        assert!(lib.contains("autumn_web::sync::SyncStore::open(&sync_db)"));
        // Engine on the server runtime, configured from the environment.
        assert!(lib.contains(r#"std::env::var("AUTUMN_SYNC__REMOTE_URL")"#));
        assert!(lib.contains("autumn_web::sync::SyncConfig::new(remote_url)"));
        assert!(lib.contains(".spawn_background(std::time::Duration::from_secs(30))"));
        assert!(lib.contains("start_background_sync(&runtime, sync_db);"));
        // Connectivity-regain trigger through the run-loop callback.
        assert!(lib.contains(".build(tauri::generate_context!())"));
        assert!(lib.contains("tauri::RunEvent::Resumed"));
        assert!(lib.contains("engine.sync_once().await"));
        assert!(lib.contains("docs/guide/tauri-mobile-offline-sync.md"));
        // Offline startup: the direct database URL stays a commented example.
        assert!(!lib.contains("\n    std::env::set_var(\"AUTUMN_DATABASE__URL\""));
    }

    #[test]
    fn offline_lib_rs_sends_the_sync_bearer_token() {
        // Client half of the fail-closed server mount (#1612 review): the
        // engine sends AUTUMN_SYNC__TOKEN as its bearer token, matching the
        // deployment's SYNC_TOKEN — and warns (without aborting: local-first
        // still works) when it is missing.
        let lib = render_mobile_lib_rs("my-app", "my_app", true);
        assert!(lib.contains(r#"std::env::var("AUTUMN_SYNC__TOKEN")"#));
        assert!(lib.contains("config.bearer_token = Some(token)"));
        assert!(
            lib.contains("AUTUMN_SYNC__TOKEN is not set"),
            "a missing client token must be called out at startup"
        );
        // The commented env block documents the pairing without shipping a
        // hard-coded secret.
        assert!(lib.contains(r#"// std::env::set_var("AUTUMN_SYNC__TOKEN", sync_token);"#));
        assert!(!render_mobile_lib_rs("my-app", "my_app", false).contains("AUTUMN_SYNC__TOKEN"));
    }

    /// The CHANGELOG promises the no-flag emission is byte-identical to the
    /// pre-#1508 scaffold; `render_mobile_lib_rs` now assembles the file
    /// from conditionals, so pin the default output byte-for-byte.
    #[test]
    fn default_lib_rs_matches_the_golden_snapshot() {
        let generated = render_mobile_lib_rs("golden-app", "golden_app", false);
        let path = concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/tests/golden/tauri_mobile_default_lib.rs.golden"
        );
        if std::env::var("UPDATE_GOLDEN").is_ok() {
            std::fs::write(path, &generated).expect("write golden");
        }
        let golden = std::fs::read_to_string(path).expect("golden snapshot file");
        assert_eq!(
            generated, golden,
            "the DEFAULT (no --offline-sync) shell lib.rs emission changed. If \
             this is intentional, regenerate the snapshot with \
             `UPDATE_GOLDEN=1 cargo test -p autumn-cli default_lib_rs_matches` \
             and mention the template change in the commit"
        );
    }

    #[test]
    fn lib_rs_without_offline_flag_has_no_sync_wiring() {
        let lib = render_mobile_lib_rs("my-app", "my_app", false);
        assert!(!lib.contains("AUTUMN_SYNC"));
        assert!(!lib.contains("sync_once"));
        assert!(!lib.contains("SYNC_KICK"));
        assert!(
            lib.contains(".run(tauri::generate_context!())"),
            "the default shell must keep the simple run(context) tail"
        );
    }

    #[test]
    fn offline_plan_edits_app_cargo_toml_features() {
        let tmp = stock_app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), OFFLINE).unwrap();
        let cargo_action = plan
            .actions
            .iter()
            .find(|a| {
                a.path().ends_with("Cargo.toml")
                    && !a.path().to_string_lossy().contains("src-tauri")
            })
            .expect("plan must edit the app Cargo.toml");
        let Action::Modify { contents, .. } = cargo_action else {
            panic!("app Cargo.toml must be a Modify action, got {cargo_action:?}");
        };
        assert!(contents.contains(r#"offline-sync = ["autumn-web/offline-sync"]"#));
        assert!(contents.contains(r#"default = ["flash", "offline-sync"]"#));
        toml::from_str::<toml::Value>(contents).expect("edited Cargo.toml must stay valid TOML");
    }

    #[test]
    fn offline_plan_skips_cargo_toml_edit_when_already_wired() {
        let tmp = stock_app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();
        let cargo_path = tmp.path().join("Cargo.toml");
        let wired = read_or_empty(&cargo_path).replace(
            "default = [\"flash\"]",
            "default = [\"flash\", \"offline-sync\"]",
        ) + "offline-sync = [\"autumn-web/offline-sync\"]\n";
        std::fs::write(&cargo_path, wired).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), OFFLINE).unwrap();
        assert!(
            !plan.actions.iter().any(|a| a.path().ends_with("Cargo.toml")
                && !a.path().to_string_lossy().contains("src-tauri")),
            "an already-wired Cargo.toml must not be edited again"
        );
        assert!(plan.warnings.is_empty(), "re-runs must stay silent");
    }

    #[test]
    fn offline_plan_warns_on_customised_cargo_toml_features() {
        // No `default = ["flash"]` anchor — the feature edit must be skipped
        // with a warning, never guessed.
        let tmp = app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), OFFLINE).unwrap();
        assert!(
            plan.warnings
                .iter()
                .any(|w| w.contains("offline-sync") && w.contains("[features]")),
            "must warn with manual steps on a customised Cargo.toml, got {:?}",
            plan.warnings
        );
    }

    #[test]
    fn offline_extraction_mounts_sync_router_in_serve() {
        let tmp = stock_app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), OFFLINE).unwrap();
        let lib_action =
            app_src_action(&plan, "lib.rs").expect("plan must create the app src/lib.rs");
        let Action::CreateIfAbsent { contents, .. } = lib_action else {
            panic!("app lib.rs must be a CreateIfAbsent action, got {lib_action:?}");
        };
        assert!(contents.contains("let app = mount_offline_sync(app).await;"));
        assert!(contents.contains("async fn mount_offline_sync"));
        assert!(contents.contains("PgSyncBackend::new(database_url)"));
        assert!(contents.contains("ensure_schema()"));
        assert!(
            contents.contains(".layer(axum::middleware::from_fn(require_sync_auth)),"),
            "the sync router must be mounted behind the generated auth middleware"
        );
        // The mount call must precede the final run().
        let mount = contents.find("mount_offline_sync(app)").unwrap();
        let run = contents.find(".run()").unwrap();
        assert!(mount < run, "sync mounting must happen before .run()");
    }

    #[test]
    fn offline_extraction_mounts_sync_fail_closed_behind_sync_token() {
        // Review hardening (#1612): a fresh scaffold must never expose an
        // UNAUTHENTICATED /sync — the endpoints trust `device_id` as sent,
        // so an open mount lets any network client read and overwrite every
        // synced row. The generated helper fails closed instead.
        let tmp = stock_app_dir("my-app");
        std::fs::write(tmp.path().join("src/main.rs"), stock_main_rs()).unwrap();

        let plan = plan_tauri_mobile(tmp.path(), OFFLINE).unwrap();
        let lib_action =
            app_src_action(&plan, "lib.rs").expect("plan must create the app src/lib.rs");
        let Action::CreateIfAbsent { contents, .. } = lib_action else {
            panic!("app lib.rs must be a CreateIfAbsent action, got {lib_action:?}");
        };
        // Startup gate: no SYNC_TOKEN → /sync not mounted, with a warning.
        assert!(
            contents.contains(r#"std::env::var("SYNC_TOKEN")"#),
            "the mount must be gated on SYNC_TOKEN"
        );
        assert!(
            contents.contains("/sync NOT mounted"),
            "the skipped mount must be explained loudly at startup"
        );
        // Per-request guard: the generated middleware fails closed on an
        // empty expected token and compares in constant time.
        assert!(contents.contains("async fn require_sync_auth"));
        assert!(contents.contains("StatusCode::INTERNAL_SERVER_ERROR"));
        assert!(contents.contains("StatusCode::UNAUTHORIZED"));
        assert!(
            contents.contains("autumn_web::sync::server::constant_time_token_eq"),
            "the token comparison must be constant-time"
        );
        // The old unauthenticated one-liner mount must be gone.
        assert!(
            !contents.contains(r#".nest("/sync", server::router(backend, Arc::new(LwwResolver)))"#),
            "an unauthenticated /sync mount must not be emitted"
        );
    }

    #[test]
    fn offline_prerequisites_swap_in_the_sync_step() {
        let prereqs = render_mobile_prerequisites(OFFLINE);
        assert!(prereqs.contains("AUTUMN_SYNC__REMOTE_URL"));
        assert!(prereqs.contains("tauri-mobile-offline-sync"));
        assert!(
            !prereqs.contains("set AUTUMN_DATABASE__URL (see the"),
            "the direct-Postgres step must be replaced, not duplicated"
        );
    }

    #[test]
    fn shell_autumn_web_dep_reads_string_and_table_version_deps() {
        let tmp = stock_app_dir("my-app");
        let mut plan = Plan::new(tmp.path());
        assert_eq!(
            shell_autumn_web_dep(tmp.path(), &mut plan).dep_entry,
            r#"autumn-web = { version = "0.9.1", features = ["offline-sync"] }"#
        );

        std::fs::write(
            tmp.path().join("Cargo.toml"),
            "[package]\nname = \"my-app\"\nversion = \"0.1.0\"\n\n[dependencies]\n\
             autumn-web = { version = \"1.2.3\", features = [\"mail\"] }\n",
        )
        .unwrap();
        assert_eq!(
            shell_autumn_web_dep(tmp.path(), &mut plan).dep_entry,
            r#"autumn-web = { version = "1.2.3", features = ["offline-sync"] }"#
        );
        assert!(plan.warnings.is_empty(), "got {:?}", plan.warnings);
    }
}