wsb 0.255.6379

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

use crate::state::project_facts::{self, ProjectFacts, ProjectIdentity};
use crate::state::run_cache::RunCache;
use crate::state::template_refs::TemplateReferences;
use crate::state::{StateConfig, VersionInfo};
use crate::workspace_state::WorkspaceState;

// ── Public types ──────────────────────────────────────────────────────────────

#[derive(Debug)]
pub struct RenderedTemplate {
    pub source_path: PathBuf,
    pub output_path: PathBuf,
    /// The lockfile this render rewrote to agree with the output, if any. Part
    /// of the render: a commit that stages the manifest and not this carries a
    /// lock naming the previous version, which `cargo --locked` refuses.
    pub lockfile: Option<PathBuf>,
}

/// One template's output, before anything is written.
#[derive(Debug, Clone)]
pub struct Produced {
    pub source_path: PathBuf,
    pub output_path: PathBuf,
    pub content: String,
    /// Whether the template belongs to the project being rendered, rather
    /// than to a peer whose template references it.
    ///
    /// Only an own manifest's lock is followed. A peer's lock is resolved
    /// against the whole of what the peer pins, and in the middle of a release
    /// those pins cannot agree yet: committing tagged-urn after a lungo release
    /// rendered capdag-objc, whose newest pins were the new lungo-swift and a
    /// tagged-urn-objc still pinning the old one, and SwiftPM's refusal to
    /// resolve that stopped tagged-urn's own commit. The peer's lock follows
    /// when the peer itself is rendered.
    pub own: bool,
}

/// The template engine for `.wstemplate` files.
///
/// ## Context variables available in every template
///
/// `{{ project.* }}` describes the project that owns the template file, and
/// `{{ projects.ALIAS.* }}` exposes the same fields for any project in the
/// workspace — including every submodule, since each is a project in its own
/// right. The full field catalogue lives in [`project_facts::FIELDS`]; run
/// `wsb wstemplate vars` to print it with the current values resolved.
///
/// Beyond identity and the calculated version, the fields most templates reach
/// for are:
///
/// | Variable                            | Description                                    |
/// |-------------------------------------|------------------------------------------------|
/// | `{{ projects.ALIAS.version }}`      | Calculated version — the version being built    |
/// | `{{ projects.ALIAS.latest_tag }}`   | Highest tag in the clone, e.g. `v1.648.6494`    |
/// | `{{ projects.ALIAS.latest_version }}`| That tag without its `v` — the pin-ready form  |
/// | `{{ projects.ALIAS.latest_remote_tag }}`| Highest tag on the remote (network)         |
/// | `{{ projects.ALIAS.commit }}`       | HEAD commit hash (`short_commit` for 7 chars)   |
/// | `{{ projects.ALIAS.relative_path }}`| Path from the workspace root, e.g. `ext/gtest`  |
///
/// `version` is the version *being produced* — `version.txt` is bumped on
/// commit, so it is normally one step ahead of anything published. A pin that an
/// outside consumer has to resolve wants `latest_version`, not `version`.
///
/// Render time is available separately:
///
/// | Variable                       | Description                               |
/// |--------------------------------|-------------------------------------------|
/// | `{{ datetime.iso }}`           | RFC 3339 timestamp                        |
/// | `{{ datetime.date }}`          | YYYY-MM-DD                                |
/// | `{{ datetime.time }}`          | HH:MM:SS                                  |
/// | `{{ datetime.year/month/day }}`| individual components                     |
/// | `{{ datetime.timestamp }}`     | seconds since the Unix epoch, as a number |
///
/// ## Fields that do not apply
///
/// A field is either a real value or an error naming the reason — never an empty
/// string. A project with no tags has no `latest_tag`, and a template that asks
/// for one fails with "it has no tags" rather than stamping `""` into a manifest.
/// References are checked before rendering, so this is reported for the template
/// as a whole rather than mid-file.
///
/// ## What counts as a reference
///
/// Only code inside `{{ … }}` and `{% … %}` is read as a reference. The rendered
/// file's own syntax is left alone: a `pyproject.toml` may carry
/// `[project.optional-dependencies]` and a fixture may quote the literal text
/// `projects.foo.version` without either being resolved. `{# … #}` comments,
/// `{% raw %}` bodies, and quoted strings inside a block are literal content.
/// See [`TemplateReferences`] for the parser both template selection and context
/// building share.
///
/// ## Template selection
///
/// When [`render_relevant`] is called, only templates that satisfy at least one
/// of the following conditions are rendered:
/// 1. The template lives under `project_root` (own templates).
/// 2. The template references `projects.SELF_ALIAS`.
///
/// ## Resolution for referenced aliases
///
/// `{{ project.* }}` resolves against the project that owns the template file,
/// identified by the closest `.wsb/state.json`.
///
/// For every alias the engine:
/// 1. Walks `scan_root` to find all `.wsb/state.json` files.
/// 2. Finds the one that registers the alias.
/// 3. Reads `{project_root}/version.txt` for the version fields, and opens
///    `{project_root}` as a git repository for the tag and head fields.
///
/// The project currently being updated (`self_alias`) reports the
/// freshly-computed `current_version` instead of its `version.txt`, so the run is
/// always self-consistent. Facts are resolved once per project and reused across
/// every template in the run.
///
/// A missing `version.txt` is a hard error — run `wsb update` in the dependency
/// project first.  An unresolvable alias is also a hard error.
pub struct WstemplateEngine {
    current_version: VersionInfo,
    current_name: Option<String>,
    /// Alias for the current project (from its `wsbtemplate_entry().alias`)
    self_alias: String,
    /// The current project's own directory
    project_root: PathBuf,
    /// Root to scan for `.wstemplate` files and peer `.wsb/state.json` files
    scan_root: PathBuf,
    /// Absolute paths of this project's git submodules.
    ///
    /// A template inside one is that submodule's, whether or not the submodule
    /// has been registered with a `.wsb/state.json`. Git already draws the
    /// boundary; deciding ownership from the state file alone means an
    /// unregistered submodule's templates get claimed — and stamped with THIS
    /// project's version — by whichever ancestor happens to run first.
    submodule_roots: Arc<Vec<PathBuf>>,
    /// What this run has already read. A run that shares one across every
    /// repository it updates is `wsb update --recursive`; a run that does not
    /// is every other caller, and the two produce the same bytes — see
    /// [`RunCache`] and `wsb update --recursive --verify`.
    cache: Arc<RunCache>,
}

impl WstemplateEngine {
    /// Create an engine for the current project.
    ///
    /// - `current_version` — freshly-computed version of this project
    /// - `current_name`    — human-readable name of this project
    /// - `self_alias`      — Tera alias for this project (from the wstemplate entry)
    /// - `project_root`    — this project's own root directory
    /// - `scan_root`       — the workspace root to scan for templates and peers
    pub fn new(
        current_version: VersionInfo,
        current_name: Option<String>,
        self_alias: String,
        project_root: PathBuf,
        scan_root: PathBuf,
    ) -> Self {
        Self::with_cache(
            current_version,
            current_name,
            self_alias,
            project_root,
            scan_root,
            RunCache::new(),
        )
    }

    /// The same engine, reading through a cache another repository's update in
    /// the same run has already filled.
    pub fn with_cache(
        current_version: VersionInfo,
        current_name: Option<String>,
        self_alias: String,
        project_root: PathBuf,
        scan_root: PathBuf,
        cache: Arc<RunCache>,
    ) -> Self {
        let submodule_roots =
            cache.submodule_roots(&project_root, || submodule_roots_of(&project_root));
        Self {
            current_version,
            current_name,
            self_alias,
            project_root,
            scan_root,
            submodule_roots,
            cache,
        }
    }

    /// The cache this engine reads through, so a caller doing more than one
    /// thing in a run can hand the same one to the next step.
    pub fn cache(&self) -> &Arc<RunCache> {
        &self.cache
    }

    /// Derive a deterministic, Tera-compatible alias from a project root path.
    ///
    /// Algorithm:
    /// 1. Take the last path component (directory basename).
    /// 2. Lowercase every character.
    /// 3. Replace any character that is not ASCII alphanumeric with `_`.
    /// 4. Collapse runs of `_` into a single `_` and strip leading/trailing `_`.
    /// 5. If the result starts with a digit, prepend `p_`.
    /// 6. If the result is empty, return `"project"`.
    ///
    /// Examples: `my-app` → `my_app`, `API Service` → `api_service`, `123abc` → `p_123abc`.
    pub fn derive_alias(path: &Path) -> String {
        let base = path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("project");

        // Step 2-3: lowercase and replace non-alphanumeric.
        let raw: String = base
            .chars()
            .map(|c| {
                if c.is_ascii_alphanumeric() {
                    c.to_ascii_lowercase()
                } else {
                    '_'
                }
            })
            .collect();

        // Step 4: collapse consecutive underscores.
        let mut slug = String::with_capacity(raw.len());
        let mut prev_underscore = true; // treat start as underscore to strip leading
        for ch in raw.chars() {
            if ch == '_' {
                if !prev_underscore {
                    slug.push('_');
                }
                prev_underscore = true;
            } else {
                slug.push(ch);
                prev_underscore = false;
            }
        }
        // Strip trailing underscore.
        let slug = slug.trim_end_matches('_').to_string();

        if slug.is_empty() {
            return "project".to_string();
        }

        // Step 5: must not start with a digit.
        if slug.starts_with(|c: char| c.is_ascii_digit()) {
            format!("p_{}", slug)
        } else {
            slug
        }
    }

    /// Discover all `.wstemplate` files in `scan_root` using `rg`.
    ///
    /// `rg` is required — the function fails hard if it is not available.
    /// `rg` respects `.gitignore` automatically when run inside a git repository.
    pub fn discover_all(&self) -> Result<Arc<Vec<PathBuf>>> {
        self.cache
            .templates_under(&self.scan_root, || discover_in(&self.scan_root))
    }

    /// Build a map of `alias → project_root` by scanning all `.wsb/state.json`
    /// files in the scan root.
    pub fn discover_project_roots(&self) -> Result<Arc<HashMap<String, PathBuf>>> {
        self.cache
            .project_roots(&self.scan_root, || find_all_project_roots(&self.scan_root))
    }

    /// Discover templates that are relevant to the current project:
    /// - templates *owned* by this project (closest project root is `project_root`), OR
    /// - templates anywhere in `scan_root` that reference `{{ projects.SELF_ALIAS.* }}`
    ///
    /// Ownership is determined by the most-specific project root: a template at
    /// `/workspace/sub/foo.wstemplate` is owned by `/workspace/sub` if that is a
    /// registered project, even if `/workspace` is also a registered project.
    ///
    /// Irrelevant templates (owned by other projects and not referencing self_alias)
    /// are silently skipped. A foreign template that cannot be parsed is a hard
    /// error rather than a skip: "we cannot tell whether it references us" is the
    /// one answer that must not be treated as "it does not".
    pub fn discover_relevant(
        &self,
        project_roots: &HashMap<String, PathBuf>,
    ) -> Result<Vec<PathBuf>> {
        let all = self.discover_all()?;
        let mut relevant = Vec::new();
        for path in all.iter() {
            if self.is_own_template(path, project_roots) {
                relevant.push(path.clone());
                continue;
            }
            if self.references(path)?.references_alias(&self.self_alias) {
                relevant.push(path.clone());
            }
        }
        Ok(relevant)
    }

    /// Render all templates relevant to the current project.
    ///
    /// See [`discover_relevant`] for the selection criteria.
    ///
    /// For each selected template the context is built with:
    /// - `{{ project.* }}` = version of the project that *owns* the template
    ///   (for own templates this is `current_version`; for foreign templates it
    ///   comes from that project's `version.txt`)
    /// - `{{ projects.SELF_ALIAS.* }}` = `current_version`
    /// - `{{ projects.OTHER.* }}` = read from `{other_project_root}/version.txt`
    ///
    /// Any unresolvable alias or missing `version.txt` is a hard error.
    pub fn render_relevant(&self) -> Result<Vec<RenderedTemplate>> {
        let produced = self.produce_relevant()?;
        self.write_produced(produced)
    }

    /// Write what [`produce_relevant`] produced, in the order it produced it.
    ///
    /// Split out so a caller can look at the whole render before any of it
    /// lands — `wsb update --verify` renders each repository twice, once
    /// through the run's shared cache and once through a cache of its own, and
    /// compares the two before either is written.
    pub fn write_produced(&self, produced: Vec<Produced>) -> Result<Vec<RenderedTemplate>> {
        let mut rendered = Vec::with_capacity(produced.len());
        for one in produced {
            write_output(&one.output_path, &one.content)?;
            let lockfile = if one.own {
                follow_into_lockfile(&one.output_path, &one.content)?
            } else {
                None
            };
            self.cache.note_written(&one.output_path);
            info!(
                "wstemplate: {} -> {}",
                one.source_path.display(),
                one.output_path.display()
            );
            rendered.push(RenderedTemplate {
                source_path: one.source_path,
                output_path: one.output_path,
                lockfile,
            });
        }
        Ok(rendered)
    }

    /// What every relevant template WOULD write, without writing any of it.
    ///
    /// The same work `render_relevant` does, stopping before the write. It
    /// exists so a caller can compare the render against what is on disk —
    /// discarding a render means knowing exactly what it contributed, and
    /// asking for that by rendering over the tree first would destroy the
    /// answer it was trying to compute.
    pub fn produce_relevant(&self) -> Result<Vec<Produced>> {
        // Build a complete alias→project_root map by scanning the workspace.
        let project_roots = self.discover_project_roots()?;

        let relevant = self.discover_relevant(&project_roots)?;
        let mut produced = Vec::new();

        // Facts are resolved once per project and reused across templates: they
        // read git refs and worktree status, which is wasted work to repeat.
        let mut facts_cache: HashMap<String, ProjectFacts> = HashMap::new();

        for path in &relevant {
            let content = self.text(path)?;

            let is_own = self.is_own_template(path, &project_roots);
            let references = self.references(path)?;

            let ctx = self
                .build_context(&references, path, is_own, &project_roots, &mut facts_cache)
                .with_context(|| format!("Cannot build render context for {}", path.display()))?;

            produced.push(
                produce_one(path, &content, &ctx, is_own)
                    .with_context(|| format!("Cannot render template {}", path.display()))?,
            );
        }

        Ok(produced)
    }
}

/// Fields the RENDER resolves, rather than the project's own facts.
///
/// They depend on the file being written, so they are not cached with the
/// project and are not checked against its facts — the engine computes them per
/// template and fails there when it cannot.
const RENDERED_FIELDS: &[&str] = &["path_from_here"];

// ── Private helpers ───────────────────────────────────────────────────────────

impl WstemplateEngine {
    /// Check if a template is owned by this project (not by a more-specific subproject).
    ///
    /// A template is "own" when `self.project_root` is the most-specific project
    /// root containing it.  For example, if project_root = `/workspace` and a
    /// subproject at `/workspace/sub` also exists, templates under `/workspace/sub`
    /// are NOT own templates of `/workspace`.
    /// One template's text, read once per run.
    ///
    /// An update writes a template's OUTPUT, never a template, so the text a
    /// recursive run reads for the first repository is the text every later
    /// repository reads. Where that stops being true — a template that renders
    /// another template — [`RunCache::note_written`] drops what was read.
    fn text(&self, path: &Path) -> Result<Arc<String>> {
        self.cache.template_text(path, || {
            fs::read_to_string(path)
                .with_context(|| format!("Cannot read template {}", path.display()))
        })
    }

    /// What one template refers to, parsed once per run.
    ///
    /// Selection alone used to read and parse every template in the workspace
    /// once per repository — 59 files, 34 times over, for an answer that is a
    /// property of the file.
    fn references(&self, path: &Path) -> Result<Arc<TemplateReferences>> {
        let text = self.text(path)?;
        self.cache
            .template_references(path, || read_references(path, &text))
    }

    fn is_own_template(
        &self,
        template_path: &Path,
        project_roots: &HashMap<String, PathBuf>,
    ) -> bool {
        // Every containment question here is asked through `is_under`: the
        // roots come from `.wsb/state.json` and the template from a walk, and
        // the two can spell one directory differently.
        if !is_under(template_path, &self.project_root) {
            return false;
        }
        // A template inside a submodule is never ours, registered or not. This
        // is decided before the project-root scan because that scan only sees
        // submodules carrying a `.wsb/state.json`, which is machine-local and
        // absent on a fresh clone.
        if self
            .submodule_roots
            .iter()
            .any(|sm| is_under(template_path, sm))
        {
            return false;
        }
        // Check that no more-specific project root also contains this template.
        let own = resolved(&self.project_root);
        let self_depth = own.components().count();
        for root in project_roots.values() {
            let root = resolved(root);
            if root == own {
                continue;
            }
            if is_under(template_path, &root) && root.components().count() > self_depth {
                return false; // a deeper project owns this template
            }
        }
        true
    }

    /// Determine which alias `{{ project.* }}` refers to for a given template.
    ///
    /// - If `is_own` is true → this project's own alias
    /// - Otherwise the most-specific registered project containing the template
    fn find_owning_alias(
        &self,
        template_path: &Path,
        project_roots: &HashMap<String, PathBuf>,
        is_own: bool,
    ) -> Result<String> {
        if is_own {
            return Ok(self.self_alias.clone());
        }

        let root = find_most_specific_root(template_path, project_roots).ok_or_else(|| {
            anyhow::anyhow!(
                "Cannot determine the owning project for template at {}. \
                 The template is not under any project registered in {}",
                template_path.display(),
                self.scan_root.display()
            )
        })?;

        // A project may register several aliases; pick deterministically so the
        // same template always renders against the same identity.
        let mut aliases: Vec<&String> = project_roots
            .iter()
            .filter(|(_, candidate)| *candidate == &root)
            .map(|(alias, _)| alias)
            .collect();
        aliases.sort();
        aliases
            .first()
            .map(|alias| (*alias).clone())
            .with_context(|| {
                format!(
                    "Project at {} owns template {} but registers no alias",
                    root.display(),
                    template_path.display()
                )
            })
    }

    /// Resolve the facts for `alias`, reusing a cached snapshot when it already
    /// covers what this template needs.
    ///
    /// The project currently being updated reports its freshly-calculated
    /// version; every other project reports what its `version.txt` records.
    fn facts_for<'cache>(
        &self,
        alias: &str,
        fields: &BTreeSet<String>,
        project_roots: &HashMap<String, PathBuf>,
        template_path: &Path,
        cache: &'cache mut HashMap<String, ProjectFacts>,
    ) -> Result<&'cache ProjectFacts> {
        let with_remote = project_facts::requires_network(fields.iter().map(String::as_str));

        // A cached snapshot is reusable unless this template needs the network
        // fields and the snapshot was taken without contacting the remote.
        let usable = cache
            .get(alias)
            .is_some_and(|facts| facts.resolved_remote || !with_remote);

        if !usable {
            let facts = if alias == self.self_alias {
                project_facts::gather_with_cache(
                    &ProjectIdentity {
                        alias,
                        root: &self.project_root,
                        scan_root: &self.scan_root,
                        version: &self.current_version,
                        name: self.current_name.as_deref(),
                    },
                    with_remote,
                    &self.cache,
                )?
            } else {
                let root = project_roots.get(alias).ok_or_else(|| {
                    let mut known: Vec<&str> = project_roots.keys().map(|s| s.as_str()).collect();
                    known.sort();
                    anyhow::anyhow!(
                        "Template {} references alias '{}' which cannot be resolved.\n\
                         Known aliases: [{}]\n\
                         Either the project is missing a .wsb/state.json or its alias doesn't match.",
                        template_path.display(),
                        alias,
                        known.join(", "),
                    )
                })?;
                let version = read_version_from_path(root)
                    .with_context(|| format!("Cannot resolve version for alias '{}'", alias))?;
                project_facts::gather_with_cache(
                    &ProjectIdentity {
                        alias,
                        root,
                        scan_root: &self.scan_root,
                        version: &version,
                        name: None,
                    },
                    with_remote,
                    &self.cache,
                )?
            };
            cache.insert(alias.to_string(), facts);
        }

        cache
            .get(alias)
            .context("facts were just resolved for this alias")
    }

    /// Build the Tera context for one template.
    ///
    /// - `{{ project.* }}`         → the project that owns the template file
    /// - `{{ projects.ALIAS.* }}`  → one entry per alias the template references
    ///
    /// Every referenced field is checked here, before rendering, so an
    /// unresolvable reference reports which project, which line, and why.
    /// The workspace declaration, with every path a template asks for checked.
    ///
    /// Which file that is, the workspace names in its stamp configuration
    /// ([`super::stamp_config`]): the stamp is told, not left to guess.
    ///
    /// Read only when a template asks for something. Most do not, and parsing
    /// the declaration for every template that never mentions it would be a
    /// cost paid on every render for a feature used once.
    ///
    /// Every path is checked BEFORE rendering, because a declaration is data
    /// somebody edits: a renamed key would otherwise reach Tera as "variable
    /// not found" naming only the last segment, and the useful thing to say is
    /// which path was asked for, on which line, and what is actually there.
    fn declaration(&self, references: &TemplateReferences) -> Result<serde_json::Value> {
        let path = super::stamp_config::StampConfig::declared_file(&self.scan_root)?;
        let text = std::fs::read_to_string(&path).with_context(|| {
            format!("cannot read the workspace declaration at {}", path.display())
        })?;
        let declaration: serde_json::Value = serde_json::from_str(&text)
            .with_context(|| format!("{} is not valid JSON", path.display()))?;
        for (asked, line) in references.declared_paths() {
            let mut here = &declaration;
            let mut walked: Vec<&str> = Vec::new();
            for segment in asked.split('.') {
                let Some(next) = here.get(segment) else {
                    let found = match here.as_object() {
                        Some(map) => format!(
                            "'declared{}{}' has: {}",
                            if walked.is_empty() { "" } else { "." },
                            walked.join("."),
                            map.keys().cloned().collect::<Vec<_>>().join(", ")
                        ),
                        None => format!(
                            "'declared.{}' is not something with named parts",
                            walked.join(".")
                        ),
                    };
                    bail!(
                        "line {line}: the workspace declares no 'declared.{asked}'.\n{found}"
                    );
                };
                walked.push(segment);
                here = next;
            }
        }
        Ok(declaration)
    }

    /// The `{{ build.* }}` context: the workspace's build root, from the file
    /// being rendered, in this platform's layout.
    fn build_facts(
        &self,
        template_output_dir: &Path,
        template_path: &Path,
    ) -> Result<BTreeMap<String, Value>> {
        // The root as the workspace names it, the same on every machine: what
        // a rendered file names has to be where every machine puts it.
        let root = super::stamp_config::StampConfig::build_root(&self.scan_root)
            .with_context(|| format!("{}: the build root", template_path.display()))?;
        let relative = path_between(template_output_dir, &root).with_context(|| {
            format!(
                "{}: there is no relative path from here to the build root {}",
                template_path.display(),
                root.display()
            )
        })?;
        Ok(BTreeMap::from([("root_from_here".to_string(), json!(relative))]))
    }

    fn build_context(
        &self,
        references: &TemplateReferences,
        template_path: &Path,
        is_own: bool,
        project_roots: &HashMap<String, PathBuf>,
        cache: &mut HashMap<String, ProjectFacts>,
    ) -> Result<TeraContext> {
        let owning_alias = self.find_owning_alias(template_path, project_roots, is_own)?;
        // The directory the RENDERED file lands in — not the project root. A
        // manifest under `crates/foo/` resolves its path dependencies from
        // there, and a path relative to the project root would climb one level
        // too few.
        let template_output_dir = template_path
            .parent()
            .context("a template path always has a parent directory")?;

        // Which projects have to be in the context, and which of their fields
        // this template actually reads. `project.foo` and
        // `projects.<owning alias>.foo` name the same project, so their fields
        // merge into a single resolution.
        let mut wanted: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        for alias in references.aliases() {
            let fields = wanted.entry(alias.to_string()).or_default();
            if let Some(referenced) = references.peer_fields(alias) {
                fields.extend(referenced.keys().cloned());
            }
        }
        wanted
            .entry(owning_alias.clone())
            .or_default()
            .extend(references.own_fields().keys().cloned());
        // The current project is always in scope, referenced or not.
        wanted.entry(self.self_alias.clone()).or_default();
        // Iterating `projects` has to see all of them, not just the ones named.
        if references.iterates_projects() {
            for alias in project_roots.keys() {
                wanted.entry(alias.clone()).or_default();
            }
        }

        let mut projects: HashMap<String, BTreeMap<String, Value>> = HashMap::new();
        for (alias, fields) in &wanted {
            let facts = self.facts_for(alias, fields, project_roots, template_path, cache)?;

            if let Some(referenced) = references.peer_fields(alias) {
                for (field, line) in referenced {
                    if RENDERED_FIELDS.contains(&field.as_str()) {
                        continue;
                    }
                    facts.require(field).with_context(|| {
                        format!("{}:{} cannot be rendered", template_path.display(), line)
                    })?;
                }
            }
            if alias == &owning_alias {
                for (field, line) in references.own_fields() {
                    if RENDERED_FIELDS.contains(&field.as_str()) {
                        continue;
                    }
                    facts.require(field).with_context(|| {
                        format!("{}:{} cannot be rendered", template_path.display(), line)
                    })?;
                }
            }

            let mut values = facts.values().clone();
            // Where this project sits, from the file being written. A local
            // dependency is a RELATIVE path in a manifest, and a template that
            // spelled one out by hand would be right on one machine and in one
            // repository layout — this is the same answer, computed.
            if let Some(path) = values.get("path").and_then(|path| path.as_str()) {
                match path_between(template_output_dir, Path::new(path)) {
                    Some(relative) => {
                        values.insert("path_from_here".to_string(), json!(relative));
                    }
                    // Nothing in common — different drives, or a project
                    // reached through a symlink that resolves elsewhere. A
                    // template asking for a relative path has to be told,
                    // rather than handed an absolute one that works on exactly
                    // this machine.
                    None => bail!(
                        "{}: there is no relative path from here to project '{alias}' at {path}",
                        template_path.display()
                    ),
                }
            }
            projects.insert(alias.clone(), values);
        }

        let mut ctx = TeraContext::new();
        ctx.insert(
            "project",
            projects
                .get(&owning_alias)
                .context("owning project facts must have been resolved")?,
        );
        ctx.insert("projects", &projects);
        ctx.insert("datetime", &datetime_map());
        ctx.insert("env", &environment_map(references.env_names(), self.cache.environment()));
        if !references.declared_paths().is_empty() {
            ctx.insert("declared", &self.declaration(references)?);
        }
        if !references.build_fields().is_empty() {
            ctx.insert("build", &self.build_facts(template_output_dir, template_path)?);
        }

        Ok(ctx)
    }
}

/// This process's environment, as templates see it.
///
/// Whole sections of a template are switched on the environment it was
/// rendered in — a dependency written as a published version ordinarily, and as
/// a path to the working directory when a variable says so:
///
/// ```text
/// {%- if env.MFR_LOCAL_LIBS %}
/// capdag = { path = "{{ projects.capdag_rs.path_from_here }}" }
/// {%- else %}
/// capdag = { git = "…", tag = "v{{ projects.capdag_rs.latest_version }}" }
/// {%- endif %}
/// ```
///
/// It reads the way a shell does. A variable that is unset is absent from this
/// map, and Tera treats a missing name in a condition as false; a variable set
/// to the empty string is present and empty, which is also false, so `FOO=` and
/// an unset `FOO` mean the same thing here as they do in `[ -n "$FOO" ]`. Any
/// other value is true, including `0` — a value test is written as one:
/// `{% if env.MFR_MODE == "local" %}`.
///
/// Variables whose value is not UTF-8 are left out rather than replaced: a
/// template that stamped a lossy value into a manifest would write something
/// nobody set.
///
/// `run` is the run's own variables, which win over the process's: a render
/// produced as if a variable were set, without setting it for every thread.
fn environment_map(
    named: &std::collections::BTreeSet<String>,
    run: &BTreeMap<String, String>,
) -> BTreeMap<String, String> {
    let mut map: BTreeMap<String, String> = std::env::vars().collect();
    map.extend(run.iter().map(|(name, value)| (name.clone(), value.clone())));
    // Every name the template asks about, whether or not it is set. Tera raises
    // an error for a key missing from a map, so without this the ordinary case
    // — the variable is not set — would fail to render instead of rendering the
    // other branch.
    for name in named {
        map.entry(name.clone()).or_default();
    }
    map
}

/// The relative path from `from` to `to`, as a manifest would write it.
///
/// `None` when the two are on different roots and no relative path exists —
/// which a template asking for one has to be told about rather than handed an
/// absolute path that works on exactly this machine.
fn path_between(from: &Path, to: &Path) -> Option<String> {
    let from = canonical_as_far_as_exists(from);
    let to = canonical_as_far_as_exists(to);
    let mut shared = 0;
    let from_parts: Vec<_> = from.components().collect();
    let to_parts: Vec<_> = to.components().collect();
    while shared < from_parts.len()
        && shared < to_parts.len()
        && from_parts[shared] == to_parts[shared]
    {
        shared += 1;
    }
    if shared == 0 {
        return None;
    }
    let mut path = String::new();
    for _ in shared..from_parts.len() {
        path.push_str("../");
    }
    for (at, part) in to_parts[shared..].iter().enumerate() {
        if at > 0 {
            path.push('/');
        }
        path.push_str(&part.as_os_str().to_string_lossy());
    }
    // The same directory: `.` rather than an empty string, which a manifest
    // would read as a path to nowhere.
    if path.is_empty() {
        return Some(".".to_string());
    }
    Some(path.trim_end_matches('/').to_string())
}

/// `path` with its longest existing ancestor canonicalized and the rest kept.
///
/// A path that does not exist yet — a build root before the first build — has
/// to be compared on the same footing as one that does: canonicalizing one side
/// and not the other puts them on different roots wherever a symlink sits above
/// both (`/var` is `/private/var` on a Mac), and the relative path between them
/// climbs to `/` and back down.
fn canonical_as_far_as_exists(path: &Path) -> PathBuf {
    let mut existing = path.to_path_buf();
    let mut rest: Vec<std::ffi::OsString> = Vec::new();
    loop {
        if let Ok(canonical) = crate::platform::canonicalize(&existing) {
            return rest.iter().rev().fold(canonical, |p, part| p.join(part));
        }
        match (existing.file_name().map(|n| n.to_os_string()), existing.parent()) {
            (Some(name), Some(parent)) => {
                rest.push(name);
                existing = parent.to_path_buf();
            }
            _ => return path.to_path_buf(),
        }
    }
}

/// Parse a template's references, naming the file when it cannot be scanned.
fn read_references(template_path: &Path, content: &str) -> Result<TemplateReferences> {
    TemplateReferences::parse(content)
        .with_context(|| format!("Cannot parse template {}", template_path.display()))
}

/// The `{{ datetime.* }}` context, stamped at render time in local time.
fn datetime_map() -> HashMap<String, Value> {
    let now = chrono::Local::now();
    let mut datetime: HashMap<String, Value> = HashMap::new();
    datetime.insert("iso".to_string(), json!(now.to_rfc3339()));
    datetime.insert(
        "date".to_string(),
        json!(now.format("%Y-%m-%d").to_string()),
    );
    datetime.insert(
        "time".to_string(),
        json!(now.format("%H:%M:%S").to_string()),
    );
    datetime.insert("year".to_string(), json!(now.format("%Y").to_string()));
    datetime.insert("month".to_string(), json!(now.format("%m").to_string()));
    datetime.insert("day".to_string(), json!(now.format("%d").to_string()));
    datetime.insert("timestamp".to_string(), json!(now.timestamp()));
    datetime
}

/// Walk `scan_root` and return a map of `alias → project_root` by reading
/// every `.wsb/state.json` found.
///
/// Duplicate aliases are a hard error — every alias must be unique across the
/// workspace.
/// Absolute paths of `project_root`'s git submodules.
///
/// Empty when the directory is not a git repository or git cannot answer —
/// the ownership rules then fall back to the registered project roots alone,
/// which is the behaviour for a plain directory tree.
fn submodule_roots_of(project_root: &Path) -> Vec<PathBuf> {
    let Ok(repo) = crate::git_backend::discover_repo(project_root) else {
        return Vec::new();
    };
    let Ok(Some(submodules)) = repo.submodules() else {
        return Vec::new();
    };
    submodules
        .filter_map(|sm| sm.path().ok().map(|p| project_root.join(p.to_string())))
        .collect()
}

/// Which other repositories each repository's templates read the projects of,
/// for every repository in `repositories` under `root`.
///
/// What a template renders depends on the versions of the projects it names
/// (`projects.<alias>.*`), so a repository whose templates name a project in
/// another repository is rendered from that one's version — and must be
/// committed after it, or it is committed against the version that was there
/// a moment before (`fleet::commands::commit`). A template that iterates every
/// project reads them all.
pub fn render_dependencies(
    root: &Path,
    repositories: &[PathBuf],
) -> Result<BTreeMap<PathBuf, BTreeSet<PathBuf>>> {
    let projects = find_all_project_roots(root)?;
    let owner = |path: &Path| -> Option<PathBuf> {
        repositories
            .iter()
            .filter(|repository| path.starts_with(repository))
            .max_by_key(|repository| repository.components().count())
            .cloned()
    };
    let mut dependencies: BTreeMap<PathBuf, BTreeSet<PathBuf>> = BTreeMap::new();
    for template in crate::search_backend::discover_files_with_suffix(root, ".wstemplate")? {
        let Some(repository) = owner(&template) else { continue };
        let text = fs::read_to_string(&template)
            .with_context(|| format!("reading {}", template.display()))?;
        let references = TemplateReferences::parse(&text)
            .with_context(|| format!("reading the references of {}", template.display()))?;
        let reads = dependencies.entry(repository.clone()).or_default();
        if references.iterates_projects() {
            reads.extend(repositories.iter().filter(|other| **other != repository).cloned());
        }
        for alias in references.aliases() {
            if let Some(read) = projects.get(alias).and_then(|project| owner(project)) {
                if read != repository {
                    reads.insert(read);
                }
            }
        }
    }
    Ok(dependencies)
}

fn find_all_project_roots(scan_root: &Path) -> Result<HashMap<String, PathBuf>> {
    let mut map: HashMap<String, PathBuf> = HashMap::new();

    for entry in WalkDir::new(scan_root)
        .follow_links(false)
        .into_iter()
        .filter_entry(|e| {
            // Always descend into the scan root itself.
            if e.depth() == 0 {
                return true;
            }
            let name = e.file_name().to_str().unwrap_or("");
            // Descend into .wsb dirs; skip build/vendor/VCS dirs.
            if name.starts_with('.') && name != ".wsb" {
                return false;
            }
            // Within a .wsb only its state.json is a project's: what is below
            // it — a build root holding cloned workspaces of its own — is not.
            if e.file_type().is_dir() && e.path().parent().and_then(|p| p.file_name()).is_some_and(|n| n == ".wsb") {
                return false;
            }
            !matches!(name, "target" | "node_modules" | "__pycache__")
        })
    {
        let entry = match entry {
            Ok(e) => e,
            Err(_) => continue, // skip permission errors
        };

        if !entry.file_type().is_file() {
            continue;
        }
        if entry.file_name() != "state.json" {
            continue;
        }

        // Verify parent directory is named ".wsb"
        let is_in_ws = entry
            .path()
            .parent()
            .and_then(|p| p.file_name())
            .map(|n| n == ".wsb")
            .unwrap_or(false);
        if !is_in_ws {
            continue;
        }

        // The project is where its `.wsb` is — the file names no place —
        // read through the one reader, which refuses what it cannot trust.
        let project_root = entry
            .path()
            .parent()
            .and_then(Path::parent)
            .expect("a .wsb/state.json has a project directory")
            .to_path_buf();
        let state = crate::workspace_state::WorkspaceState::load(&project_root)?;
        let alias = state.effective_wstemplate_entry().alias;
        if let Some(existing) = map.get(&alias) {
            anyhow::bail!(
                "Duplicate wstemplate alias '{}': registered by both {} and {}. \
                 Each alias must be unique across the workspace.",
                alias,
                existing.display(),
                project_root.display()
            );
        }
        map.insert(alias, project_root);
    }

    Ok(map)
}

/// Return the project root that most specifically contains `path` (longest prefix).
fn find_most_specific_root(
    path: &Path,
    project_roots: &HashMap<String, PathBuf>,
) -> Option<PathBuf> {
    project_roots
        .values()
        .filter(|root| is_under(path, root))
        .max_by_key(|root| resolved(root).components().count())
        .cloned()
}

/// Whether `path` lies inside `root`, however each of them was spelled.
///
/// The two arrive from different places. A template is found by walking the
/// scan root as its registration spells it; a project root is read back from
/// `.wsb/state.json`, and wsb writes that from its working directory, which
/// the operating system reports RESOLVED. On macOS `/var` is a link to
/// `/private/var`, so after one `wsb update` a project registered at
/// `/var/…/fleet` read back as `/private/var/…/fleet`, no template under
/// `/var/…/fleet` started with it, and the next update refused with "the
/// template is not under any project registered" — for a template sitting
/// in that project. Any registration reached through a symlink did the same.
///
/// Resolved for the COMPARISON only: the paths themselves are handed on as
/// they came, because they end up in rendered files and in messages, and on
/// Windows a resolved path is a `\\?\` verbatim path nothing else writes.
fn is_under(path: &Path, root: &Path) -> bool {
    resolved(path).starts_with(resolved(root))
}

/// A path with its links resolved, for comparing against another one.
///
/// One that does not exist has nothing to resolve and is compared as given —
/// the same rule `relative_path` follows.
fn resolved(path: &Path) -> PathBuf {
    crate::platform::canonicalize(&path).unwrap_or_else(|_| path.to_path_buf())
}

/// Read `version.txt` from `project_root` and parse it into a [`VersionInfo`].
///
/// If the file is missing for a managed git project, materialize it on demand
/// using the normal workspace version calculation path.
pub fn read_version_from_path(project_root: &Path) -> Result<VersionInfo> {
    let version_file = project_root.join("version.txt");
    if !version_file.exists() {
        materialize_version_file(project_root)?;
    }
    let content = fs::read_to_string(&version_file).with_context(|| {
        format!(
            "Cannot read version.txt for project at {} after attempting automatic regeneration.",
            project_root.display()
        )
    })?;
    parse_version_string(content.trim())
}

fn materialize_version_file(project_root: &Path) -> Result<()> {
    let (config, workspace_state, version_info) = if tokio::runtime::Handle::try_current().is_ok() {
        tokio::task::block_in_place(|| {
            let handle = tokio::runtime::Handle::current();
            let config = handle.block_on(StateConfig::load_async(project_root));
            let workspace_state = WorkspaceState::load(project_root);
            let version_info = handle.block_on(crate::state::calculate_workspace_version_async(
                project_root,
            ));
            Ok::<_, anyhow::Error>((config, workspace_state, version_info))
        })?
    } else {
        (
            StateConfig::load(project_root),
            WorkspaceState::load(project_root),
            crate::state::calculate_workspace_version(project_root),
        )
    };
    let config = config.with_context(|| {
        format!(
            "failed to load workspace config for project at {} while regenerating version.txt",
            project_root.display()
        )
    })?;
    let workspace_state = workspace_state.with_context(|| {
        format!(
            "failed to load workspace state for project at {} while regenerating version.txt",
            project_root.display()
        )
    })?;
    let mut version_info = version_info.with_context(|| {
        format!(
            "failed to calculate workspace version for project at {} while regenerating version.txt",
            project_root.display()
        )
    })?;
    version_info.full_version = workspace_state.format_version(&version_info, None);
    crate::state::update_version_file_in_repo(&version_info, &config, project_root).with_context(
        || {
            format!(
                "failed to write version.txt for project at {} during automatic regeneration",
                project_root.display()
            )
        },
    )?;
    Ok(())
}

/// Parse a `major.minor.patch` string into a [`VersionInfo`].
pub fn parse_version_string(s: &str) -> Result<VersionInfo> {
    let parts: Vec<&str> = s.splitn(3, '.').collect();
    anyhow::ensure!(
        parts.len() == 3,
        "Invalid version string '{}': expected major.minor.patch",
        s
    );
    let major: u32 = parts[0]
        .parse()
        .with_context(|| format!("Invalid major in version string '{}'", s))?;
    let minor: u32 = parts[1]
        .parse()
        .with_context(|| format!("Invalid minor in version string '{}'", s))?;
    let patch_part = parts[2]
        .split_once('-')
        .map(|(patch, _suffix)| patch)
        .unwrap_or(parts[2]);
    let patch: u32 = patch_part
        .parse()
        .with_context(|| format!("Invalid patch in version string '{}'", s))?;

    Ok(VersionInfo {
        major_version: format!("v{}", major),
        minor_version: minor,
        patch_version: patch,
        full_version: s.to_string(),
    })
}

/// Render a single `.wstemplate` file given pre-read content and a pre-built context.
///
/// The output path is derived by stripping the `.wstemplate` suffix.
/// Render one template, without writing it.
fn produce_one(template_path: &Path, content: &str, ctx: &TeraContext, own: bool) -> Result<Produced> {
    let path_str = template_path.to_string_lossy();
    anyhow::ensure!(
        path_str.ends_with(".wstemplate"),
        "Template path does not end with .wstemplate: {}",
        template_path.display()
    );

    let output_path = PathBuf::from(&path_str[..path_str.len() - ".wstemplate".len()]);

    let mut tera = Tera::default();
    let tpl_name = template_path.display().to_string();
    tera.add_raw_template(&tpl_name, content)
        .with_context(|| format!("Tera parse error in {}", template_path.display()))?;

    let rendered = tera
        .render(&tpl_name, ctx)
        .with_context(|| format!("Tera render error in {}", template_path.display()))?;

    Ok(Produced {
        source_path: template_path.to_path_buf(),
        output_path,
        content: rendered,
        own,
    })
}

/// Write one rendered output, creating the directory it needs.
fn write_output(output_path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = output_path.parent() {
        fs::create_dir_all(parent).with_context(|| {
            format!(
                "Cannot create parent directory for {}",
                output_path.display()
            )
        })?;
    }
    fs::write(output_path, content)
        .with_context(|| format!("Cannot write {}", output_path.display()))
}

fn discover_in(root: &Path) -> Result<Vec<PathBuf>> {
    crate::search_backend::discover_files_with_suffix(root, ".wstemplate")
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::state::StateConfig;
    use std::fs;

    /// TEST12358: a rendered `go.mod` leaves its `go.sum` recording every
    /// requirement it names — the module's hash and its `go.mod`'s, and the
    /// `go.mod` hash of what that module requires — asking only for what is
    /// missing, and nothing for a module replaced by a local directory.
    ///
    /// The render moved tagged-urn-go's lungo-go pin to the new release and
    /// `go.sum` had no line for it, so the release's suite stopped at `missing
    /// go.sum entry for module providing package …/lungo-go`.
    #[test]
    fn test12358_a_rendered_go_mod_carries_its_requirements_into_go_sum() {
        let dir = committed(&[(
            "go.sum",
            "github.com/stretchr/testify v1.8.4 h1:TESTIFY=\ngithub.com/stretchr/testify v1.8.4/go.mod h1:TESTIFYMOD=\n",
        )]);
        let manifest = dir.path().join("go.mod");
        let rendered = "module github.com/machinefabric/tagged-urn-go\n// version: 1.54.451\n\ngo 1.22\n\n\
            // the relations run on lungo-go\nrequire github.com/machinefabric/lungo-go v1.78.3254\n\n\
            require (\n\tgithub.com/stretchr/testify v1.8.4\n\texample.com/local v0.0.0 // indirect\n)\n\n\
            replace example.com/local => ../local\n";
        let asked = std::cell::RefCell::new(Vec::new());
        let download = |module: &str, version: &str| -> Result<GoModule> {
            asked.borrow_mut().push(format!("{module}@{version}"));
            Ok(match module {
                "github.com/machinefabric/lungo-go" => GoModule {
                    sum: "h1:LUNGO=".into(),
                    go_mod_sum: "h1:LUNGOMOD=".into(),
                    requires: vec![("example.com/dep".into(), "v1.0.0".into())],
                },
                "example.com/dep" => GoModule {
                    sum: "h1:DEP=".into(),
                    go_mod_sum: "h1:DEPMOD=".into(),
                    requires: Vec::new(),
                },
                other => panic!("{other} was asked for, and go.sum already records it or it is local"),
            })
        };

        let sum = follow_into_go_sum(&manifest, rendered, &download).unwrap();
        assert_eq!(sum, Some(dir.path().join("go.sum")));
        let text = fs::read_to_string(dir.path().join("go.sum")).unwrap();
        for line in [
            "github.com/machinefabric/lungo-go v1.78.3254 h1:LUNGO=",
            "github.com/machinefabric/lungo-go v1.78.3254/go.mod h1:LUNGOMOD=",
            "example.com/dep v1.0.0/go.mod h1:DEPMOD=",
            "github.com/stretchr/testify v1.8.4 h1:TESTIFY=",
        ] {
            assert!(text.lines().any(|l| l == line), "go.sum lacks `{line}`:\n{text}");
        }
        assert!(!text.contains("example.com/dep v1.0.0 h1:"), "a dependency's module hash is not what the graph needs");
        assert!(!text.contains("example.com/local"), "a local replacement has no hash");

        asked.borrow_mut().clear();
        follow_into_go_sum(&manifest, rendered, &download).unwrap();
        assert!(asked.borrow().is_empty(), "a recorded requirement asked again: {:?}", asked.borrow());

        // A module that keeps no go.sum is not given one: a scaffold's tree
        // holds only what its author wrote.
        let bare = tempfile::tempdir().unwrap();
        let none = follow_into_go_sum(&bare.path().join("go.mod"), rendered, &download).unwrap();
        assert_eq!(none, None);
        assert!(!bare.path().join("go.sum").exists(), "a go.sum was made where the module keeps none");
        assert!(asked.borrow().is_empty(), "and nothing was asked for it");

        // A module may quote the paths of its own requirements, and a
        // dependency's `go.mod` did: the quotes are not part of the path.
        let quoted = "module m\nrequire (\n\t\"gopkg.in/check.v1\" v0.0.0-20161208181325-20d25e280405\n)\nreplace \"example.com/x\" => \"../x\"\n";
        assert_eq!(
            go_mod_requirements(quoted),
            (
                vec![("gopkg.in/check.v1".to_string(), "v0.0.0-20161208181325-20d25e280405".to_string())],
                vec!["example.com/x".to_string()]
            )
        );
    }

    /// A repository holding `files`, committed, so a lock in it is tracked.
    fn committed(files: &[(&str, &str)]) -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        for (name, text) in files {
            fs::write(dir.path().join(name), text).unwrap();
        }
        let git = |args: &[&str]| {
            let out = crate::git_backend::git_command().arg("-C").arg(dir.path()).args(args).output().unwrap();
            assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));
        };
        git(&["init", "-q"]);
        git(&["add", "-A"]);
        git(&["-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "-m", "fixture"]);
        dir
    }

    /// TEST12359: a tracked `package-lock.json` is brought up to date when the
    /// rendered `package.json` specifies its dependencies differently or names
    /// another version of its own package, and is left alone when they agree
    /// or when it is not tracked.
    ///
    /// floom-uikit's committed manifest named `capdag ^1.243.691` and its
    /// committed lock `file:../../capdag/capdag-js` — the render had switched
    /// one and not the other, and `npm ci` refuses the pair. And a lock whose
    /// own version was not compared stayed a commit behind its manifest, so
    /// every checkpoint committed it catching up.
    #[test]
    fn test12359_a_rendered_package_json_brings_its_tracked_lock_along() {
        let lock = r#"{"name":"ui","version":"1.2.3","lockfileVersion":3,"packages":{"":{"name":"ui","version":"1.2.3","dependencies":{"capdag":"file:../capdag-js"}}}}"#;
        let repo = committed(&[("package-lock.json", lock)]);
        let manifest = repo.path().join("package.json");
        let relocked = std::cell::Cell::new(0);
        let relock = |_: &Path| -> Result<()> {
            relocked.set(relocked.get() + 1);
            Ok(())
        };

        let published = r#"{"name":"ui","version":"1.2.3","dependencies":{"capdag":"^1.243.691"}}"#;
        let returned = follow_into_package_lock(&manifest, published, &relock).unwrap();
        assert_eq!(relocked.get(), 1, "a lock naming another specification is brought up to date");
        assert_eq!(returned, Some(repo.path().join("package-lock.json")), "and is staged with its manifest");

        let same = r#"{"name":"ui","version":"1.2.3","dependencies":{"capdag":"file:../capdag-js"}}"#;
        follow_into_package_lock(&manifest, same, &relock).unwrap();
        assert_eq!(relocked.get(), 1, "a lock that agrees is not rewritten");

        let next = r#"{"name":"ui","version":"1.2.4","dependencies":{"capdag":"file:../capdag-js"}}"#;
        follow_into_package_lock(&manifest, next, &relock).unwrap();
        assert_eq!(relocked.get(), 2, "a lock naming another version of its own package is brought up to date");

        let untracked = tempfile::tempdir().unwrap();
        fs::write(untracked.path().join("package-lock.json"), lock).unwrap();
        let none = follow_into_package_lock(&untracked.path().join("package.json"), published, &relock).unwrap();
        assert_eq!((none, relocked.get()), (None, 2), "an untracked lock is this machine's own");
    }

    /// TEST12671: a lock that resolves a dependency as a link to a sibling
    /// folder, while its manifest takes that dependency from the registry, is
    /// not in agreement with it — whatever the two say about specifications —
    /// and the link is out of the lock before npm is asked to bring it up to
    /// date.
    ///
    /// machinefabric-dot-com's committed manifest asked for `capdag
    /// ^1.426.27` and its committed lock recorded the same specification and
    /// resolved it as `"link": true` to `../capdag/capdag-js`: npm keeps a
    /// resolution that satisfies the range, and the working copy did. A
    /// machine that installed from the pair got the sibling checkout, which
    /// holds none of what the release packs.
    #[test]
    fn test12671_a_lock_does_not_keep_a_link_for_what_its_manifest_takes_from_the_registry() {
        let lock = r#"{"name":"site","version":"1.0.0","lockfileVersion":3,"packages":{
            "":{"name":"site","version":"1.0.0","dependencies":{"capdag":"^1.426.27","left-pad":"^1.3.0"},"devDependencies":{"kit":"file:../kit"}},
            "../capdag/capdag-js":{"name":"capdag","version":"1.427.0","dependencies":{"tagged-urn":"^1.129.4"}},
            "../capdag/capdag-js/node_modules/peggy":{"version":"5.1.0"},
            "../capdag/capdag-js-old":{"name":"unrelated","version":"1.0.0"},
            "../kit":{"name":"kit","version":"2.0.0"},
            "node_modules/capdag":{"resolved":"../capdag/capdag-js","link":true},
            "node_modules/kit":{"resolved":"../kit","link":true},
            "node_modules/left-pad":{"version":"1.3.0","resolved":"https://registry.npmjs.org/left-pad/-/left-pad-1.3.0.tgz"}}}"#;
        let repo = committed(&[("package-lock.json", lock)]);
        let manifest = repo.path().join("package.json");
        let lock_path = repo.path().join("package-lock.json");
        let seen_by_npm = std::cell::RefCell::new(Vec::<String>::new());
        let relock = |dir: &Path| -> Result<()> {
            let held: Value = serde_json::from_str(&fs::read_to_string(dir.join("package-lock.json"))?)?;
            let mut keys: Vec<String> = held["packages"].as_object().unwrap().keys().cloned().collect();
            keys.sort();
            *seen_by_npm.borrow_mut() = keys;
            Ok(())
        };

        // The specifications and the version agree: only the resolution is wrong.
        let published = r#"{"name":"site","version":"1.0.0","dependencies":{"capdag":"^1.426.27","left-pad":"^1.3.0"},"devDependencies":{"kit":"file:../kit"}}"#;
        follow_into_package_lock(&manifest, published, &relock).unwrap();
        assert_eq!(
            *seen_by_npm.borrow(),
            ["", "../capdag/capdag-js-old", "../kit", "node_modules/kit", "node_modules/left-pad"],
            "npm is asked with the link, its folder and what was under it gone — and nothing else: \
             a folder whose name only begins the same, a link the manifest does ask for, and a registry resolution all stay"
        );

        // The working copies' render: the same link is what the manifest asks for.
        fs::write(&lock_path, lock.replace(r#""capdag":"^1.426.27""#, r#""capdag":"file:../capdag/capdag-js""#)).unwrap();
        seen_by_npm.borrow_mut().clear();
        let local = r#"{"name":"site","version":"1.0.0","dependencies":{"capdag":"file:../capdag/capdag-js","left-pad":"^1.3.0"},"devDependencies":{"kit":"file:../kit"}}"#;
        follow_into_package_lock(&manifest, local, &relock).unwrap();
        assert!(seen_by_npm.borrow().is_empty(), "a link the manifest names is in agreement, and nothing is rewritten");
        assert!(fs::read_to_string(&lock_path).unwrap().contains(r#""node_modules/capdag":{"resolved":"../capdag/capdag-js","link":true}"#));
    }

    /// TEST12360: a tracked `Package.resolved` is resolved again when an exact
    /// pin of the rendered `Package.swift` is missing from it or names another
    /// version, and is left alone when every exact pin is there.
    ///
    /// capdag-objc's committed `Package.resolved` named neither tagged-urn-objc
    /// nor lungo-swift, which its `Package.swift` pinned exactly.
    #[test]
    fn test12360_a_rendered_package_swift_brings_its_tracked_resolution_along() {
        let resolved = r#"{"pins":[{"identity":"lungo-swift","kind":"remoteSourceControl","location":"https://github.com/machinefabric/lungo-swift.git","state":{"revision":"abc","version":"1.78.3254"}}],"version":2}"#;
        let repo = committed(&[("Package.resolved", resolved)]);
        let manifest = repo.path().join("Package.swift");
        let resolves = std::cell::Cell::new(0);
        let resolve = |_: &Path| -> Result<()> {
            resolves.set(resolves.get() + 1);
            Ok(())
        };
        let swift = |lungo: &str, extra: &str| {
            format!(
                "let package = Package(dependencies: [\n        .package(url: \"https://github.com/machinefabric/lungo-swift\", exact: \"{lungo}\"),\n{extra}        .package(url: \"https://github.com/unrelentingtech/SwiftCBOR.git\", from: \"0.4.7\"),\n])\n"
            )
        };

        follow_into_package_resolved(&manifest, &swift("1.78.3254", ""), &resolve).unwrap();
        assert_eq!(resolves.get(), 0, "every exact pin is resolved — `.git` or not — and `from:` is SwiftPM's");

        follow_into_package_resolved(&manifest, &swift("1.79.0", ""), &resolve).unwrap();
        assert_eq!(resolves.get(), 1, "an exact pin at another version is resolved again");

        let missing = "        .package(url: \"https://github.com/machinefabric/tagged-urn-objc.git\", exact: \"1.50.545\"),\n";
        follow_into_package_resolved(&manifest, &swift("1.78.3254", missing), &resolve).unwrap();
        assert_eq!(resolves.get(), 2, "an exact pin the resolution does not hold is resolved");

        let local = "let package = Package(dependencies: [ .package(path: \"../lungo-swift\") ])\n";
        follow_into_package_resolved(&manifest, local, &resolve).unwrap();
        assert_eq!(resolves.get(), 2, "a local package is not pinned by version");
    }

    /// TEST11292: a rendered manifest leaves its lockfile agreeing with it.
    ///
    /// A render bumps the version in `Cargo.toml`; `Cargo.lock` kept the old
    /// one until somebody built, so the COMMITTED pair disagreed and
    /// `cargo build --locked` refused it. Invisible locally, because an
    /// ordinary build just fixes the lock — and fatal anywhere reproducibility
    /// is the point. A test guest allocated, booted, installed a toolchain and
    /// spent four minutes reaching `cannot update the lock file … because
    /// --locked was passed`, about a workspace that builds on the machine that
    /// sent it.
    #[test]
    fn test11292_a_rendered_manifest_carries_its_version_into_the_lockfile() {
        let directory = tempfile::tempdir().expect("a scratch directory");
        let manifest = directory.path().join("Cargo.toml");
        let lock = directory.path().join("Cargo.lock");
        fs::write(
            &lock,
            "version = 4\n\n[[package]]\nname = \"other\"\nversion = \"0.1.0\"\n\n\
             [[package]]\nname = \"wsb\"\nversion = \"1.324.5836\"\ndependencies = [\n \"other\",\n]\n",
        )
        .expect("writes");

        let rendered = "[package]\nname = \"wsb\"\nversion = \"1.325.5840\"\nedition = \"2021\"\n";
        fs::write(&manifest, rendered).expect("writes");
        follow_into_lockfile(&manifest, rendered).expect("the lockfile follows");

        let after = fs::read_to_string(&lock).expect("reads");
        assert!(after.contains("version = \"1.325.5840\""), "{after}");
        assert!(!after.contains("1.324.5836"), "the stale version is gone:\n{after}");
        // Another package's version is not this manifest's business.
        assert!(after.contains("name = \"other\"\nversion = \"0.1.0\""), "{after}");
        // And the dependency graph is cargo's, left exactly as it was.
        assert!(after.contains("dependencies = [\n \"other\",\n]"), "{after}");
    }

    /// TEST11360: a workspace MEMBER reaches the lock that governs it.
    ///
    /// A member has no lock of its own — cargo keeps one beside the workspace
    /// root and resolves every member into it. Looking only alongside the
    /// manifest meant `wsb/daemon` never updated `wsb/Cargo.lock`: the
    /// daemon's version sat three releases behind in it, and every
    /// `cargo build --locked` in the workspace was refused after a version
    /// bump, which is what a checkpoint does every time.
    #[test]
    fn test11360_a_workspace_member_updates_the_workspace_lockfile() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        fs::write(
            root.join("Cargo.toml"),
            "[workspace]\nmembers = [\"daemon\"]\nresolver = \"2\"\n",
        )
        .unwrap();
        let lock = root.join("Cargo.lock");
        fs::write(
            &lock,
            "version = 4\n\n[[package]]\nname = \"wsb-daemon\"\nversion = \"1.325.5840\"\n",
        )
        .unwrap();
        let member = root.join("daemon");
        fs::create_dir_all(&member).unwrap();
        let manifest = member.join("Cargo.toml");

        let rendered = "[package]\nname = \"wsb-daemon\"\nversion = \"1.328.5871\"\n";
        fs::write(&manifest, rendered).unwrap();
        follow_into_lockfile(&manifest, rendered).expect("the workspace lockfile follows");

        let after = fs::read_to_string(&lock).unwrap();
        assert!(after.contains("version = \"1.328.5871\""), "{after}");
        assert!(!after.contains("1.325.5840"), "the stale version is gone:\n{after}");
        // And no lock was invented beside the member, which has none by design.
        assert!(!member.join("Cargo.lock").exists());
    }

    /// TEST11361: a crate outside any workspace keeps its own lock.
    #[test]
    fn test11361_a_standalone_crate_updates_its_own_lockfile() {
        let place = TempDir::new().unwrap();
        let root = place.path();
        let manifest = root.join("Cargo.toml");
        let lock = root.join("Cargo.lock");
        fs::write(
            &lock,
            "version = 4\n\n[[package]]\nname = \"alone\"\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let rendered = "[package]\nname = \"alone\"\nversion = \"0.2.0\"\n";
        fs::write(&manifest, rendered).unwrap();
        follow_into_lockfile(&manifest, rendered).expect("its own lockfile follows");
        assert!(fs::read_to_string(&lock).unwrap().contains("0.2.0"));
    }

    /// TEST11362: a member of a workspace that has no lock rewrites nothing.
    ///
    /// The walk stops at the workspace root whether or not a lock is there, so
    /// a member cannot reach past it and rewrite an unrelated lock belonging to
    /// some enclosing tree.
    #[test]
    fn test11362_a_member_never_reaches_past_its_workspace_root() {
        let outer = TempDir::new().unwrap();
        let root = outer.path();
        // An unrelated lock further up, naming the same package.
        let intruder = root.join("Cargo.lock");
        fs::write(
            &intruder,
            "version = 4\n\n[[package]]\nname = \"member\"\nversion = \"9.9.9\"\n",
        )
        .unwrap();
        fs::write(root.join("Cargo.toml"), "[workspace]\nmembers = [\"inner\"]\n").unwrap();

        let inner = root.join("inner");
        fs::create_dir_all(&inner).unwrap();
        let manifest = inner.join("Cargo.toml");
        let rendered = "[package]\nname = \"member\"\nversion = \"1.0.0\"\n";
        fs::write(&manifest, rendered).unwrap();
        follow_into_lockfile(&manifest, rendered).expect("nothing to do");
        // The workspace root HAS a lock, so that one is the governing one and
        // it is updated — this is the same case as TEST11360.
        assert!(fs::read_to_string(&intruder).unwrap().contains("1.0.0"));
    }

    /// TEST11293: nothing else is touched.
    ///
    /// A virtual workspace root declares no version, a manifest with no
    /// lockfile beside it has nothing to follow into, and a file that is not a
    /// manifest is not one. Each of these used to be reached by the same code
    /// path, and a rewrite triggered by any of them would be a rewrite nobody
    /// asked for.
    #[test]
    fn test11293_only_a_manifest_with_a_version_and_a_lockfile_is_followed() {
        let directory = tempfile::tempdir().expect("a scratch directory");

        // Not a manifest.
        let other = directory.path().join("package.json");
        fs::write(&other, "{}").expect("writes");
        follow_into_lockfile(&other, "{}").expect("nothing to do");

        // A manifest with no lockfile beside it.
        let manifest = directory.path().join("Cargo.toml");
        let rendered = "[package]\nname = \"solo\"\nversion = \"1.0.0\"\n";
        fs::write(&manifest, rendered).expect("writes");
        follow_into_lockfile(&manifest, rendered).expect("nothing to do");
        assert!(!directory.path().join("Cargo.lock").exists(), "none is created");

        // A virtual workspace root: members have versions, the root has none.
        let lock = directory.path().join("Cargo.lock");
        let original = "version = 4\n\n[[package]]\nname = \"member\"\nversion = \"2.0.0\"\n";
        fs::write(&lock, original).expect("writes");
        let virtual_root = "[workspace]\nmembers = [\"member\"]\nresolver = \"2\"\n";
        fs::write(&manifest, virtual_root).expect("writes");
        follow_into_lockfile(&manifest, virtual_root).expect("nothing to do");
        assert_eq!(fs::read_to_string(&lock).expect("reads"), original);
    }
    /// TEST12306: a workspace that states its version once carries it into the
    /// lock for every member inheriting it.
    ///
    /// A virtual root with `[workspace.package] version` is the one manifest a
    /// multi-crate workspace renders; its members say `version.workspace =
    /// true` and are never rendered. Following only a `[package]` version left
    /// lungo's lock naming every crate at the previous version after each bump,
    /// and `cargo build --locked` refused it. A member stating its own version,
    /// and a package that is not a member, keep theirs.
    #[test]
    fn test12306_a_workspace_version_follows_into_every_inheriting_member() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        for (dir, manifest) in [
            ("crates/a", "[package]\nname = \"a\"\nversion.workspace = true\n"),
            ("crates/b", "[package]\nname = \"b\"\nversion = { workspace = true }\n"),
            ("tools/own", "[package]\nname = \"own\"\nversion = \"0.3.0\"\n"),
        ] {
            fs::create_dir_all(root.join(dir)).unwrap();
            fs::write(root.join(dir).join("Cargo.toml"), manifest).unwrap();
        }
        let lock = root.join("Cargo.lock");
        fs::write(
            &lock,
            "version = 4\n\n[[package]]\nname = \"a\"\nversion = \"1.0.0\"\n\n\
             [[package]]\nname = \"b\"\nversion = \"1.0.0\"\n\n\
             [[package]]\nname = \"own\"\nversion = \"0.2.0\"\n\n\
             [[package]]\nname = \"elsewhere\"\nversion = \"1.0.0\"\n",
        )
        .unwrap();
        let manifest = root.join("Cargo.toml");
        let rendered = "[workspace]\nmembers = [\"crates/*\", \"tools/own\"]\n\n\
                        [workspace.package]\nversion = \"1.1.0\"\n";
        fs::write(&manifest, rendered).unwrap();
        follow_into_lockfile(&manifest, rendered).expect("the lockfile follows");

        let after = fs::read_to_string(&lock).unwrap();
        assert!(after.contains("name = \"a\"\nversion = \"1.1.0\""), "{after}");
        assert!(after.contains("name = \"b\"\nversion = \"1.1.0\""), "{after}");
        assert!(after.contains("name = \"own\"\nversion = \"0.2.0\""), "its own version is its own:\n{after}");
        assert!(after.contains("name = \"elsewhere\"\nversion = \"1.0.0\""), "not a member:\n{after}");

        // A member pattern this does not follow is refused, not skipped.
        let globbed = "[workspace]\nmembers = [\"cr*/a\"]\n\n[workspace.package]\nversion = \"1.2.0\"\n";
        let err = follow_into_lockfile(&manifest, globbed).unwrap_err();
        assert!(format!("{err:#}").contains("cr*/a"), "{err:#}");
    }

    /// TEST12309: a render names the lock it governs even when the lock
    /// already agrees, so the commit that stages the manifest stages it too.
    ///
    /// The pre-commit hook stages what the render wrote. A lock brought into
    /// agreement by an EARLIER render (going local after a checkpoint) was not
    /// rewritten by the commit's own render, so it was never staged: lungo's
    /// commit carried a manifest at 1.70.2879 beside a lock at 1.69.2868, and
    /// `cargo build --locked` refuses that commit.
    #[test]
    fn test12309_the_governing_lock_is_named_whether_or_not_it_changed() {
        let dir = TempDir::new().unwrap();
        let manifest = dir.path().join("Cargo.toml");
        let lock = dir.path().join("Cargo.lock");
        let rendered = "[package]\nname = \"crate\"\nversion = \"2.0.0\"\n";
        fs::write(&manifest, rendered).unwrap();
        fs::write(&lock, "version = 4\n\n[[package]]\nname = \"crate\"\nversion = \"1.0.0\"\n").unwrap();

        assert_eq!(follow_into_lockfile(&manifest, rendered).unwrap(), Some(lock.clone()), "rewritten");
        assert!(fs::read_to_string(&lock).unwrap().contains("2.0.0"));
        assert_eq!(
            follow_into_lockfile(&manifest, rendered).unwrap(),
            Some(lock.clone()),
            "already in agreement, and still the lock the commit must carry"
        );
        // A manifest no lock governs names none.
        fs::remove_file(&lock).unwrap();
        assert_eq!(follow_into_lockfile(&manifest, rendered).unwrap(), None);
    }

    use tempfile::TempDir;

    pub(super) fn make_vi(version: &str) -> VersionInfo {
        let parts: Vec<&str> = version.splitn(3, '.').collect();
        let major: u32 = parts[0].parse().unwrap_or(0);
        let minor: u32 = parts.get(1).and_then(|s| s.parse().ok()).unwrap_or(0);
        let patch: u32 = parts.get(2).and_then(|s| s.parse().ok()).unwrap_or(0);
        VersionInfo {
            major_version: format!("v{}", major),
            minor_version: minor,
            patch_version: patch,
            full_version: version.to_string(),
        }
    }

    /// Create a minimal project directory with `.wsb/state.json` and `version.txt`.
    pub(super) fn make_project(
        parent: &Path,
        name: &str,
        alias: &str,
        version: &str,
        scan_root: &Path,
    ) -> PathBuf {
        let project_dir = parent.join(name);
        fs::create_dir_all(&project_dir).unwrap();
        fs::create_dir_all(project_dir.join(".wsb")).unwrap();
        fs::write(project_dir.join("version.txt"), version).unwrap();

        let state = serde_json::json!({
            "version": 1,
            "project_name": name,
            "tools": {},
            "wstemplate_entries": [
                { "alias": alias, "root": crate::workspace_state::relative_to(scan_root, &project_dir).unwrap() }
            ]
        });
        fs::write(
            project_dir.join(".wsb").join("state.json"),
            serde_json::to_string_pretty(&state).unwrap(),
        )
        .unwrap();
        project_dir
    }

    /// A project whose root is also a git repository with one commit, so the
    /// git-derived fields resolve.
    pub(super) fn make_git_project(
        parent: &Path,
        name: &str,
        alias: &str,
        version: &str,
        scan_root: &Path,
    ) -> PathBuf {
        let project_dir = make_project(parent, name, alias, version, scan_root);
        let repo = crate::git_backend::init_repository(&project_dir).unwrap();
        crate::git_backend::configure_local_user(&repo, "Test User", "test@example.com").unwrap();
        fs::write(project_dir.join("README.md"), "hello\n").unwrap();
        // Commit the whole fixture, including the files make_project wrote, so
        // the worktree starts clean and `is_dirty` means what a test asserts.
        crate::git_backend::stage_all(&repo).unwrap();
        crate::git_backend::commit_all(&repo, "initial").unwrap();
        project_dir
    }

    // ── derive_alias ──────────────────────────────────────────────────────────

    #[test]
    fn test_derive_alias_simple_name() {
        assert_eq!(
            WstemplateEngine::derive_alias(Path::new("/path/to/myapp")),
            "myapp"
        );
    }

    #[test]
    fn test_derive_alias_hyphenated() {
        assert_eq!(
            WstemplateEngine::derive_alias(Path::new("/path/to/my-service")),
            "my_service"
        );
    }

    #[test]
    fn test_derive_alias_spaces_and_mixed_case() {
        assert_eq!(
            WstemplateEngine::derive_alias(Path::new("/path/API Service")),
            "api_service"
        );
    }

    #[test]
    fn test_derive_alias_leading_digit() {
        assert_eq!(
            WstemplateEngine::derive_alias(Path::new("/path/123project")),
            "p_123project"
        );
    }

    #[test]
    fn test_derive_alias_collapses_multiple_separators() {
        assert_eq!(
            WstemplateEngine::derive_alias(Path::new("/path/my--app__v2")),
            "my_app_v2"
        );
    }

    #[test]
    fn test_derive_alias_empty_basename_returns_project() {
        // A path that ends in separator produces an empty basename.
        assert_eq!(WstemplateEngine::derive_alias(Path::new("/")), "project");
    }

    #[test]
    fn test_derive_alias_is_deterministic() {
        let path = Path::new("/some/dir/my-cool-project");
        assert_eq!(
            WstemplateEngine::derive_alias(path),
            WstemplateEngine::derive_alias(path)
        );
    }

    // ── parse_version_string ──────────────────────────────────────────────────

    #[test]
    fn test_parse_version_string_valid() {
        let vi = parse_version_string("1.23.456").unwrap();
        assert_eq!(vi.full_version, "1.23.456");
        assert_eq!(vi.major_version, "v1");
        assert_eq!(vi.minor_version, 23);
        assert_eq!(vi.patch_version, 456);
    }

    #[test]
    fn test_parse_version_string_with_suffix() {
        let vi = parse_version_string("1.23.456-release").unwrap();
        assert_eq!(vi.full_version, "1.23.456-release");
        assert_eq!(vi.major_version, "v1");
        assert_eq!(vi.minor_version, 23);
        assert_eq!(vi.patch_version, 456);
    }

    #[test]
    fn test_parse_version_string_zeros() {
        let vi = parse_version_string("0.0.0").unwrap();
        assert_eq!(vi.full_version, "0.0.0");
        assert_eq!(vi.major_version, "v0");
        assert_eq!(vi.minor_version, 0);
        assert_eq!(vi.patch_version, 0);
    }

    #[test]
    fn test_parse_version_string_missing_patch_fails() {
        assert!(parse_version_string("1.2").is_err());
    }

    #[test]
    fn test_parse_version_string_non_numeric_fails() {
        assert!(parse_version_string("a.b.c").is_err());
    }

    #[test]
    fn test_parse_version_string_empty_fails() {
        assert!(parse_version_string("").is_err());
    }

    // ── read_version_from_path ────────────────────────────────────────────────

    #[test]
    fn test_read_version_from_path_success() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("version.txt"), "2.100.5000\n").unwrap();
        let vi = read_version_from_path(dir.path()).unwrap();
        assert_eq!(vi.full_version, "2.100.5000");
        assert_eq!(vi.minor_version, 100);
    }

    #[test]
    fn test_read_version_from_path_missing_fails_hard() {
        let dir = TempDir::new().unwrap();
        let err = read_version_from_path(dir.path()).unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("regenerating version.txt"),
            "error must mention regeneration attempt, got: {}",
            msg
        );
        // A bare directory has no workspace state, so regeneration stops there.
        // The error must name that precondition rather than the downstream git
        // history it never got far enough to read.
        assert!(
            msg.contains("workspace state"),
            "error must name the precondition that failed, got: {}",
            msg
        );
        assert!(
            msg.contains(&dir.path().display().to_string()),
            "error must identify which project failed, got: {}",
            msg
        );
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn test_read_version_from_path_regenerates_missing_version_for_managed_project() {
        let dir = TempDir::new().unwrap();
        let root = dir.path();

        fn run_git(repo_root: &Path, args: &[&str]) {
            let repo = match args {
                ["init"] => crate::git_backend::init_repository(repo_root).unwrap(),
                _ => crate::git_backend::open_repo(repo_root).unwrap(),
            };

            match args {
                ["init"] => {}
                ["config", "user.name", name] => {
                    let email = repo
                        .config_snapshot()
                        .string("user.email")
                        .map(|value| value.to_string())
                        .unwrap_or_else(|| "test@example.com".to_string());
                    crate::git_backend::configure_local_user(&repo, name, &email).unwrap();
                }
                ["config", "user.email", email] => {
                    let name = repo
                        .config_snapshot()
                        .string("user.name")
                        .map(|value| value.to_string())
                        .unwrap_or_else(|| "Test User".to_string());
                    crate::git_backend::configure_local_user(&repo, &name, email).unwrap();
                }
                ["add", path] => {
                    crate::git_backend::stage_paths(&repo, &[path.to_string()]).unwrap();
                }
                ["commit", "-m", message] => {
                    crate::git_backend::commit_all(&repo, message).unwrap();
                }
                _ => panic!("unsupported git test helper command: {args:?}"),
            }
        }

        run_git(root, &["init"]);
        run_git(root, &["config", "user.name", "Test User"]);
        run_git(root, &["config", "user.email", "test@example.com"]);
        fs::write(root.join("README.md"), "hello\n").unwrap();
        run_git(root, &["add", "README.md"]);
        run_git(root, &["commit", "-m", "initial"]);

        let _ = StateConfig::load_async(root).await.unwrap();
        // Regeneration reads the workspace state to format the version, so the
        // fixture must be a fully initialized workspace, not just a database.
        crate::workspace_state::WorkspaceState::initialize(root, Some("test-project"))
            .unwrap()
            .save(root)
            .unwrap();
        let db_path = root.join(".wsb/wsb.db");
        let config = crate::persist::global::DatabaseConfig::new(&db_path);
        let service = crate::persist::global::DatabaseService::new(&config).unwrap();
        let conn = service.get_connection().unwrap();
        conn.execute(
            "UPDATE projects SET major_version = 7 WHERE id = (SELECT id FROM projects LIMIT 1)",
            [],
        )
        .unwrap();

        let expected = crate::state::calculate_workspace_version_async(root)
            .await
            .unwrap();
        let version_path = root.join("version.txt");
        if version_path.exists() {
            fs::remove_file(&version_path).unwrap();
        }

        let actual = read_version_from_path(root).unwrap();
        assert_eq!(actual.full_version, expected.full_version);
        assert_eq!(
            fs::read_to_string(version_path).unwrap().trim(),
            expected.full_version
        );
    }

    // ── find_all_project_roots ────────────────────────────────────────────────

    #[test]
    fn test_find_all_project_roots_discovers_projects() {
        let workspace = TempDir::new().unwrap();
        make_project(
            workspace.path(),
            "alpha",
            "alpha",
            "1.0.0",
            workspace.path(),
        );
        make_project(workspace.path(), "beta", "beta", "2.0.0", workspace.path());

        let roots = find_all_project_roots(workspace.path()).unwrap();
        assert!(roots.contains_key("alpha"), "must find alpha");
        assert!(roots.contains_key("beta"), "must find beta");
        assert_eq!(roots["alpha"], workspace.path().join("alpha"));
        assert_eq!(roots["beta"], workspace.path().join("beta"));
    }

    #[test]
    fn test_find_all_project_roots_skips_target_directories() {
        let workspace = TempDir::new().unwrap();
        make_project(
            workspace.path(),
            "real_proj",
            "real_proj",
            "1.0.0",
            workspace.path(),
        );

        // Simulate a Cargo target directory with a stale state.json inside.
        let target_ws = workspace.path().join("target").join(".wsb");
        fs::create_dir_all(&target_ws).unwrap();
        let fake_state = serde_json::json!({
            "version": 1,
            "project_name": "fake",
            "tools": {},
            "wstemplate_entries": [{ "alias": "should_be_skipped", "root": workspace.path().to_str().unwrap() }]
        });
        fs::write(
            target_ws.join("state.json"),
            serde_json::to_string_pretty(&fake_state).unwrap(),
        )
        .unwrap();

        let roots = find_all_project_roots(workspace.path()).unwrap();
        assert!(
            roots.contains_key("real_proj"),
            "real project must be found"
        );
        assert!(
            !roots.contains_key("should_be_skipped"),
            "projects inside target/ must be skipped"
        );
    }

    #[test]
    fn test_find_all_project_roots_defaults_alias_when_entries_are_empty() {
        let workspace = TempDir::new().unwrap();
        let project_root = workspace.path().join("wsb");
        let state_dir = project_root.join(".wsb");
        fs::create_dir_all(&state_dir).unwrap();
        fs::write(project_root.join("version.txt"), "1.0.0").unwrap();
        fs::write(
            state_dir.join("state.json"),
            serde_json::json!({
                "version": 1,
                "project_name": "wsb",
                "tools": {},
                "wstemplate_entries": [],
                "completion_hint_shown": true
            })
            .to_string(),
        )
        .unwrap();

        let roots = find_all_project_roots(workspace.path()).unwrap();
        assert_eq!(roots.get("wsb"), Some(&project_root));
    }

    #[test]
    fn test_find_all_project_roots_duplicate_alias_fails_hard() {
        let workspace = TempDir::new().unwrap();
        make_project(
            workspace.path(),
            "proj_a",
            "shared_alias",
            "1.0.0",
            workspace.path(),
        );
        make_project(
            workspace.path(),
            "proj_b",
            "shared_alias",
            "2.0.0",
            workspace.path(),
        );

        let err = find_all_project_roots(workspace.path()).unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("shared_alias"),
            "error must name the duplicate alias, got: {}",
            msg
        );
    }

    // ── discover_all ─────────────────────────────────────────────────────────

    #[test]
    fn test_discover_all_finds_wstemplate_files() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(
            workspace.path(),
            "myapp",
            "myapp",
            "1.0.0",
            workspace.path(),
        );
        fs::write(
            proj.join("Cargo.toml.wstemplate"),
            "version = \"{{ project.version }}\"",
        )
        .unwrap();
        fs::write(proj.join("README.md"), "not a template").unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("myapp".to_string()),
            "myapp".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let found = engine.discover_all().unwrap();
        assert_eq!(found.len(), 1);
        assert!(found[0].ends_with("Cargo.toml.wstemplate"));
    }

    // ── discover_relevant ─────────────────────────────────────────────────────

    #[test]
    fn test_discover_relevant_includes_own_templates() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(
            workspace.path(),
            "self_proj",
            "self_proj",
            "1.0.0",
            workspace.path(),
        );
        let other = make_project(
            workspace.path(),
            "other",
            "other",
            "2.0.0",
            workspace.path(),
        );

        // Own template (under project_root) — always relevant.
        fs::write(proj.join("a.txt.wstemplate"), "{{ project.version }}").unwrap();
        // Template in other project, does NOT reference self_proj.
        fs::write(other.join("b.txt.wstemplate"), "{{ project.version }}").unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("self_proj".to_string()),
            "self_proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let project_roots = find_all_project_roots(workspace.path()).unwrap();
        let relevant = engine.discover_relevant(&project_roots).unwrap();
        assert_eq!(relevant.len(), 1, "only own template must be included");
        assert!(relevant[0].starts_with(&proj));
    }

    #[test]
    fn test_discover_relevant_includes_foreign_template_referencing_self() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "lib", "lib", "3.0.0", workspace.path());
        let consumer = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        // Consumer's template references lib (self_alias = "lib").
        fs::write(
            consumer.join("Cargo.toml.wstemplate"),
            "dep_version = \"{{ projects.lib.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("3.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let project_roots = find_all_project_roots(workspace.path()).unwrap();
        let relevant = engine.discover_relevant(&project_roots).unwrap();
        assert_eq!(relevant.len(), 1, "consumer's template must be included");
        assert!(relevant[0].starts_with(&consumer));
    }

    #[test]
    fn test_discover_relevant_skips_unrelated_templates() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "lib", "lib", "1.0.0", workspace.path());
        let unrelated = make_project(
            workspace.path(),
            "other",
            "other",
            "2.0.0",
            workspace.path(),
        );

        // unrelated template only uses project.version — no reference to "lib".
        fs::write(unrelated.join("x.txt.wstemplate"), "{{ project.version }}").unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let project_roots = find_all_project_roots(workspace.path()).unwrap();
        let relevant = engine.discover_relevant(&project_roots).unwrap();
        assert!(relevant.is_empty(), "unrelated template must be skipped");
    }

    #[test]
    fn test_discover_relevant_root_project_does_not_claim_subproject_templates() {
        // When project_root == scan_root (root project), templates under
        // subprojects must NOT be claimed as "own".
        let workspace = TempDir::new().unwrap();

        // Root project at workspace level.
        let root = make_project(workspace.path(), "root", "root", "9.0.0", workspace.path());
        // Subproject inside root.
        let sub = make_project(&root, "sub", "sub", "1.0.0", workspace.path());

        // Root's own template.
        fs::write(root.join("root.txt.wstemplate"), "{{ project.version }}").unwrap();
        // Sub's own template — must NOT be claimed by root.
        fs::write(sub.join("sub.txt.wstemplate"), "{{ project.version }}").unwrap();

        let engine = WstemplateEngine::new(
            make_vi("9.0.0"),
            Some("root".to_string()),
            "root".to_string(),
            root.clone(),
            workspace.path().to_path_buf(),
        );

        let project_roots = find_all_project_roots(workspace.path()).unwrap();
        let relevant = engine.discover_relevant(&project_roots).unwrap();

        // Only root's own template should be relevant.
        assert_eq!(
            relevant.len(),
            1,
            "sub's template must not be claimed by root"
        );
        assert!(
            relevant[0].ends_with("root.txt.wstemplate"),
            "only root's own template, got: {}",
            relevant[0].display()
        );
    }

    #[test]
    fn test_render_root_project_does_not_clobber_subproject_versions() {
        // When running wsb update from a root project that encompasses subprojects,
        // subproject templates must get their OWN version, not the root's version.
        let workspace = TempDir::new().unwrap();

        let root = make_project(workspace.path(), "root", "root", "9.0.0", workspace.path());
        let sub = make_project(&root, "sub", "sub", "1.5.100", workspace.path());

        // Sub's template references root's version.
        fs::write(
            sub.join("file.txt.wstemplate"),
            "root={{ projects.root.version }} own={{ project.version }}",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("9.0.0"),
            Some("root".to_string()),
            "root".to_string(),
            root.clone(),
            workspace.path().to_path_buf(),
        );

        let rendered = engine.render_relevant().unwrap();
        assert_eq!(rendered.len(), 1, "sub's template references root");

        let content = fs::read_to_string(sub.join("file.txt")).unwrap();
        assert!(
            content.contains("root=9.0.0"),
            "root version must be the freshly computed one, got: {}",
            content
        );
        assert!(
            content.contains("own=1.5.100"),
            "own version must come from sub's version.txt (not root's), got: {}",
            content
        );
    }

    /// TEST12441: rendering a project follows its own manifests' locks and not
    /// its peers'.
    ///
    /// A peer's template that references the project is rendered with it, to
    /// keep the peer's pin current. Its lock was followed too — resolved
    /// against everything the peer pins — and in the middle of a release that
    /// cannot agree: committing tagged-urn after lungo's release rendered
    /// capdag-objc, SwiftPM refused its pins, and tagged-urn's own commit
    /// failed. Cargo's lock is the one followed offline, so it is what shows
    /// which locks were reached.
    #[test]
    fn test12441_only_the_projects_own_locks_are_followed() {
        let workspace = TempDir::new().unwrap();
        let lib = make_project(workspace.path(), "lib", "lib", "2.0.0", workspace.path());
        let app = make_project(workspace.path(), "app", "app", "3.0.0", workspace.path());

        fs::write(
            lib.join("Cargo.toml.wstemplate"),
            "[package]\nname = \"lib\"\nversion = \"{{ project.version }}\"\n",
        )
        .unwrap();
        fs::write(lib.join("Cargo.lock"), "version = 4\n\n[[package]]\nname = \"lib\"\nversion = \"1.0.0\"\n").unwrap();
        fs::write(
            app.join("Cargo.toml.wstemplate"),
            "[package]\nname = \"app\"\nversion = \"{{ project.version }}\"\n# lib {{ projects.lib.version }}\n",
        )
        .unwrap();
        let app_lock = "version = 4\n\n[[package]]\nname = \"app\"\nversion = \"0.0.1\"\n";
        fs::write(app.join("Cargo.lock"), app_lock).unwrap();

        let engine = WstemplateEngine::new(
            make_vi("2.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            lib.clone(),
            workspace.path().to_path_buf(),
        );
        let rendered = engine.render_relevant().unwrap();
        assert_eq!(rendered.len(), 2, "its own template and the peer's that references it");

        assert!(
            fs::read_to_string(lib.join("Cargo.lock")).unwrap().contains("version = \"2.0.0\""),
            "the project's own lock follows its manifest"
        );
        assert!(
            fs::read_to_string(app.join("Cargo.toml")).unwrap().contains("# lib 2.0.0"),
            "the peer's manifest is rendered with the project's version"
        );
        assert_eq!(
            fs::read_to_string(app.join("Cargo.lock")).unwrap(),
            app_lock,
            "the peer's lock is the peer's to follow"
        );
    }

    // ── render_relevant ───────────────────────────────────────────────────────

    #[test]
    fn test_render_relevant_renders_own_template_with_current_version() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(
            workspace.path(),
            "mylib",
            "mylib",
            "5.10.2000",
            workspace.path(),
        );

        fs::write(
            proj.join("Cargo.toml.wstemplate"),
            "version = \"{{ project.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("5.10.2000"),
            Some("mylib".to_string()),
            "mylib".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let rendered = engine.render_relevant().unwrap();
        assert_eq!(rendered.len(), 1);

        let content = fs::read_to_string(proj.join("Cargo.toml")).unwrap();
        assert_eq!(content, "version = \"5.10.2000\"");
    }

    #[test]
    fn test_render_relevant_resolves_peer_alias_dynamically() {
        let workspace = TempDir::new().unwrap();
        // lib is the project being updated.
        let lib = make_project(workspace.path(), "lib", "lib", "3.0.0", workspace.path());
        // app depends on lib.
        let app = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        fs::write(
            app.join("Cargo.toml.wstemplate"),
            "lib_dep = \"{{ projects.lib.version }}\"\nown = \"{{ project.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("3.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            lib.clone(),
            workspace.path().to_path_buf(),
        );

        let rendered = engine.render_relevant().unwrap();
        assert_eq!(rendered.len(), 1, "app's template must be rendered");

        let content = fs::read_to_string(app.join("Cargo.toml")).unwrap();
        // app's own version comes from app's version.txt = "1.0.0"
        assert!(
            content.contains("lib_dep = \"3.0.0\""),
            "lib version must be the freshly-computed one"
        );
        assert!(
            content.contains("own = \"1.0.0\""),
            "own version must come from app's version.txt"
        );
    }

    #[test]
    fn test_render_relevant_fails_hard_on_unresolvable_alias() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(
            workspace.path(),
            "myapp",
            "myapp",
            "1.0.0",
            workspace.path(),
        );

        // Template references an alias that has no matching state.json.
        fs::write(
            proj.join("file.txt.wstemplate"),
            "v = \"{{ projects.ghost_dep.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("myapp".to_string()),
            "myapp".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let err = engine.render_relevant().unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("ghost_dep"),
            "error must name the unresolvable alias, got: {}",
            msg
        );
        assert!(
            msg.contains("Known aliases:"),
            "error must list known aliases, got: {}",
            msg
        );
        assert!(
            msg.contains("myapp"),
            "known aliases must include myapp, got: {}",
            msg
        );
    }

    #[test]
    fn test_render_relevant_fails_hard_when_version_txt_missing() {
        let workspace = TempDir::new().unwrap();
        let lib = make_project(workspace.path(), "lib", "lib", "1.0.0", workspace.path());
        let app = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        // Remove app's version.txt to simulate never-updated project.
        fs::remove_file(app.join("version.txt")).unwrap();

        // app's template references lib — so lib's update will try to render it.
        fs::write(
            app.join("file.txt.wstemplate"),
            "v = \"{{ projects.lib.version }}\"\nown = \"{{ project.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            lib.clone(),
            workspace.path().to_path_buf(),
        );

        // The render must fail because app has no version.txt.
        let err = engine.render_relevant().unwrap_err();
        let msg = format!("{:#}", err);
        assert!(
            msg.contains("version.txt"),
            "error must mention version.txt, got: {}",
            msg
        );
    }

    // ── project facts in rendered output ──────────────────────────────────────

    #[test]
    fn test_render_stamps_the_published_tag_not_the_version_being_built() {
        // The motivating case: version.txt is bumped on every commit, so it is
        // structurally ahead of the newest published tag. A pin that an outside
        // consumer must resolve has to name the tag that actually exists.
        let workspace = TempDir::new().unwrap();
        let dep = make_git_project(workspace.path(), "dep", "dep", "1.649.0", workspace.path());
        let app = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        let repo = crate::git_backend::open_repo(&dep).unwrap();
        crate::git_backend::create_tag(&repo, "v1.648.6494", "release").unwrap();

        fs::write(
            app.join("deps.txt.wstemplate"),
            "published={{ projects.dep.latest_version }}\nbuilding={{ projects.dep.version }}\ntag={{ projects.dep.latest_tag }}",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.649.0"),
            Some("dep".to_string()),
            "dep".to_string(),
            dep.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(app.join("deps.txt")).unwrap();
        assert!(
            content.contains("published=1.648.6494"),
            "the pin must name the published tag, got: {content}"
        );
        assert!(
            content.contains("building=1.649.0"),
            "the calculated version must stay available, got: {content}"
        );
        assert!(
            content.contains("tag=v1.648.6494"),
            "latest_tag must be verbatim, got: {content}"
        );
    }

    #[test]
    fn test_render_reports_why_a_field_does_not_apply() {
        // A dependency that has never been published cannot supply a pin, and
        // the failure must say so instead of stamping an empty version.
        let workspace = TempDir::new().unwrap();
        let dep = make_git_project(workspace.path(), "dep", "dep", "1.0.0", workspace.path());
        let app = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        fs::write(
            app.join("deps.txt.wstemplate"),
            "dep = \"{{ projects.dep.latest_version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("dep".to_string()),
            "dep".to_string(),
            dep.clone(),
            workspace.path().to_path_buf(),
        );

        let err = format!("{:#}", engine.render_relevant().unwrap_err());
        assert!(err.contains("latest_version"), "got: {err}");
        assert!(err.contains("has no tags"), "got: {err}");
        assert!(
            !app.join("deps.txt").exists(),
            "a template that cannot resolve must not produce a half-written file"
        );
    }

    #[test]
    fn test_render_rejects_an_unknown_field_before_writing_anything() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "1.0.0", workspace.path());
        fs::write(
            proj.join("out.txt.wstemplate"),
            "{{ project.release_date_of_next_version }}",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let err = format!("{:#}", engine.render_relevant().unwrap_err());
        assert!(
            err.contains("is not a wstemplate project field"),
            "got: {err}"
        );
        assert!(
            err.contains("latest_tag"),
            "the error must list what is available, got: {err}"
        );
    }

    #[test]
    fn test_render_exposes_identity_and_head_state_of_a_referenced_project() {
        let workspace = TempDir::new().unwrap();
        let ext = workspace.path().join("ext");
        fs::create_dir_all(&ext).unwrap();
        let dep = make_git_project(&ext, "gtest", "gtest", "1.0.0", workspace.path());
        let app = make_project(workspace.path(), "app", "app", "1.0.0", workspace.path());

        fs::write(
            app.join("deps.txt.wstemplate"),
            "path={{ projects.gtest.relative_path }}\ncommit={{ projects.gtest.short_commit }}\n\
             branch={{ projects.gtest.branch }}\nname={{ projects.gtest.name }}\n\
             dirty={{ projects.gtest.is_dirty }}",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("gtest".to_string()),
            "gtest".to_string(),
            dep.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(app.join("deps.txt")).unwrap();
        assert!(
            content.contains("path=ext/gtest"),
            "a nested project must report its path from the workspace root, got: {content}"
        );
        assert!(
            content.contains("name=gtest"),
            "peer names must resolve from their own state.json, got: {content}"
        );
        assert!(content.contains("dirty=false"), "got: {content}");

        let head = crate::git_backend::open_repo(&dep)
            .unwrap()
            .head_commit()
            .unwrap()
            .id()
            .to_hex()
            .to_string();
        assert!(
            content.contains(&format!("commit={}", &head[..7])),
            "got: {content}"
        );
        let branch =
            crate::git_backend::current_branch(&crate::git_backend::open_repo(&dep).unwrap())
                .unwrap();
        assert!(
            content.contains(&format!("branch={branch}")),
            "got: {content}"
        );
    }

    #[test]
    fn test_booleans_render_as_booleans_so_conditionals_work() {
        // is_dirty must be a real boolean: the string "false" is truthy in Tera,
        // which would invert every conditional built on it.
        let workspace = TempDir::new().unwrap();
        let proj = make_git_project(workspace.path(), "proj", "proj", "1.0.0", workspace.path());
        fs::write(
            proj.join("out.txt.wstemplate"),
            "{% if project.is_dirty %}dirty{% else %}clean{% endif %}",
        )
        .unwrap();
        // Commit the template itself: an untracked file would make the worktree
        // dirty, and the truthy branch cannot distinguish a boolean from a string.
        let repo = crate::git_backend::open_repo(&proj).unwrap();
        crate::git_backend::stage_all(&repo).unwrap();
        crate::git_backend::commit_all(&repo, "add template").unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        assert_eq!(fs::read_to_string(proj.join("out.txt")).unwrap(), "clean");
    }

    // ── the rendered file's own syntax is not template syntax ─────────────────

    #[test]
    fn test_render_leaves_the_output_files_own_syntax_alone() {
        // A pyproject.toml carries `[project.optional-dependencies]`. Reading
        // that as `project.optional` would reject a perfectly valid template.
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "2.5.0", workspace.path());

        fs::write(
            proj.join("pyproject.toml.wstemplate"),
            "[project]\nname = \"demo\"\nversion = \"{{ project.version }}\"\n\n\
             [project.optional-dependencies]\ndev = [\"pytest\"]\n\n\
             [project.urls]\nHome = \"https://example.invalid\"\n",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("2.5.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(proj.join("pyproject.toml")).unwrap();
        assert!(content.contains("version = \"2.5.0\""), "got: {content}");
        assert!(
            content.contains("[project.optional-dependencies]"),
            "the section header must survive untouched, got: {content}"
        );
        assert!(content.contains("[project.urls]"), "got: {content}");
    }

    #[test]
    fn test_a_quoted_alias_inside_a_block_does_not_resolve_a_project() {
        // The alias does not exist. If the string literal were read as a
        // reference the render would fail trying to resolve it.
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "1.0.0", workspace.path());

        fs::write(
            proj.join("out.txt.wstemplate"),
            "{{ \"projects.ghost.version\" }} is the syntax, {{ project.version }} is the value",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(proj.join("out.txt")).unwrap();
        assert_eq!(
            content,
            "projects.ghost.version is the syntax, 1.0.0 is the value"
        );
    }

    #[test]
    fn test_selection_ignores_a_literal_mention_of_the_alias() {
        // A foreign file that merely talks about the alias is not a consumer of
        // it, and must not be rendered when that project updates.
        let workspace = TempDir::new().unwrap();
        let lib = make_project(workspace.path(), "lib", "lib", "1.0.0", workspace.path());
        let docs = make_project(workspace.path(), "docs", "docs", "1.0.0", workspace.path());

        fs::write(
            docs.join("guide.md.wstemplate"),
            "Write projects.lib.version to stamp the library version.\n\
             This file is version {{ project.version }}.\n",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("lib".to_string()),
            "lib".to_string(),
            lib.clone(),
            workspace.path().to_path_buf(),
        );

        let rendered = engine.render_relevant().unwrap();
        assert!(
            rendered.is_empty(),
            "a prose mention must not make the template relevant, rendered: {rendered:?}"
        );
        assert!(!docs.join("guide.md").exists());
    }

    #[test]
    fn test_a_raw_block_documents_syntax_without_resolving_it() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "3.0.0", workspace.path());

        fs::write(
            proj.join("guide.md.wstemplate"),
            "Use {% raw %}{{ projects.ghost.version }}{% endraw %} in your template.\n\
             Rendered with proj {{ project.version }}.\n",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("3.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(proj.join("guide.md")).unwrap();
        assert!(
            content.contains("{{ projects.ghost.version }}"),
            "raw content must reach the output verbatim, got: {content}"
        );
        assert!(content.contains("proj 3.0.0"), "got: {content}");
    }

    #[test]
    fn test_iterating_projects_sees_every_project_not_just_the_named_ones() {
        // Nothing names `beta`, so resolving only literal references would emit
        // a silently incomplete list.
        let workspace = TempDir::new().unwrap();
        let alpha = make_project(
            workspace.path(),
            "alpha",
            "alpha",
            "1.0.0",
            workspace.path(),
        );
        make_project(workspace.path(), "beta", "beta", "2.0.0", workspace.path());

        fs::write(
            alpha.join("manifest.txt.wstemplate"),
            "{% for alias, entry in projects %}{{ alias }}={{ entry.version }}\n{% endfor %}",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("alpha".to_string()),
            "alpha".to_string(),
            alpha.clone(),
            workspace.path().to_path_buf(),
        );
        engine.render_relevant().unwrap();

        let content = fs::read_to_string(alpha.join("manifest.txt")).unwrap();
        assert!(content.contains("alpha=1.0.0"), "got: {content}");
        assert!(
            content.contains("beta=2.0.0"),
            "iteration must see projects no reference names, got: {content}"
        );
    }

    #[test]
    fn test_a_malformed_template_names_the_file_and_the_line() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "1.0.0", workspace.path());
        fs::write(
            proj.join("out.txt.wstemplate"),
            "fine\n{{ project.version\nnever closed\n",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let err = format!("{:#}", engine.render_relevant().unwrap_err());
        assert!(err.contains("out.txt.wstemplate"), "got: {err}");
        assert!(err.contains("line 2"), "got: {err}");
        assert!(err.contains("never closed"), "got: {err}");
    }

    #[test]
    fn test_an_unresolvable_field_points_at_the_line_that_uses_it() {
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "1.0.0", workspace.path());
        fs::write(
            proj.join("out.txt.wstemplate"),
            "version = {{ project.version }}\nname = {{ project.name }}\ntag = {{ project.latest_tag }}\n",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("proj".to_string()),
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let err = format!("{:#}", engine.render_relevant().unwrap_err());
        assert!(
            err.contains("out.txt.wstemplate:3"),
            "the error must point at the offending line, got: {err}"
        );
        assert!(err.contains("not a git repository"), "got: {err}");
    }

    #[test]
    fn test_render_relevant_own_template_does_not_need_version_txt() {
        // Own templates (under project_root) must render without version.txt in
        // other projects — no dynamic resolution is needed.
        let workspace = TempDir::new().unwrap();
        let proj = make_project(workspace.path(), "proj", "proj", "7.0.0", workspace.path());

        // Template only uses project.version — no peer references.
        fs::write(
            proj.join("version.h.wstemplate"),
            "#define VERSION \"{{ project.version }}\"",
        )
        .unwrap();

        let engine = WstemplateEngine::new(
            make_vi("7.0.0"),
            None,
            "proj".to_string(),
            proj.clone(),
            workspace.path().to_path_buf(),
        );

        let rendered = engine.render_relevant().unwrap();
        assert_eq!(rendered.len(), 1);
        let content = fs::read_to_string(proj.join("version.h")).unwrap();
        assert_eq!(content, "#define VERSION \"7.0.0\"");
    }
    // TEST8962: a template inside a git submodule is never the parent's. Ownership decided from `.wsb/state.json` alone claims an unregistered submodule's templates and stamps the PARENT's version into them — the state file is machine-local and absent on a fresh clone
    #[test]
    fn test8962_a_template_inside_a_submodule_is_not_the_parents() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();

        // A parent git repository with one committed file.
        run_git(root, &["init", "-q", "-b", "main"]);
        run_git(root, &["config", "user.email", "t@t"]);
        run_git(root, &["config", "user.name", "t"]);
        fs::write(root.join("README"), "parent\n").unwrap();
        run_git(root, &["add", "README"]);
        run_git(root, &["commit", "-qm", "parent"]);

        // A submodule with its OWN .wstemplate, and deliberately NO
        // .wsb/state.json — the state exactly reproduced from a fresh clone.
        let child_src = TempDir::new().unwrap();
        run_git(child_src.path(), &["init", "-q", "-b", "main"]);
        run_git(child_src.path(), &["config", "user.email", "t@t"]);
        run_git(child_src.path(), &["config", "user.name", "t"]);
        fs::write(
            child_src.path().join("package.json.wstemplate"),
            "{\"version\": \"{{ project.version }}\"}",
        )
        .unwrap();
        fs::write(child_src.path().join("version.txt"), "2.0.0").unwrap();
        run_git(child_src.path(), &["add", "."]);
        run_git(child_src.path(), &["commit", "-qm", "child"]);
        run_git(
            root,
            &[
                "-c",
                "protocol.file.allow=always",
                "submodule",
                "add",
                "-q",
                child_src.path().to_str().unwrap(),
                "child",
            ],
        );

        fs::create_dir_all(root.join(".wsb")).unwrap();
        let engine = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("parent".to_string()),
            "parent".to_string(),
            root.to_path_buf(),
            root.to_path_buf(),
        );

        let template = root.join("child/package.json.wstemplate");
        assert!(template.is_file(), "the submodule's template is present");

        let project_roots = find_all_project_roots(root).unwrap();
        assert!(
            !project_roots
                .values()
                .any(|p| p == &root.join("child")),
            "the submodule is deliberately unregistered — this is the fresh-clone state"
        );

        assert!(
            !engine.is_own_template(&template, &project_roots),
            "an unregistered submodule's template must not be claimed by the parent; \
             claiming it stamps the parent's version into the submodule's manifest"
        );

        // And the parent's own template still is its own, so the rule
        // discriminates rather than disowning everything.
        fs::write(root.join("own.txt.wstemplate"), "{{ project.version }}").unwrap();
        assert!(
            engine.is_own_template(&root.join("own.txt.wstemplate"), &project_roots),
            "the parent still owns the templates that are actually its own"
        );
    }

    fn run_git(dir: &Path, args: &[&str]) {
        // Through the scoped spawner, like every other git call in this crate:
        // an inherited GIT_DIR overrides current_dir and would silently drive a
        // different repository than the fixture just built.
        let out = crate::git_backend::git_command()
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

#[cfg(test)]
mod environment_tests {
    use super::tests::{make_git_project, make_project, make_vi};
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    fn render(root: &Path, project: &Path, alias: &str) -> Result<Vec<RenderedTemplate>> {
        WstemplateEngine::new(
            make_vi("1.0.0"),
            Some(alias.to_string()),
            alias.to_string(),
            project.to_path_buf(),
            root.to_path_buf(),
        )
        .render_relevant()
    }

    /// TEST10100: the environment decides which section of a manifest is
    /// written.
    ///
    /// The point of having it: the same template renders a published dependency
    /// ordinarily, and a path to the working directory when a variable says so
    /// — so a change to a library can be built against without being committed,
    /// tagged and published first.
    #[test]
    fn test10100_the_environment_chooses_which_section_is_rendered() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();

        let lib = make_git_project(root, "thelib", "thelib", "2.5.0", root);
        crate::git_backend::create_tag(
            &crate::git_backend::open_repo(&lib).unwrap(),
            "v2.4.0",
            "released",
        )
        .unwrap();
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(
            app.join("Cargo.toml.wstemplate"),
            "[dependencies]\n\
             {%- if env.WSB_TEST_LOCAL_LIBS %}\n\
             thelib = { path = \"{{ projects.thelib.path_from_here }}\" }\n\
             {%- else %}\n\
             thelib = \"{{ projects.thelib.latest_version }}\"\n\
             {%- endif %}\n",
        )
        .unwrap();

        // Ordinarily: the published reference.
        std::env::remove_var("WSB_TEST_LOCAL_LIBS");
        render(root, &app, "theapp").expect("the ordinary render");
        let published = fs::read_to_string(app.join("Cargo.toml")).unwrap();
        assert!(published.contains("thelib = \"2.4.0\""), "{published}");
        assert!(!published.contains("path ="), "{published}");

        // With the variable set: the working directory, as a relative path this
        // template did not have to know.
        std::env::set_var("WSB_TEST_LOCAL_LIBS", "1");
        render(root, &app, "theapp").expect("the local render");
        let local = fs::read_to_string(app.join("Cargo.toml")).unwrap();
        std::env::remove_var("WSB_TEST_LOCAL_LIBS");
        assert!(local.contains("thelib = { path = \"../thelib\" }"), "{local}");
        assert!(!local.contains("2.4.0"), "{local}");
    }

    /// TEST10101: set-and-empty is unset, and a value is compared as a value.
    ///
    /// It reads the way a shell does. `WSB_X=` is how a shell empties a
    /// variable it cannot unset, and a template that took it as "set" would
    /// make the obvious way to turn something off turn it on. Anything else is
    /// true — including `0`, which is a value and not a denial, so a template
    /// that means to test a value writes the test.
    #[test]
    fn test10101_an_empty_variable_reads_as_unset_and_a_value_is_compared() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(
            app.join("state.txt.wstemplate"),
            "presence={% if env.WSB_TEST_MODE %}yes{% else %}no{% endif %} \
             local={% if env.WSB_TEST_MODE == \"local\" %}yes{% else %}no{% endif %} \
             absent={% if not env.WSB_TEST_MODE %}yes{% else %}no{% endif %}\n",
        )
        .unwrap();

        let read = |value: Option<&str>| {
            match value {
                Some(text) => std::env::set_var("WSB_TEST_MODE", text),
                None => std::env::remove_var("WSB_TEST_MODE"),
            }
            render(root, &app, "theapp").expect("the render");
            fs::read_to_string(app.join("state.txt")).unwrap()
        };

        assert_eq!(read(None).trim(), "presence=no local=no absent=yes");
        assert_eq!(
            read(Some("")).trim(),
            "presence=no local=no absent=yes",
            "an empty value is the same state as no value, as it is in a shell"
        );
        assert_eq!(read(Some("local")).trim(), "presence=yes local=yes absent=no");
        assert_eq!(
            read(Some("0")).trim(),
            "presence=yes local=no absent=no",
            "'0' is a value that was set, not a denial"
        );
        std::env::remove_var("WSB_TEST_MODE");
    }

    /// TEST20010: a run's own variable is seen by its templates, wins over
    /// the process's, and is never put into the process's environment.
    ///
    /// The local render used to be produced by setting the variable for the
    /// whole process and restoring it afterwards. Every thread shares that
    /// environment, so every render running meanwhile was produced as local
    /// too, and a check that the variable was unset afterwards failed whenever
    /// two of them overlapped.
    #[test]
    fn test20010_a_runs_variable_is_its_own() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(
            app.join("state.txt.wstemplate"),
            "{% if env.WSB_TEST_RUN_ONLY %}{{ env.WSB_TEST_RUN_ONLY }}{% else %}unset{% endif %}\n",
        )
        .unwrap();
        let render_with = |cache: Arc<RunCache>| {
            WstemplateEngine::with_cache(
                make_vi("1.0.0"),
                Some("theapp".to_string()),
                "theapp".to_string(),
                app.clone(),
                root.to_path_buf(),
                cache,
            )
            .render_relevant()
            .expect("the render");
            fs::read_to_string(app.join("state.txt")).unwrap()
        };

        std::env::remove_var("WSB_TEST_RUN_ONLY");
        assert_eq!(render_with(RunCache::new()).trim(), "unset");
        assert_eq!(render_with(RunCache::with_variable("WSB_TEST_RUN_ONLY", "local")).trim(), "local");
        assert!(
            std::env::var_os("WSB_TEST_RUN_ONLY").is_none(),
            "the run's variable leaked into the process's environment"
        );

        std::env::set_var("WSB_TEST_RUN_ONLY", "process");
        let both = render_with(RunCache::with_variable("WSB_TEST_RUN_ONLY", "run"));
        std::env::remove_var("WSB_TEST_RUN_ONLY");
        assert_eq!(both.trim(), "run", "the run's own value must win over the process's");
    }

    /// TEST10102: a local path is relative to the FILE, not to the project.
    ///
    /// A manifest resolves its path dependencies from the directory it sits in.
    /// A workspace member two directories down that took the project root's
    /// answer would climb one level too few and point at nothing.
    #[test]
    fn test10102_a_local_path_is_relative_to_the_file_being_written() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();

        make_git_project(root, "thelib", "thelib", "2.5.0", root);
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        let member = app.join("crates").join("inner");
        fs::create_dir_all(&member).unwrap();
        fs::write(
            member.join("Cargo.toml.wstemplate"),
            "path = \"{{ projects.thelib.path_from_here }}\"\n",
        )
        .unwrap();

        render(root, &app, "theapp").expect("the render");
        let written = fs::read_to_string(member.join("Cargo.toml")).unwrap();
        assert!(
            written.contains("path = \"../../../thelib\""),
            "two levels down needs two more steps up: {written}"
        );
    }
}

/// Carry a rendered manifest's version into the lockfile beside it.
///
/// A render bumps the version in `Cargo.toml` and `Cargo.lock` keeps the old
/// one until somebody builds — so the committed pair disagrees, and
/// `cargo build --locked` refuses it:
///
/// ```text
/// error: cannot update the lock file … because --locked was passed
/// ```
///
/// Locally that is invisible, because an ordinary build just fixes the lock.
/// It is not invisible anywhere that reproducibility is the point: a guest
/// building the workspace it was given, a release build, CI. A test guest
/// allocated, booted, installed a toolchain and spent four minutes getting to
/// that error, about a workspace that builds perfectly on the machine that
/// sent it.
///
/// Edited directly rather than by running cargo: an update runs on every
/// command, offline, and shelling out to resolve a dependency graph to change
/// one string would make the common case pay for the rare one. Only the
/// package's OWN version is touched — the dependency graph is cargo's and is
/// left exactly as it was.
///
/// Returns the lock it governs whenever there is one — rewritten now or already
/// in agreement — so a caller staging the manifest stages the lock with it: a
/// lock that already agrees in the working tree may still differ from what is
/// staged, and a commit of the manifest alone carries the stale one.
/// The lock a render keeps in step with `manifest`, when it keeps one: what
/// [`follow_into_lockfile`] rewrites after the manifest is written.
pub fn lockfile_followed_by(manifest: &Path) -> Option<PathBuf> {
    let beside = |name: &str| manifest.parent().map(|dir| dir.join(name));
    match manifest.file_name().and_then(|n| n.to_str()) {
        Some("go.mod") => beside("go.sum"),
        Some("package.json") => beside("package-lock.json"),
        Some("Package.swift") => beside("Package.resolved"),
        Some("Cargo.toml") => governing_lockfile(manifest),
        _ => None,
    }
}

pub fn follow_into_lockfile(manifest: &Path, content: &str) -> Result<Option<PathBuf>> {
    match manifest.file_name().and_then(|n| n.to_str()) {
        Some("go.mod") => return follow_into_go_sum(manifest, content, &download_go_module),
        Some("package.json") => return follow_into_package_lock(manifest, content, &relock_npm),
        Some("Package.swift") => return follow_into_package_resolved(manifest, content, &resolve_swift),
        _ => {}
    }
    if manifest.file_name().and_then(|n| n.to_str()) != Some("Cargo.toml") {
        return Ok(None);
    }
    let versioned = versioned_packages(manifest, content)?;
    if versioned.is_empty() {
        // A virtual workspace root that states no version for its members.
        return Ok(None);
    }
    // The lock that GOVERNS this manifest, which for a workspace member is the
    // one beside its workspace root and not one beside itself — a member has
    // no lock of its own. Looking only alongside meant `wsb/daemon` never
    // updated `wsb/Cargo.lock`, so the daemon's version sat three releases
    // behind in it and `cargo build --locked` refused the whole workspace
    // after every version bump.
    //
    // Found by asking which directory is the workspace root rather than by
    // walking up until a lock appears: an unrelated lock further up would
    // otherwise be rewritten by a member that has nothing to do with it.
    let Some(lock) = governing_lockfile(manifest) else {
        return Ok(None);
    };
    let mut text = std::fs::read_to_string(&lock)
        .with_context(|| format!("reading {}", lock.display()))?;
    let mut changed = false;
    for (name, version) in &versioned {
        // A package not in this lock, or one it already agrees with, is left alone.
        if let Some(updated) = lockfile_with_version(&text, name, version) {
            text = updated;
            changed = true;
        }
    }
    if changed {
        write_output(&lock, &text)?;
    }
    Ok(Some(lock))
}

/// The packages whose version `content` (the rendered `manifest`) states.
///
/// Its own `[package]`, when it names a version — written out, or inherited
/// from the `[workspace.package]` it declares itself. And when it declares
/// `[workspace.package] version`, every member of its `[workspace]` that
/// inherits it (`version.workspace = true`): such a root is the ONE place a
/// multi-crate workspace states its version, and its members' manifests are
/// never rendered. Following only `[package]` left lungo's lock naming every
/// crate at the previous version after each bump, and `cargo build --locked`
/// refused it.
fn versioned_packages(manifest: &Path, content: &str) -> Result<Vec<(String, String)>> {
    let parsed: toml::Value = toml::from_str(content)
        .with_context(|| format!("{} is not a valid manifest", manifest.display()))?;
    let shared = parsed
        .get("workspace")
        .and_then(|w| w.get("package"))
        .and_then(|p| p.get("version"))
        .and_then(|v| v.as_str())
        .map(str::to_string);
    let mut versioned = Vec::new();
    if let Some(package) = parsed.get("package") {
        if let Some(name) = package.get("name").and_then(|n| n.as_str()) {
            match package.get("version") {
                Some(toml::Value::String(version)) if !version.is_empty() => {
                    versioned.push((name.to_string(), version.clone()))
                }
                Some(inherited) if inherits_workspace(inherited) => {
                    if let Some(version) = &shared {
                        versioned.push((name.to_string(), version.clone()));
                    }
                }
                _ => {}
            }
        }
    }
    let Some(version) = shared else {
        return Ok(versioned);
    };
    let root = manifest.parent().expect("a manifest path has a directory");
    let members = parsed
        .get("workspace")
        .and_then(|w| w.get("members"))
        .and_then(|m| m.as_array())
        .cloned()
        .unwrap_or_default();
    for member in members {
        let Some(member) = member.as_str() else {
            bail!("{}: a workspace member is not a path: {member}", manifest.display());
        };
        for directory in member_directories(root, member)
            .with_context(|| format!("{}: member {member}", manifest.display()))?
        {
            let path = directory.join("Cargo.toml");
            let text = std::fs::read_to_string(&path)
                .with_context(|| format!("reading {}, a member of {}", path.display(), manifest.display()))?;
            let member_manifest: toml::Value = toml::from_str(&text)
                .with_context(|| format!("{} is not a valid manifest", path.display()))?;
            let Some(package) = member_manifest.get("package") else {
                continue;
            };
            if package.get("version").is_some_and(inherits_workspace) {
                let name = package.get("name").and_then(|n| n.as_str()).ok_or_else(|| {
                    anyhow!("{} inherits the workspace's version but names no package", path.display())
                })?;
                versioned.push((name.to_string(), version.clone()));
            }
        }
    }
    Ok(versioned)
}

/// Whether a `version` value is `{ workspace = true }` (also written
/// `version.workspace = true`).
fn inherits_workspace(value: &toml::Value) -> bool {
    value.get("workspace").and_then(|w| w.as_bool()) == Some(true)
}

/// The directories a `[workspace] members` entry names: a path, or a path whose
/// last component is `*` (every directory in it holding a manifest). Cargo
/// accepts other globs; one here is refused by name rather than half-followed.
fn member_directories(root: &Path, member: &str) -> Result<Vec<PathBuf>> {
    if let Some(parent) = member.strip_suffix("/*") {
        if !parent.contains(['*', '?', '[']) {
            let mut found = Vec::new();
            for entry in std::fs::read_dir(root.join(parent))
                .with_context(|| format!("reading {}", root.join(parent).display()))?
            {
                let path = entry?.path();
                if path.join("Cargo.toml").is_file() {
                    found.push(path);
                }
            }
            found.sort();
            return Ok(found);
        }
    }
    if member.contains(['*', '?', '[']) {
        bail!("the member pattern '{member}' is not followed: name the directory, or end it in /*");
    }
    Ok(vec![root.join(member)])
}

/// The lockfile that governs `manifest`, if there is one.
///
/// A crate in a workspace has no lock of its own: cargo keeps one beside the
/// workspace root and resolves every member into it. So the search is for the
/// nearest ancestor whose manifest declares `[workspace]`, and the manifest's
/// own directory when it declares one itself or belongs to no workspace.
///
/// Bounded by the presence of a manifest at each step: the walk stops at the
/// first directory with no `Cargo.toml`, so it cannot wander out of the crate
/// tree and into somebody else's.
/// What `go mod download -json` says of one module version: the hashes
/// `go.sum` records, and the requirements of its own `go.mod`.
pub struct GoModule {
    pub sum: String,
    pub go_mod_sum: String,
    pub requires: Vec<(String, String)>,
}

/// Carry a rendered `go.mod`'s requirements into the `go.sum` beside it.
///
/// A render moves a pinned module to the version just released, and `go.sum`
/// kept the hashes of the one before — or none, for a requirement the render
/// had just added — so the committed pair did not build: tagged-urn-go's
/// release failed its suite with
///
/// ```text
/// missing go.sum entry for module providing package github.com/machinefabric/lungo-go
/// ```
///
/// The `Cargo.lock` of the same render followed its manifest; this is the same
/// rule for Go. Each requirement without both of its lines gets them, and each
/// module that brings in gets its requirements' `go.mod` lines, which is what
/// Go reads to build the module graph. A requirement already recorded costs
/// nothing and nothing is asked of the network, which is every render but the
/// one that moved a pin. A module replaced by a local directory — the local
/// render — has no hash to record.
///
/// `go.sum` is returned whenever there is one, so a caller staging the
/// manifest stages it too.
pub fn follow_into_go_sum(
    manifest: &Path,
    content: &str,
    download: &dyn Fn(&str, &str) -> Result<GoModule>,
) -> Result<Option<PathBuf>> {
    let dir = manifest.parent().unwrap_or(Path::new("."));
    let sum_path = dir.join("go.sum");
    // A `go.sum` the repository keeps is kept right; one is never made. A
    // module with no `go.sum` is one whose author left it out — a scaffold a
    // generator copies, which must hold only what an implementation would
    // write — and writing one there put an undeclared file into the stub tree.
    if !sum_path.is_file() || !tracked(&sum_path) {
        return Ok(None);
    }
    let existing = std::fs::read_to_string(&sum_path)
        .with_context(|| format!("reading {}", sum_path.display()))?;
    let mut lines: std::collections::BTreeSet<String> =
        existing.lines().filter(|l| !l.trim().is_empty()).map(str::to_string).collect();
    let has = |lines: &std::collections::BTreeSet<String>, module: &str, version: &str| {
        lines.iter().any(|l| l.starts_with(&format!("{module} {version} ")))
    };
    let has_go_mod = |lines: &std::collections::BTreeSet<String>, module: &str, version: &str| {
        lines.iter().any(|l| l.starts_with(&format!("{module} {version}/go.mod ")))
    };
    let (requires, replaced) = go_mod_requirements(content);
    let mut changed = false;
    let mut graph: Vec<(String, String)> = Vec::new();
    for (module, version) in requires {
        if replaced.contains(&module) {
            continue;
        }
        if has(&lines, &module, &version) && has_go_mod(&lines, &module, &version) {
            continue;
        }
        let found = download(&module, &version)?;
        lines.insert(format!("{module} {version} {}", found.sum));
        lines.insert(format!("{module} {version}/go.mod {}", found.go_mod_sum));
        graph.extend(found.requires);
        changed = true;
    }
    let mut seen = std::collections::BTreeSet::new();
    while let Some((module, version)) = graph.pop() {
        if !seen.insert((module.clone(), version.clone())) || has_go_mod(&lines, &module, &version) {
            continue;
        }
        let found = download(&module, &version)?;
        lines.insert(format!("{module} {version}/go.mod {}", found.go_mod_sum));
        graph.extend(found.requires);
        changed = true;
    }
    if changed {
        let text: String = lines.iter().map(|l| format!("{l}\n")).collect();
        write_output(&sum_path, &text)?;
    }
    Ok(sum_path.is_file().then_some(sum_path))
}

/// The `require`d modules of a `go.mod`, and the modules it replaces with a
/// local directory.
pub fn go_mod_requirements(content: &str) -> (Vec<(String, String)>, Vec<String>) {
    let mut requires = Vec::new();
    let mut replaced = Vec::new();
    let mut block: Option<&str> = None;
    for raw in content.lines() {
        let line = raw.split("//").next().unwrap_or("").trim();
        if line.is_empty() {
            continue;
        }
        if let Some(kind) = block {
            if line == ")" {
                block = None;
                continue;
            }
            match kind {
                "require" => push_requirement(line, &mut requires),
                "replace" => push_local_replace(line, &mut replaced),
                _ => {}
            }
            continue;
        }
        let (word, rest) = line.split_once(char::is_whitespace).unwrap_or((line, ""));
        let rest = rest.trim();
        match (word, rest) {
            ("require" | "replace", "(") => block = Some(word),
            ("require", rest) => push_requirement(rest, &mut requires),
            ("replace", rest) => push_local_replace(rest, &mut replaced),
            _ => {}
        }
    }
    (requires, replaced)
}

/// A module path or version as `go.mod` may write it: bare, or quoted —
/// `"gopkg.in/check.v1"` is one module's own spelling of its requirement.
fn go_mod_word(word: &str) -> String {
    word.trim_matches(|c| c == '"' || c == '`').to_string()
}

fn push_requirement(line: &str, into: &mut Vec<(String, String)>) {
    let mut words = line.split_whitespace();
    if let (Some(module), Some(version)) = (words.next(), words.next()) {
        into.push((go_mod_word(module), go_mod_word(version)));
    }
}

fn push_local_replace(line: &str, into: &mut Vec<String>) {
    if let Some((from, to)) = line.split_once("=>") {
        let target = go_mod_word(to.trim());
        if target.starts_with('.') || target.starts_with('/') {
            if let Some(module) = from.split_whitespace().next() {
                into.push(go_mod_word(module));
            }
        }
    }
}

/// `go mod download -json <module>@<version>`, run outside any module so it
/// reads nothing of the one being rendered.
fn download_go_module(module: &str, version: &str) -> Result<GoModule> {
    let scratch = tempfile::tempdir().context("creating a directory to ask go from")?;
    let output = crate::git_backend::command_without_repo_scope("go")
        .args(["mod", "download", "-json"])
        .arg(format!("{module}@{version}"))
        .env("GOFLAGS", "-mod=mod")
        // This workspace's own modules from their repositories, not through
        // the module proxy and checksum database, which learn of a tag just
        // pushed only some time after it is there.
        .env("GOPRIVATE", "github.com/machinefabric/*")
        .current_dir(scratch.path())
        .output()
        .with_context(|| format!("running go mod download for {module}@{version} (is go installed?)"))?;
    let answer: serde_json::Value = serde_json::from_slice(&output.stdout).with_context(|| {
        format!(
            "go mod download {module}@{version} gave no answer: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )
    })?;
    if let Some(error) = answer.get("Error").and_then(|e| e.as_str()) {
        anyhow::bail!("go.sum cannot record {module} {version}: {error}");
    }
    let field = |name: &str| {
        answer
            .get(name)
            .and_then(|v| v.as_str())
            .map(str::to_string)
            .ok_or_else(|| anyhow::anyhow!("go mod download {module}@{version} reported no {name}"))
    };
    let go_mod = std::fs::read_to_string(field("GoMod")?).unwrap_or_default();
    Ok(GoModule {
        sum: field("Sum")?,
        go_mod_sum: field("GoModSum")?,
        requires: go_mod_requirements(&go_mod).0,
    })
}

/// Whether git tracks `path`: a lock nobody commits is this machine's, and no
/// committed pair can disagree through it.
fn tracked(path: &Path) -> bool {
    let (Some(dir), Some(name)) = (path.parent(), path.file_name()) else {
        return false;
    };
    crate::git_backend::git_command()
        .arg("-C")
        .arg(dir)
        .args(["ls-files", "--error-unmatch", "--"])
        .arg(name)
        .output()
        .is_ok_and(|out| out.status.success())
}

/// Keep a tracked `package-lock.json` agreeing with the rendered `package.json`
/// beside it.
///
/// The render switches a workspace package between its published version
/// (`^1.243.691`) and the working copy (`file:../../capdag/capdag-js`), and the
/// lock kept whichever it had last: floom-uikit's committed pair named one in
/// the manifest and the other in the lock, which `npm ci` refuses. When the
/// dependency specifications the lock records for the package differ from the
/// manifest's, npm rewrites the lock from the manifest — `--package-lock-only`,
/// so nothing is installed and no script runs. When they agree nothing runs.
///
/// The lock also records the package's own version, twice (`version` and
/// `packages[""].version`), and those must be the manifest's too. Left out of
/// the comparison, a version-only render left the lock a commit behind: every
/// checkpoint's hook relocked against the manifest still on disk, then
/// rendered the next version into it, so the lock caught up in the commit after
/// — a change, a commit, a new version — and floom-uikit and
/// machinefabric-dot-com were committed on every checkpoint with nothing in
/// them.
///
/// And the lock's RESOLUTION must be the kind the manifest asks for. npm keeps
/// whatever resolution a lock already holds as long as it satisfies the
/// specification, and a working copy one commit past its release satisfies
/// `^<the release>`: so a manifest rendered back to `^1.426.27` was relocked
/// and still resolved `capdag` as a link to `../capdag/capdag-js`. The
/// committed pair named a release in the manifest and a sibling folder in the
/// lock — for twenty commits of machinefabric-dot-com — and installing from
/// it gave a checkout with none of what a release packs. A link the lock
/// holds for a dependency the manifest takes from the registry is a
/// disagreement, and is taken out of the lock before npm is asked, so that
/// there is nothing for it to keep.
pub fn follow_into_package_lock(
    manifest: &Path,
    content: &str,
    relock: &dyn Fn(&Path) -> Result<()>,
) -> Result<Option<PathBuf>> {
    let dir = manifest.parent().unwrap_or(Path::new("."));
    let lock_path = dir.join("package-lock.json");
    if !lock_path.is_file() || !tracked(&lock_path) {
        return Ok(None);
    }
    let rendered: Value = serde_json::from_str(content)
        .with_context(|| format!("{} is not JSON", manifest.display()))?;
    let lock: Value = serde_json::from_str(&fs::read_to_string(&lock_path)?)
        .with_context(|| format!("{} is not JSON", lock_path.display()))?;
    let recorded = lock.pointer("/packages/").cloned().unwrap_or(Value::Null);
    let specifications_agree = ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"]
        .iter()
        .all(|section| {
            let wanted = rendered.get(section).cloned().unwrap_or_else(|| json!({}));
            let held = recorded.get(section).cloned().unwrap_or_else(|| json!({}));
            wanted == held
        });
    let version = rendered.get("version");
    let version_agrees = version.is_none()
        || (lock.get("version") == version && recorded.get("version") == version);
    let stale_links = links_held_for_registry_dependencies(&rendered, &lock);
    let agrees = specifications_agree && version_agrees && stale_links.is_empty();
    if !agrees {
        if !stale_links.is_empty() {
            let without = without_links(lock, &stale_links);
            let mut text = serde_json::to_string_pretty(&without)
                .with_context(|| format!("writing {}", lock_path.display()))?;
            text.push('\n');
            fs::write(&lock_path, text).with_context(|| format!("writing {}", lock_path.display()))?;
        }
        relock(dir)?;
    }
    Ok(Some(lock_path))
}

/// Whether a dependency specification names a place on this machine rather
/// than a version for the registry to supply.
fn names_a_local_path(specification: &str) -> bool {
    ["file:", "link:", "./", "../", "/", "~/"].iter().any(|prefix| specification.starts_with(prefix))
}

/// The links a lock holds for dependencies its manifest takes from the
/// registry: each as the `packages` key of the link and the folder it points
/// at.
fn links_held_for_registry_dependencies(manifest: &Value, lock: &Value) -> Vec<(String, String)> {
    let Some(packages) = lock.get("packages").and_then(Value::as_object) else {
        return Vec::new();
    };
    let mut held = Vec::new();
    for section in ["dependencies", "devDependencies", "optionalDependencies", "peerDependencies"] {
        let Some(wanted) = manifest.get(section).and_then(Value::as_object) else { continue };
        for (name, specification) in wanted {
            if specification.as_str().is_none_or(names_a_local_path) {
                continue;
            }
            let key = format!("node_modules/{name}");
            let Some(entry) = packages.get(&key) else { continue };
            if entry.get("link").and_then(Value::as_bool) != Some(true) {
                continue;
            }
            let target = entry.get("resolved").and_then(Value::as_str).unwrap_or_default().to_string();
            if !held.iter().any(|(known, _): &(String, String)| *known == key) {
                held.push((key, target));
            }
        }
    }
    held
}

/// The lock with those links, the folders they point at, and everything
/// recorded under those folders taken out — what npm then resolves afresh.
fn without_links(mut lock: Value, links: &[(String, String)]) -> Value {
    if let Some(packages) = lock.get_mut("packages").and_then(Value::as_object_mut) {
        packages.retain(|key, _| {
            !links.iter().any(|(link, target)| {
                key == link || (!target.is_empty() && (key == target || key.starts_with(&format!("{target}/"))))
            })
        });
    }
    lock
}

fn relock_npm(dir: &Path) -> Result<()> {
    let output = crate::git_backend::program_without_repo_scope("npm")
        // `--prefer-online`: the version a lock moves to is often one published
        // a minute ago, and npm's cached metadata did not have it yet —
        // capdag-js 1.374.0 was refused as `notarget` for minutes after npm
        // had accepted it.
        .args(["install", "--package-lock-only", "--prefer-online", "--ignore-scripts", "--no-audit", "--no-fund"])
        .current_dir(dir)
        .output()
        .with_context(|| format!("running npm in {} to bring its lock up to date (is npm installed?)", dir.display()))?;
    if !output.status.success() {
        anyhow::bail!(
            "npm could not bring {}/package-lock.json up to date with its manifest: {}",
            dir.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

/// Keep a tracked `Package.resolved` agreeing with the rendered `Package.swift`
/// beside it.
///
/// The render pins a workspace package exactly — `.package(url: …, exact:
/// "1.78.3254")` — and the resolved file kept the pins of the render before,
/// or none: capdag-objc's committed `Package.resolved` named neither
/// tagged-urn-objc nor lungo-swift, which its `Package.swift` pinned. When an
/// exact pin is missing from the resolved file or names another version,
/// SwiftPM resolves the package again. A package taken from a local path — the
/// local render — is not pinned by version, and is not looked at.
pub fn follow_into_package_resolved(
    manifest: &Path,
    content: &str,
    resolve: &dyn Fn(&Path) -> Result<()>,
) -> Result<Option<PathBuf>> {
    let dir = manifest.parent().unwrap_or(Path::new("."));
    let resolved_path = dir.join("Package.resolved");
    if !resolved_path.is_file() || !tracked(&resolved_path) {
        return Ok(None);
    }
    let resolved: Value = serde_json::from_str(&fs::read_to_string(&resolved_path)?)
        .with_context(|| format!("{} is not JSON", resolved_path.display()))?;
    let pins: Vec<(String, String)> = resolved
        .get("pins")
        .and_then(Value::as_array)
        .map(|pins| {
            pins.iter()
                .filter_map(|pin| {
                    Some((
                        swift_location(pin.get("location")?.as_str()?),
                        pin.pointer("/state/version")?.as_str()?.to_string(),
                    ))
                })
                .collect()
        })
        .unwrap_or_default();
    let agrees = exact_swift_pins(content)
        .iter()
        .all(|(url, version)| pins.iter().any(|(at, pinned)| *at == swift_location(url) && pinned == version));
    if !agrees {
        resolve(dir)?;
    }
    Ok(Some(resolved_path))
}

/// The `.package(url: "…", exact: "…")` pins of a `Package.swift`.
pub fn exact_swift_pins(content: &str) -> Vec<(String, String)> {
    let mut pins = Vec::new();
    for line in content.lines() {
        let code = without_line_comment(line);
        let (Some(url_at), Some(exact_at)) = (code.find("url:"), code.find("exact:")) else {
            continue;
        };
        let quoted = |from: usize| -> Option<String> {
            let rest = &code[from..];
            let start = rest.find('"')? + 1;
            let end = rest[start..].find('"')?;
            Some(rest[start..start + end].to_string())
        };
        if let (Some(url), Some(version)) = (quoted(url_at), quoted(exact_at)) {
            pins.push((url, version));
        }
    }
    pins
}

/// A line with its `//` comment removed — a `//` outside a string literal, so
/// the `https://` of a package URL is not taken for one.
fn without_line_comment(line: &str) -> &str {
    let mut quoted = false;
    let bytes = line.as_bytes();
    for (at, byte) in bytes.iter().enumerate() {
        match byte {
            b'"' => quoted = !quoted,
            b'/' if !quoted && bytes.get(at + 1) == Some(&b'/') => return &line[..at],
            _ => {}
        }
    }
    line
}

/// A package location as SwiftPM compares it: without a trailing `.git` or
/// slash, case-insensitively.
fn swift_location(url: &str) -> String {
    url.trim_end_matches('/').trim_end_matches(".git").to_ascii_lowercase()
}

fn resolve_swift(dir: &Path) -> Result<()> {
    let output = crate::git_backend::command_without_repo_scope("swift")
        .args(["package", "resolve"])
        .current_dir(dir)
        .output()
        .with_context(|| format!("running swift package resolve in {} (is Swift installed?)", dir.display()))?;
    if !output.status.success() {
        anyhow::bail!(
            "swift could not resolve {} against its manifest: {}",
            dir.display(),
            String::from_utf8_lossy(&output.stderr).trim()
        );
    }
    Ok(())
}

fn governing_lockfile(manifest: &Path) -> Option<PathBuf> {
    let start = manifest.parent()?;
    let mut here = Some(start);
    while let Some(directory) = here {
        let candidate = directory.join("Cargo.toml");
        let Ok(text) = std::fs::read_to_string(&candidate) else {
            break;
        };
        if declares_workspace(&text) {
            let lock = directory.join("Cargo.lock");
            return lock.is_file().then_some(lock);
        }
        here = directory.parent();
    }
    // No workspace above it: a standalone crate keeps its own lock.
    let lock = start.join("Cargo.lock");
    lock.is_file().then_some(lock)
}

/// Whether a manifest declares a `[workspace]` table.
fn declares_workspace(content: &str) -> bool {
    content.lines().any(|line| {
        let line = line.trim();
        line == "[workspace]" || line.starts_with("[workspace.")
    })
}

/// The lockfile with one package's version replaced, or `None` when there is
/// nothing to change.
fn lockfile_with_version(lock: &str, name: &str, version: &str) -> Option<String> {
    let wanted = format!("name = \"{name}\"");
    let mut lines: Vec<String> = lock.lines().map(str::to_string).collect();
    let mut changed = false;
    for index in 0..lines.len() {
        if lines[index].trim() != wanted {
            continue;
        }
        // The version is the next `version = ` line inside the same entry. An
        // entry ends at the blank line before the next `[[package]]`.
        for candidate in lines.iter_mut().skip(index + 1) {
            let trimmed = candidate.trim();
            if trimmed.is_empty() || trimmed.starts_with("[[") {
                break;
            }
            if let Some(rest) = trimmed.strip_prefix("version = ") {
                if rest.trim().trim_matches('"') == version {
                    break;
                }
                *candidate = format!("version = \"{version}\"");
                changed = true;
                break;
            }
        }
    }
    if !changed {
        return None;
    }
    let mut text = lines.join("\n");
    if lock.ends_with('\n') {
        text.push('\n');
    }
    Some(text)
}

#[cfg(test)]
mod declaration_tests {
    //! What a template reads out of the workspace's own declaration.
    //!
    //! The values that are neither a fact about a project nor an environment
    //! variable: things the workspace states about itself. The case that
    //! forced it is the version of a library a GUEST can install, which is not
    //! this tree's version — that one is unpublished by construction, and
    //! stamping it sent every guest looking on PyPI for something that exists
    //! only here.

    use super::tests::{make_project, make_vi};
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// A workspace whose stamp configuration names `workspace.json` as its
    /// declaration and `.wsb/disposable/build` as its build root.
    fn workspace_with(declaration: &str, template: &str) -> (TempDir, Result<Vec<RenderedTemplate>>) {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        fs::create_dir_all(root.join(".wsb")).unwrap();
        fs::write(
            root.join(super::super::stamp_config::FILE),
            r#"{"declared": "workspace.json", "build_root": ".wsb/disposable/build"}"#,
        )
        .unwrap();
        fs::write(root.join("workspace.json"), declaration).unwrap();
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(app.join("requirements.txt.wstemplate"), template).unwrap();
        let rendered = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("theapp".to_string()),
            "theapp".to_string(),
            app,
            root.to_path_buf(),
        )
        .render_relevant();
        (workspace, rendered)
    }

    /// TEST11354: a template renders what the workspace declares.
    #[test]
    fn test11354_a_declared_value_is_rendered() {
        let (_workspace, rendered) = workspace_with(
            r#"{"mg_test": {"bootstrap": {"published_capdag": "1.308.0"}}}"#,
            "capdag=={{ declared.mg_test.bootstrap.published_capdag }}\n",
        );
        let rendered = rendered.expect("the declaration should render");
        assert_eq!(rendered.len(), 1);
        assert_eq!(
            fs::read_to_string(&rendered[0].output_path).unwrap(),
            "capdag==1.308.0\n"
        );
    }

    /// TEST11355: a path the workspace does not declare names itself, and its
    /// line, and what is actually there.
    ///
    /// Without the check ahead of rendering this arrived as Tera's "variable
    /// not found", naming only the last segment — so a renamed key in
    /// `workspace.json` reported `published_capdag` and left somebody to work
    /// out which of several templates had asked for it and under what path.
    #[test]
    fn test11355_an_undeclared_path_is_named_with_its_line() {
        let (_workspace, rendered) = workspace_with(
            r#"{"mg_test": {"bootstrap": {"published_capdag": "1.308.0"}}}"#,
            "# a comment\ncapdag=={{ declared.mg_test.bootstrap.published_capdog }}\n",
        );
        let error = rendered.expect_err("an undeclared path must be refused");
        let said = format!("{error:#}");
        assert!(said.contains("line 2"), "{said}");
        assert!(
            said.contains("declared.mg_test.bootstrap.published_capdog"),
            "{said}"
        );
        // And what IS there, so the fix does not need a second look at the file.
        assert!(said.contains("published_capdag"), "{said}");
    }

    /// TEST11356: a path that runs off the end of a value says so.
    #[test]
    fn test11356_a_path_through_a_leaf_is_refused() {
        let (_workspace, rendered) = workspace_with(
            r#"{"mg_test": {"bootstrap": {"published_capdag": "1.308.0"}}}"#,
            "{{ declared.mg_test.bootstrap.published_capdag.major }}\n",
        );
        let error = rendered.expect_err("a path through a leaf must be refused");
        let said = format!("{error:#}");
        assert!(said.contains("not something with named parts"), "{said}");
    }

    /// TEST12300: `build.root_from_here` is the build root, relative to the
    /// rendered file — what a local render names something the workspace
    /// builds by.
    #[test]
    fn test12300_the_build_root_is_named_from_the_rendered_file() {
        let (workspace, rendered) = workspace_with(
            "{}",
            "path = \"{{ build.root_from_here }}/lungo/distribution\"\n",
        );
        let rendered = rendered.expect("the build root should render");
        let text = fs::read_to_string(&rendered[0].output_path).unwrap();
        // theapp is a directory of the workspace, and the build root is not
        // created yet: the path is still the one it will have.
        assert_eq!(text, "path = \"../.wsb/disposable/build/lungo/distribution\"\n");
        assert!(!workspace.path().join(".wsb/disposable").exists(), "nothing was built");
        drop(workspace);
    }

    /// TEST12301: a `build` field that does not exist names the ones that do.
    #[test]
    fn test12301_an_unknown_build_field_is_refused() {
        let (_workspace, rendered) = workspace_with("{}", "{{ build.root }}\n");
        let said = format!("{:#}", rendered.expect_err("an unknown build field must be refused"));
        assert!(said.contains("root_from_here"), "{said}");
    }

    /// TEST11357: a template that asks for nothing does not read the file.
    ///
    /// Most templates never mention the declaration, and parsing the registry
    /// for every one of them would be a cost paid on every render for a
    /// feature used once. Proven by rendering with no registry present at all:
    /// a template that does not ask still renders.
    #[test]
    fn test11357_a_template_that_asks_for_nothing_needs_no_declaration() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        // Deliberately no workspace.json.
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(app.join("version.txt.wstemplate"), "{{ project.version }}\n").unwrap();
        let rendered = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("theapp".to_string()),
            "theapp".to_string(),
            app,
            root.to_path_buf(),
        )
        .render_relevant()
        .expect("a template with no declaration reference should render");
        assert_eq!(fs::read_to_string(&rendered[0].output_path).unwrap(), "1.0.0\n");
    }

    /// TEST11358: a missing declaration is reported as a missing file.
    ///
    /// `.wsb/stamp.json` names the file; the file is not there.
    #[test]
    fn test11358_a_template_that_asks_needs_the_declaration_to_exist() {
        let workspace = TempDir::new().unwrap();
        let root = workspace.path();
        fs::create_dir_all(root.join(".wsb")).unwrap();
        fs::write(
            root.join(super::super::stamp_config::FILE),
            r#"{"declared": "declared.json"}"#,
        )
        .unwrap();
        let app = make_project(root, "theapp", "theapp", "1.0.0", root);
        fs::write(
            app.join("requirements.txt.wstemplate"),
            "{{ declared.mg_test.bootstrap.published_capdag }}\n",
        )
        .unwrap();
        let error = WstemplateEngine::new(
            make_vi("1.0.0"),
            Some("theapp".to_string()),
            "theapp".to_string(),
            app,
            root.to_path_buf(),
        )
        .render_relevant()
        .expect_err("a template asking for a declaration that is not there must fail");
        let said = format!("{error:#}");
        assert!(said.contains("cannot read the workspace declaration"), "{said}");
    }
}

#[cfg(test)]
mod take_back_tests {
    //! Putting a manifest back keeps its lockfile in step.
    //!
    //! The rule is about CHANGING a manifest, not about rendering one. `wsb
    //! local off` restores the committed manifest with a plain write, so the
    //! lock was left naming whatever version the render had put there — ahead
    //! of the manifest — and `cargo build --locked` refused the whole
    //! workspace: in the tree, and in every target a run staged it into.

    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// TEST11392: a manifest put back carries its version into the lockfile.
    #[test]
    fn test11392_a_restored_manifest_updates_the_lockfile() {
        let place = TempDir::new().unwrap();
        let root = place.path();
        let manifest = root.join("Cargo.toml");
        let lock = root.join("Cargo.lock");
        // The lock as a render left it: ahead of what is about to be restored.
        fs::write(
            &lock,
            "version = 4\n\n[[package]]\nname = \"thing\"\nversion = \"1.332.5937\"\n",
        )
        .unwrap();

        let restored = "[package]\nname = \"thing\"\nversion = \"1.331.5923\"\n";
        fs::write(&manifest, restored).unwrap();
        follow_into_lockfile(&manifest, restored).expect("the lockfile follows a take-back");

        let after = fs::read_to_string(&lock).unwrap();
        assert!(after.contains("1.331.5923"), "{after}");
        assert!(
            !after.contains("1.332.5937"),
            "the lock must not be left ahead of the manifest:\n{after}"
        );
    }
}

#[cfg(all(test, unix))]
mod spelled_differently_tests {
    use super::*;

    /// TEST12105: a template belongs to its project however the two paths are
    /// spelled.
    ///
    /// The owning project was decided by a plain prefix match between a
    /// template found by walking the scan root and a root read back from
    /// `.wsb/state.json` — which wsb rewrites from its resolved working
    /// directory. On macOS `/var` links to `/private/var`, so the second
    /// `wsb update --recursive` in a fresh temp directory refused with "the
    /// template is not under any project registered", and seven recursive
    /// update tests failed on it. A symlink makes the same two spellings on
    /// any Unix, which is what this uses.
    #[test]
    fn test12105_a_template_is_owned_through_a_linked_path() {
        let tmp = tempfile::TempDir::new().unwrap();
        let real = tmp.path().join("real");
        let fleet = real.join("fleet");
        std::fs::create_dir_all(fleet.join("mid")).unwrap();
        let link = tmp.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        // Registered in the resolved spelling, found through the linked one.
        let roots: HashMap<String, PathBuf> = [
            ("fleet".to_string(), crate::platform::canonicalize(&fleet).unwrap()),
            ("mid".to_string(), crate::platform::canonicalize(&fleet.join("mid")).unwrap()),
        ]
        .into_iter()
        .collect();
        let template = link.join("fleet/fleet.toml.wstemplate");
        std::fs::write(&template, "x").unwrap();
        let nested = link.join("fleet/mid/mid.toml.wstemplate");
        std::fs::write(&nested, "x").unwrap();

        assert_eq!(
            find_most_specific_root(&template, &roots),
            Some(crate::platform::canonicalize(&fleet).unwrap()),
            "a template found through a link was not owned by the project it is in"
        );
        // And the most specific one still wins, not merely any that contains it.
        assert_eq!(
            find_most_specific_root(&nested, &roots),
            Some(crate::platform::canonicalize(&fleet.join("mid")).unwrap())
        );
    }
}