dodot-lib 5.9.0

Core library for dodot dotfiles manager
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
//! Shell integration — generates `dodot-init.sh`.
//!
//! The script is generated flat and declarative from the actual
//! datastore state, rather than re-discovering the datastore layout at
//! runtime in shell. This means:
//!
//! - Zero logic duplication between Rust and shell
//! - The script is just `source` and `PATH=` lines — trivially fast
//! - Changes to the datastore layout only need to happen in Rust
//!
//! The generated script is written to `data_dir/shell/dodot-init.sh`.
//! `dodot install --write` wires the line below into the user's rc
//! file ([`rc`]), [`probe`] measures whether a new shell actually
//! runs it, and [`trace`] reports what `dodot` resolves to at that
//! rc line (`dodot probe shell-init --trace-hook`). Users can also add it by hand:
//!
//! ```sh
//! [ -f "$HOME/.local/share/dodot/shell/dodot-init.sh" ] && . "$HOME/.local/share/dodot/shell/dodot-init.sh"
//! ```
//!
//! # Targeted verification
//!
//! Current init scripts open with the one-use challenge branch from
//! `docs/proposals/shipped/targeted-shell-init-verification.lex`: when dodot starts a fresh
//! interactive shell only to verify that the hook is reached, the
//! script reports its nonce, verifier PID, shell PID, generation, and
//! dodot version, then exits before heartbeat writes, profiling, PATH
//! setup, Homebrew, or pack contributions. Ordinary shells do not
//! carry the challenge variables and continue into activation evidence
//! unchanged.
//!
//! # Hook tracing
//!
//! Current init scripts also recognize the internal diagnostic mode
//! used by `dodot probe shell-init --trace-hook`. In that mode they
//! suppress activation evidence and profiling writes, then continue
//! through Homebrew, PATH setup, and pack contributions so the trace
//! can diagnose the same startup work without manufacturing heartbeat
//! or profile evidence.
//!
//! # Activation evidence (shell-hookup-ergonomics.lex §2.1)
//!
//! Every generated script — profiled or not, empty datastore or not —
//! opens with three lines that prove it ran and say who wrote it: an
//! `export DODOT_INIT_GEN=` carrying the *generation* the script was
//! written at, an `export DODOT_INIT_VERSION=` carrying the dodot that
//! wrote it, and a single truncating redirect of both fields into the
//! heartbeat marker. `dodot up`, `dodot down` and `dodot status` read
//! them back through [`activation`] to tell "no shell has ever loaded
//! dodot" from "this terminal predates your last `up`" from "your
//! shells load a different dodot" from "healthy".
//!
//! The generation is an argument, not something the generator invents:
//! callers that write the script stamp [`activation::current_generation`],
//! and tests pin a value so the emitted script is deterministic. The
//! version is not — it is this binary's, by definition.
//!
//! The block is on a strict budget — exports and one redirect, no
//! command execution — because it runs on every shell start forever.
//! That is also why the heartbeat is a whole-file rewrite of static
//! content: concurrent shell startups race, and last-writer-wins on a
//! truncating redirect is a correct answer to that race, where an
//! append or a read-modify-write would not be. It is also why "when did
//! a shell last load dodot" is read from that file's *mtime* rather
//! than from anything written inside it: the redirect already updates
//! mtime on every activation, so the answer costs no extra write.
//!
//! # Homebrew bootstrap (shell-hookup-ergonomics.lex §4)
//!
//! Right after the evidence, and before anything a pack contributed,
//! the script can carry Homebrew's environment as captured from
//! `brew shellenv` by `dodot up`/`down` and cached in the datastore.
//! [`homebrew`] owns the capture, the cache, the `$ZSH_VERSION` guard,
//! and the reasons for all three; the generator only decides *where*
//! the block goes, which is: first, so dodot's own PATH additions are
//! always the last word.
//!
//! # Profiling wrapper (Phase 2 of profiling.lex)
//!
//! When the caller passes `profiling_enabled = true`, the generator
//! wraps every `source` and PATH line with an inline `EPOCHREALTIME`
//! capture and writes one `profile-*.tsv` per shell start under
//! `<data_dir>/probes/shell-init/`. The wrapper is gated on a runtime
//! check (`bash 5+` / `zsh` with `EPOCHREALTIME` available); shells
//! without the variable fall through to the unchanged source/PATH
//! path with a single `[ "$_dodot_prof" = "1" ]` test of overhead.
//! When `profiling_enabled = false`, the profile writer is omitted;
//! the verification and diagnostic branches still remain at the top
//! because they serve separate command paths.
//!
//! Sources are *not* wrapped in a shell function: in zsh, `source`
//! inside a function changes scoping for plain variable assignments
//! in the sourced file, which is a behavioural surprise nobody asked
//! for. We pay the price of a slightly longer script in exchange for
//! semantic equivalence with the un-instrumented form.
//!
//! # PATH attribution (path-precedence.lex §5)
//!
//! The composed `export PATH=…` line ([`compose_path_tier`]) only knows
//! about directories the `path` handler declared — it can't see a raw
//! `export PATH=` a pack's own shell script issues, since that only
//! happens once some shell actually sources the script. The generator
//! closes that gap live: each pack's group of `source` lines is
//! bracketed by a `$PATH` before/after capture, unconditionally,
//! independent of the profiling wrapper above. When a pack's scripts
//! changed `$PATH`, the run records `<pack>\t<raw dirs>` to
//! [`Pather::path_attribution_path`] — truncated to header-only when
//! nothing changed, so a pack that stops raw-mutating `$PATH` drops out
//! of the report on its very next shell start. [`path_attribution`]
//! owns the format on both ends: the constant the generator's emitters
//! write and this doc describes, and the parser/reader `dodot probe
//! shell-init`'s PATH-provenance block uses to merge it back with the
//! declared tier.

use std::collections::HashSet;
use std::fmt::Write;
use std::path::{Path, PathBuf};

use crate::fs::Fs;
use crate::paths::Pather;
use crate::Result;

pub mod activation;
pub mod homebrew;
pub mod path_attribution;
pub mod probe;
pub mod rc;
pub mod trace;
pub mod validate;
pub use activation::{ActivationNotice, ActivationState, INIT_GEN_ENV, INIT_VERSION_ENV};
pub use homebrew::{
    read_cached_blocks, BrewBlocks, BrewBootstrapMode, BrewCapture, BrewHost, CaptureFailure,
    PersistedCapture,
};
pub use path_attribution::{
    parse_path_attribution, path_provenance, read_path_attribution, PathOrigin,
    PathProvenanceEntry, RawPathEntry, PATH_ATTRIBUTION_MARKER,
};
pub use probe::ProbePolicy;
pub use rc::ShellEnv;
pub use validate::{
    error_sidecar_path, validate_shell_sources, NoopSyntaxChecker, ShellValidationFailure,
    ShellValidationReport, SyntaxCheckResult, SyntaxChecker, SystemSyntaxChecker, ERRORS_SUBDIR,
};

/// The line an init script with no pack contributions carries, and the
/// marker [`script_has_contributions`] reads back.
///
/// One string, written by the generator and parsed by the footer, so
/// "the script is empty" can never mean two different things in the
/// two halves of the round trip.
pub const EMPTY_SCRIPT_MARKER: &str = "# No shell scripts or PATH additions to load.";

/// Whether generated init-script text sources or PATHs anything.
///
/// `false` for the three ways a script ends up with nothing to do —
/// after `dodot down`, in a repository where every pack is ignored, and
/// after a first `up` that deployed nothing — which is the one rule the
/// footer needs to say "wired, but nothing is deployed" instead of
/// claiming a healthy deployment (`shell-hookup-ergonomics.lex` §2.3).
pub fn script_has_contributions(script: &str) -> bool {
    !script
        .lines()
        .any(|line| line.trim() == EMPTY_SCRIPT_MARKER)
}

/// Whether a generated script advertises the process-bound targeted
/// verification protocol.
pub fn script_supports_targeted_probe(script: &str) -> bool {
    script
        .lines()
        .any(|line| line.trim() == "# dodot shell-init-probe v1")
}

/// Whether a generated script can suppress activation evidence and
/// shell-init profile writes while a hook trace runs through the rest
/// of the init body.
pub fn script_supports_diagnostic_trace(script: &str) -> bool {
    script
        .lines()
        .any(|line| line.trim() == "# dodot shell-init-trace v1")
}

/// Generate the guarded challenge response fragment used by current
/// init scripts.
///
/// [`generate_init_script`] embeds this fragment at the beginning of
/// the full script. When a verifier starts a shell with a valid
/// targeted challenge, the fragment prints the nonce-bound response and
/// exits before activation evidence, Homebrew setup, profiling, or pack
/// contributions run; ordinary shells continue into the generated init
/// body. This helper returns the fragment by itself for callers that
/// need to inspect or test the probe protocol.
pub fn generate_init_probe_response(generation: u64) -> String {
    let mut script = String::new();
    emit_init_probe_response(&mut script, generation);
    script
}

/// Generate the targeted response fragment for an eval-form hook.
///
/// This fragment is intentionally cheap to create: `dodot init-sh` can
/// return it before resolving the dotfiles root, loading configuration,
/// capturing Homebrew, or scanning packs. The shell still owns the parent
/// identity check. If inherited or stale challenge variables fail that
/// check, the fragment clears them and asks the exact same dodot executable
/// for the ordinary full init body.
pub fn generate_eval_init_probe_response(generation: u64, dodot_executable: &Path) -> String {
    let mut script = String::new();
    emit_init_probe_response_body(&mut script, generation);
    writeln!(script, "else").unwrap();
    writeln!(script, "    unset {}", probe::TARGET_PROBE_ENV).unwrap();
    writeln!(script, "    unset {}", probe::TARGET_PROBE_PARENT_ENV).unwrap();
    writeln!(
        script,
        "    eval \"$({} init-sh)\"",
        sh_quote(&dodot_executable.display().to_string())
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
    script
}

/// Append the "nothing to do" notice for an empty init script.
fn append_empty_notice(script: &mut String) {
    writeln!(script, "{EMPTY_SCRIPT_MARKER}").unwrap();
    writeln!(
        script,
        "# Run `dodot up` to deploy packs, or `dodot status` to see available packs."
    )
    .unwrap();
}

/// One directory in the composed `$PATH`'s "packs" tier, attributed to
/// the pack that staged it.
///
/// The attribution is not cosmetic: it drives the `# [pack]` comments
/// emitted above the composed line, and — when profiling is on — the
/// `(pack, target)` columns of each profile row `probe::shell_init`
/// reads back, even though every contribution now lands on `$PATH` via
/// one shared `export`. `pub(crate)` (rather than module-private) so
/// [`path_attribution::path_provenance`] can build the merged
/// declared+raw provenance view `dodot probe shell-init` surfaces
/// (`docs/proposals/path-precedence.lex` §5.4) without re-deriving the
/// tier/dedup rule — [`compose_path_tier`] stays the one owner (§4.3).
pub(crate) struct PathContribution {
    pub(crate) pack: String,
    pub(crate) dir: PathBuf,
}

/// Group consecutive `(pack, target)` entries by pack, preserving each
/// pack's own internal (scan) order.
///
/// Both the packs-tier composer ([`compose_path_tier`]) and
/// [`generate_init_script`]'s per-pack `$PATH` diff wrapper (which
/// brackets each pack's shell-source lines with
/// [`emit_pack_path_diff_open`] / [`emit_pack_path_diff_close`]) need
/// this: the datastore scan ([`scan_pack_contributions`]) already
/// produces entries grouped this way — one pack fully drained before
/// the next begins — so a linear pass suffices; no sort needed.
fn group_consecutive_by_pack(entries: &[(String, PathBuf)]) -> Vec<(String, Vec<PathBuf>)> {
    let mut groups: Vec<(String, Vec<PathBuf>)> = Vec::new();
    for (pack, dir) in entries {
        match groups.last_mut() {
            Some((last_pack, dirs)) if last_pack == pack => dirs.push(dir.clone()),
            _ => groups.push((pack.clone(), vec![dir.clone()])),
        }
    }
    groups
}

/// Compose the packs tier of the final `$PATH`
/// (`docs/proposals/path-precedence.lex` §3.1, §3.2, §4.2) — the one
/// place the cross-pack `$PATH` rule lives (§4.3).
///
/// `path_additions` is every pack's staged `path`-handler directory, in
/// pack-scan order: ascending on-disk directory name ([`Fs::read_dir`]
/// sorts), with each pack's own directories in their own scan order.
/// The tiers contract ranks packs purely by that lex order with the
/// *last* pack winning the front of the string — prepending above
/// system `$PATH` is what forces that direction (§2.3), not a style
/// choice — so this reverses the list one pack-group at a time: each
/// pack's own directories keep their internal order, only the
/// pack-to-pack order flips.
///
/// `known_lower_tier_dirs` is every directory a lower, fixed tier
/// already places on `$PATH` before this composed line runs — today
/// that is just Homebrew's `<prefix>/bin` and `<prefix>/sbin`
/// ([`homebrew_known_dirs`]; §3.1 "homebrew / toolchains"). That tier's
/// block is emitted verbatim and untouched (RCS01, out of scope here),
/// so its entry can't itself be deduped away — a pack directory that
/// collides with one is dropped from the packs tier instead, and the
/// lower tier's already-emitted entry is what survives. The surviving
/// copy therefore sits at the lower tier's fixed position, not the
/// pack's — read literally, the opposite of "highest-precedence tier
/// wins the slot" — but the outcome is still exactly one entry rather
/// than two, which is what §3.2 requires and names by example: a stale
/// `001-homebrew` pack collapses into Homebrew's own single entry.
///
/// Deduplication within the packs tier itself is the ordinary case:
/// first occurrence in pack-precedence order — the highest-precedence
/// pack (last on disk) wins the slot, and every lower-precedence repeat
/// of the same directory is dropped.
pub(crate) fn compose_path_tier(
    path_additions: &[(String, PathBuf)],
    known_lower_tier_dirs: &[PathBuf],
) -> Vec<PathContribution> {
    let groups = group_consecutive_by_pack(path_additions);

    let mut seen: HashSet<PathBuf> = known_lower_tier_dirs.iter().cloned().collect();
    let mut out = Vec::new();
    for (pack, dirs) in groups.into_iter().rev() {
        for dir in dirs {
            if seen.insert(dir.clone()) {
                out.push(PathContribution {
                    pack: pack.clone(),
                    dir,
                });
            }
        }
    }
    out
}

/// The directories Homebrew's own captured bootstrap block already
/// places on `$PATH` before the composed packs-tier line runs — used
/// only to dedup the packs tier against that lower tier
/// ([`compose_path_tier`]); the block itself is untouched
/// (`docs/proposals/path-precedence.lex` note at the top: Homebrew's
/// bootstrap is settled by RCS01 and not reopened here).
///
/// `brew shellenv` puts `<prefix>/bin` and `<prefix>/sbin` on `$PATH`;
/// `None` (not macOS, no brew, or `[shell] homebrew = "off"`) yields no
/// known directories to dedup against.
pub(crate) fn homebrew_known_dirs(homebrew: Option<&BrewBlocks>) -> Vec<PathBuf> {
    match homebrew {
        Some(blocks) => vec![blocks.prefix.join("bin"), blocks.prefix.join("sbin")],
        None => Vec::new(),
    }
}

/// The datastore scan both [`generate_init_script`] and
/// [`path_attribution::path_provenance`] need: every pack's `path`- and
/// `shell`-handler contributions, plus the on-disk pack order both
/// derive their own orderings from.
pub(crate) struct PackScan {
    /// Pack display names in on-disk (ascending) scan order, one entry
    /// per pack regardless of which handlers it uses — the canonical
    /// ordering [`compose_path_tier`] and the provenance view both
    /// reverse to get "last pack wins the front" (§2.3).
    pub(crate) pack_order: Vec<String>,
    /// (pack, target) — `path`-handler directories, pack-scan order.
    pub(crate) path_additions: Vec<(String, PathBuf)>,
    /// (pack, target) — `shell`-handler scripts, pack-scan order.
    pub(crate) shell_sources: Vec<(String, PathBuf)>,
}

/// Scan `<data_dir>/packs` for every pack's `shell`- and `path`-handler
/// contributions. `None` when the packs directory doesn't exist yet
/// (fresh install, or after `dodot down`) — the caller's empty-notice
/// path.
pub(crate) fn scan_pack_contributions(fs: &dyn Fs, paths: &dyn Pather) -> Result<Option<PackScan>> {
    let packs_dir = paths.data_dir().join("packs");
    if !fs.exists(&packs_dir) {
        return Ok(None);
    }

    let pack_entries = fs.read_dir(&packs_dir)?;

    let mut pack_order: Vec<String> = Vec::new();
    let mut shell_sources: Vec<(String, PathBuf)> = Vec::new();
    let mut path_additions: Vec<(String, PathBuf)> = Vec::new();

    for pack_entry in &pack_entries {
        if !pack_entry.is_dir {
            continue;
        }
        // The datastore subtree is keyed by the on-disk directory
        // name (e.g. `010-nvim`), but the comment we emit in the
        // generated init script uses the pack's display name
        // (`nvim`) — that's what the user sees in `dodot status` and
        // expects to recognise here.
        let pack_dir = &pack_entry.name;
        let pack_display = crate::packs::display_name_for(pack_dir).to_string();
        pack_order.push(pack_display.clone());

        // Shell handler: source scripts
        let shell_dir = paths.handler_data_dir(pack_dir, "shell");
        if fs.is_dir(&shell_dir) {
            if let Ok(entries) = fs.read_dir(&shell_dir) {
                for entry in entries {
                    if !entry.is_symlink {
                        continue;
                    }
                    let target = fs.readlink(&entry.path)?;
                    shell_sources.push((pack_display.clone(), target));
                }
            }
        }

        // Path handler: add to PATH
        let path_dir = paths.handler_data_dir(pack_dir, "path");
        if fs.is_dir(&path_dir) {
            if let Ok(entries) = fs.read_dir(&path_dir) {
                for entry in entries {
                    if !entry.is_symlink {
                        continue;
                    }
                    let target = fs.readlink(&entry.path)?;
                    path_additions.push((pack_display.clone(), target));
                }
            }
        }
    }

    Ok(Some(PackScan {
        pack_order,
        path_additions,
        shell_sources,
    }))
}

/// Generate the shell init script content from the current datastore state.
///
/// Scans the datastore for:
/// - `packs/*/shell/*` — symlinks to shell scripts → one `source` line
///   each, each pack's group bracketed by a `$PATH` before/after capture
///   ([`emit_pack_path_diff_open`] / [`emit_pack_path_diff_close`]) so a
///   raw `export PATH=` the script issues itself is attributed rather
///   than silently lost (`docs/proposals/path-precedence.lex` §5) — the
///   captured rows are written to
///   [`Pather::path_attribution_path`] once sourcing finishes
///   ([`emit_path_attribution_write`]; cleared to header-only via
///   [`emit_path_attribution_clear`] on every path where no pack shell
///   script could have raw-mutated `$PATH`, so stale attribution never
///   lingers)
/// - `packs/*/path/*` — symlinks to directories, composed by
///   [`compose_path_tier`] into a single deduplicated, tiered
///   `export PATH=…` line (`docs/proposals/path-precedence.lex` §3–§4)
///   instead of one `export PATH=` per directory
///
/// `generation` is stamped into the activation-evidence block (see the
/// module docs), which is emitted unconditionally — before the
/// early-return for an empty datastore, because "a shell sourced this"
/// is worth knowing even when the script has nothing else to do.
///
/// `homebrew` is the bootstrap block captured from `brew shellenv` —
/// by [`homebrew::capture_and_persist`] in `up`/`down`, or served from
/// the datastore cache by [`homebrew::cached_or_capture`] in passive
/// generation paths — or `None` when there is nothing to emit (not
/// macOS, no brew, or `[shell] homebrew = "off"`). Like
/// the evidence it lands ahead of the empty-datastore early return: it
/// is a function of config and the host, not of what any pack deployed,
/// and a user whose rc file is empty still needs brew's environment.
/// Emitting it *first* is what lets dodot's own PATH additions be the
/// last word without any pack-ordering choreography.
///
/// When `profiling_enabled` is true and there is at least one entry to
/// emit, the script also carries the per-line timing wrapper described
/// in the module docs. Every generated completion path clears the
/// temporary `_dodot_trace` shell variable before returning control to
/// the user's interactive shell.
pub fn generate_init_script(
    fs: &dyn Fs,
    paths: &dyn Pather,
    profiling_enabled: bool,
    generation: u64,
    homebrew: Option<&BrewBlocks>,
) -> Result<String> {
    let mut script = String::new();

    writeln!(script, "#!/bin/sh").unwrap();
    writeln!(script, "# Generated by dodot — do not edit manually.").unwrap();
    writeln!(script, "# Regenerated on every `dodot up` / `dodot down`.").unwrap();
    writeln!(script).unwrap();

    emit_init_probe_response(&mut script, generation);
    emit_trace_mode_preamble(&mut script);
    emit_activation_evidence(&mut script, generation, &paths.hookup_heartbeat_path());

    if let Some(blocks) = homebrew {
        homebrew::emit_homebrew_block(&mut script, blocks);
    }

    let Some(scan) = scan_pack_contributions(fs, paths)? else {
        append_empty_notice(&mut script);
        emit_path_attribution_clear(&mut script, &paths.path_attribution_path());
        emit_trace_mode_cleanup(&mut script);
        return Ok(script);
    };
    let PackScan {
        path_additions,
        shell_sources,
        ..
    } = scan;

    // Compose the packs tier once here rather than at each of the two
    // sites below that need it (the empty-datastore check and the
    // emitter) — see [`compose_path_tier`] for the tier/dedup rule
    // itself.
    let path_contributions = compose_path_tier(&path_additions, &homebrew_known_dirs(homebrew));

    if path_contributions.is_empty() && shell_sources.is_empty() {
        append_empty_notice(&mut script);
        emit_path_attribution_clear(&mut script, &paths.path_attribution_path());
        emit_trace_mode_cleanup(&mut script);
        return Ok(script);
    }

    // Profiling preamble (only when enabled and there's at least one entry).
    let profiling_active = profiling_enabled;
    if profiling_active {
        emit_profiling_preamble(
            &mut script,
            &paths.probes_shell_init_dir(),
            &paths.init_script_path(),
        );
    }

    if !path_contributions.is_empty() {
        writeln!(script, "# PATH additions").unwrap();
        for c in &path_contributions {
            writeln!(script, "# [{}]", c.pack).unwrap();
        }
        if profiling_active {
            emit_timed_path(&mut script, &path_contributions);
        } else {
            let joined = path_contributions
                .iter()
                .map(|c| c.dir.display().to_string())
                .collect::<Vec<_>>()
                .join(":");
            writeln!(script, "export PATH=\"{joined}:$PATH\"").unwrap();
        }
        writeln!(script).unwrap();
    }

    if !shell_sources.is_empty() {
        writeln!(script, "# Shell scripts").unwrap();
        emit_path_attribution_setup(&mut script);
        for (pack, targets) in group_consecutive_by_pack(&shell_sources) {
            emit_pack_path_diff_open(&mut script);
            for target in &targets {
                writeln!(script, "# [{pack}]").unwrap();
                if profiling_active {
                    emit_timed_source(&mut script, &pack, target);
                } else {
                    // Loud-failure wrapper: if the source command itself
                    // exits non-zero, print a dodot-attributed message to
                    // stderr alongside the shell's own error so the user
                    // can see *which* dodot-managed file failed. The
                    // shell's native message already carries the line
                    // number; we add the breadcrumb back to dodot.
                    writeln!(
                        script,
                        "[ -f \"{p}\" ] && {{ . \"{p}\" || echo \"dodot: shell source exited $?: {p}\" >&2; }}",
                        p = target.display()
                    )
                    .unwrap();
                }
            }
            // Per-pack $PATH diff (path-precedence.lex §5.2): only a
            // pack's own shell scripts can raw-mutate $PATH (the `path`
            // handler never does), so the capture/diff brackets this
            // group and only this group.
            emit_pack_path_diff_close(&mut script, &pack);
        }
        writeln!(script).unwrap();
    }

    if profiling_active {
        emit_profiling_epilogue(&mut script);
    }
    if !shell_sources.is_empty() {
        emit_path_attribution_write(&mut script, &paths.path_attribution_path());
    } else {
        emit_path_attribution_clear(&mut script, &paths.path_attribution_path());
    }
    emit_trace_mode_cleanup(&mut script);

    Ok(script)
}

/// Generate and write the init script to `data_dir/shell/dodot-init.sh`,
/// stamping it with a fresh generation.
///
/// The write is atomic ([`Fs::write_atomic_with_mode`]): the reader
/// is every shell the user opens, and a truncating in-place write
/// would let a shell starting mid-`up` source a prefix of the script
/// — usually still valid shell, so the loss is silent, and since the
/// activation evidence sits at the top of the script the truncated
/// load still stamps itself healthy (#297). The executable mode goes
/// on the temp before the rename, so the visible file is never a
/// non-executable script.
///
/// Also creates the heartbeat's parent directory. The emitted redirect
/// can't `mkdir -p` its own way out of a missing directory without
/// spending a process on every shell start, so the write side owns
/// that once per regeneration instead.
///
/// `homebrew` carries the captured Homebrew bootstrap, as for
/// [`generate_init_script`].
///
/// Returns the path where the script was written.
pub fn write_init_script(
    fs: &dyn Fs,
    paths: &dyn Pather,
    profiling_enabled: bool,
    homebrew: Option<&BrewBlocks>,
) -> Result<PathBuf> {
    let generation = activation::current_generation();
    let script_content = generate_init_script(fs, paths, profiling_enabled, generation, homebrew)?;
    let script_path = paths.init_script_path();

    fs.mkdir_all(&paths.probes_hookup_dir())?;
    fs.mkdir_all(paths.shell_dir())?;
    fs.write_atomic_with_mode(&script_path, script_content.as_bytes(), 0o755)?;

    Ok(script_path)
}

/// Emit the process-bound shell-init verification branch.
fn emit_init_probe_response(script: &mut String, generation: u64) {
    emit_init_probe_response_body(script, generation);
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
}

/// Emit the targeted response through its `exit 0`, leaving the opening
/// `if` unfinished so file-source and eval callers can choose their own
/// identity-mismatch behavior.
fn emit_init_probe_response_body(script: &mut String, generation: u64) {
    let version = activation::running_version();
    writeln!(script, "# dodot shell-init-probe v1").unwrap();
    writeln!(
        script,
        "if [ -n \"${{{}-}}\" ] && [ \"${{{}-}}\" = \"$PPID\" ]; then",
        probe::TARGET_PROBE_ENV,
        probe::TARGET_PROBE_PARENT_ENV
    )
    .unwrap();
    writeln!(
        script,
        "    _dodot_probe_nonce=${}",
        probe::TARGET_PROBE_ENV
    )
    .unwrap();
    writeln!(script, "    unset {}", probe::TARGET_PROBE_ENV).unwrap();
    writeln!(script, "    unset {}", probe::TARGET_PROBE_PARENT_ENV).unwrap();
    writeln!(
        script,
        "    \\printf '\\n{}%s|%s|%s|{}|{}\\n' \"$_dodot_probe_nonce\" \"$PPID\" \"$$\"",
        probe::TARGET_PROBE_MARKER,
        generation,
        version
    )
    .unwrap();
    writeln!(script, "    unset _dodot_probe_nonce").unwrap();
    writeln!(script, "    exit 0").unwrap();
}

// ── Activation evidence emitter ──────────────────────────────────────

/// Emit the evidence block (shell-hookup-ergonomics.lex §2.1).
///
/// - `export DODOT_INIT_GEN=<generation>` — free to read back from any
///   dodot process that the shell later spawns.
/// - `export DODOT_INIT_VERSION=<version>` — which dodot generated the
///   script *this* shell loaded. Without it a hookup can be wired,
///   sourced on every start, and still dead, because the binary that
///   wrote the script is not the binary the user runs.
/// - `echo <generation> <version> >| <heartbeat> 2>/dev/null || :` — one
///   builtin and one truncating redirect, now carrying both fields so a
///   detached caller can answer the same question about the last shell
///   anywhere. `2>/dev/null` keeps an unwritable data dir from spraying
///   errors across every shell start, and the `|| :` keeps the failed
///   redirect's non-zero status from aborting an rc file that runs
///   under `set -e`.
///
/// `>|`, not `>`: `setopt noclobber` / `set -C` is an ordinary rc line,
/// and under it a plain `>` *refuses* to write a file that already
/// exists. The heartbeat exists after the first activation, so every
/// activation from then on would fail silently — the two guards above
/// see to the silence — and freeze "last loaded" at the first shell
/// that ever ran. Three claims now rest on that file (the footer's
/// timestamp, the skew comparison, and the probe gate), so the failure
/// reads as a confident wrong answer rather than a missing one.
/// `>|` overrides `noclobber` and is POSIX; verified against zsh, bash
/// and dash, where plain `>` leaves the file untouched.
///
/// Still two exports and one redirect: no command execution, no `dodot`
/// invocation on the shell startup path.
fn emit_trace_mode_preamble(script: &mut String) {
    writeln!(script, "# dodot shell-init-trace v1").unwrap();
    writeln!(script, "_dodot_trace=0").unwrap();
    writeln!(
        script,
        "if [ -n \"${{{}-}}\" ]; then",
        trace::DIAGNOSTIC_TRACE_ENV
    )
    .unwrap();
    // Keep the process-scoped marker exported until the trace shell dies.
    // An rc may source this script more than once; consuming the marker on
    // the first source would let a later source write heartbeat/profile
    // evidence during the same diagnostic invocation.
    writeln!(script, "  _dodot_trace=1").unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
}

fn emit_trace_mode_cleanup(script: &mut String) {
    writeln!(script, "unset _dodot_trace 2>/dev/null").unwrap();
}

fn emit_activation_evidence(script: &mut String, generation: u64, heartbeat_path: &Path) {
    let heartbeat = sh_quote(&heartbeat_path.display().to_string());
    let version = activation::running_version();
    writeln!(script, "if [ \"${{_dodot_trace:-0}}\" != \"1\" ]; then").unwrap();
    writeln!(script, "# ── dodot activation evidence ──").unwrap();
    writeln!(script, "  export {}={generation}", activation::INIT_GEN_ENV).unwrap();
    writeln!(
        script,
        "  export {}={version}",
        activation::INIT_VERSION_ENV
    )
    .unwrap();
    writeln!(
        script,
        "  echo {generation} {version} >| {heartbeat} 2>/dev/null || :"
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
}

// ── Profiling wrapper emitters ───────────────────────────────────────

/// The runtime-detection preamble. Sets `_dodot_prof` to `1` when the
/// current shell is bash 5+ or zsh with `EPOCHREALTIME` available;
/// otherwise leaves it `0` (the wrapper falls through to the no-op
/// path). All shell variables are namespaced `_dodot_*` so we don't
/// stomp on the user's environment.
fn emit_profiling_preamble(script: &mut String, profiles_dir: &Path, init_script_path: &Path) {
    let dir = sh_quote(&profiles_dir.display().to_string());
    let init_script = sh_quote(&init_script_path.display().to_string());
    writeln!(script, "# ── dodot shell-init profiling (Phase 2) ──").unwrap();
    writeln!(script, "_dodot_prof=0").unwrap();
    writeln!(script, "if [ \"${{_dodot_trace:-0}}\" != \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  if [ -n \"${{BASH_VERSION:-}}\" ] || [ -n \"${{ZSH_VERSION:-}}\" ]; then"
    )
    .unwrap();
    // zsh exposes EPOCHREALTIME only after `zmodload zsh/datetime`. Load
    // it eagerly here; bash 5+ has the variable built in and ignores
    // unknown commands like `zmodload` (we suppress its `command not
    // found` error). Doing this *inside* the bash/zsh guard keeps it off
    // hot paths in plain sh.
    writeln!(
        script,
        "    [ -n \"${{ZSH_VERSION:-}}\" ] && zmodload zsh/datetime 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "    if [ -n \"${{EPOCHREALTIME:-}}\" ]; then").unwrap();
    writeln!(script, "      _dodot_prof_dir={dir}").unwrap();
    writeln!(
        script,
        "      _dodot_prof_file=\"$_dodot_prof_dir/profile-${{EPOCHSECONDS:-0}}-$$-${{RANDOM}}.tsv\""
    )
    .unwrap();
    // Sibling errors log: one record per source whose stderr was non-empty.
    // Format: `@@\t<target>\t<exit_status>` header line, followed by the
    // captured stderr verbatim, followed by a trailing newline. Loaded
    // alongside the profile by `probe::shell_init::read_recent_profiles`
    // and parsed by `probe::shell_init::parse_errors_log`.
    writeln!(
        script,
        "      _dodot_err_file=\"${{_dodot_prof_file%.tsv}}.errors.log\""
    )
    .unwrap();
    // Per-shell scratch file for capturing each source's stderr. Reused
    // across every source in this shell startup; truncated each time.
    writeln!(
        script,
        "      _dodot_err_tmp=\"$_dodot_prof_dir/.errtmp-$$\""
    )
    .unwrap();
    writeln!(
        script,
        "      if mkdir -p \"$_dodot_prof_dir\" 2>/dev/null; then"
    )
    .unwrap();
    writeln!(script, "        _dodot_prof_t0=$EPOCHREALTIME").unwrap();
    writeln!(script, "        {{").unwrap();
    writeln!(
        script,
        "          printf '# dodot shell-init profile v1\\n'"
    )
    .unwrap();
    writeln!(
        script,
        "          printf '# shell\\t%s\\n' \"${{BASH_VERSION:+bash $BASH_VERSION}}${{ZSH_VERSION:+zsh $ZSH_VERSION}}\""
    )
    .unwrap();
    writeln!(
        script,
        "          printf '# start_t\\t%s\\n' \"$_dodot_prof_t0\""
    )
    .unwrap();
    writeln!(
        script,
        "          printf '# init_script\\t%s\\n' {init_script}"
    )
    .unwrap();
    writeln!(
        script,
        "          printf '# columns\\tphase\\tpack\\thandler\\ttarget\\tstart_t\\tend_t\\texit_status\\n'"
    )
    .unwrap();
    writeln!(
        script,
        "        }} > \"$_dodot_prof_file\" 2>/dev/null && _dodot_prof=1"
    )
    .unwrap();
    // Errors log is created lazily — see `emit_timed_source`. Most shell
    // startups have no stderr from any source, and writing an empty
    // header file for each one would defeat the "fast path is free"
    // claim. The first source that actually emits stderr seeds the
    // header before appending its record.
    writeln!(script, "      fi").unwrap();
    writeln!(script, "    fi").unwrap();
    writeln!(script, "  fi").unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(script).unwrap();
}

/// One inline-timed `export PATH=…` row emitting the whole composed
/// packs-tier line in a single shell statement — composition is one
/// command now (§4.2 of the Spec), not one per directory — with one
/// profiling record per contributing directory, all sharing that one
/// timing window. The branch is one comparison at runtime — negligible
/// on shells where the wrapper is inert.
fn emit_timed_path(script: &mut String, contributions: &[PathContribution]) {
    let joined = contributions
        .iter()
        .map(|c| c.dir.display().to_string())
        .collect::<Vec<_>>()
        .join(":");
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  _dodot_t0=$EPOCHREALTIME; export PATH=\"{joined}:$PATH\"; _dodot_t1=$EPOCHREALTIME"
    )
    .unwrap();
    for c in contributions {
        let pack = &c.pack;
        let target_q = sh_quote(&c.dir.display().to_string());
        writeln!(
            script,
            "  printf 'path\\t{pack}\\tpath\\t%s\\t%s\\t%s\\t0\\n' {target_q} \"$_dodot_t0\" \"$_dodot_t1\" >> \"$_dodot_prof_file\" 2>/dev/null"
        )
        .unwrap();
    }
    writeln!(script, "else").unwrap();
    writeln!(script, "  export PATH=\"{joined}:$PATH\"").unwrap();
    writeln!(script, "fi").unwrap();
}

/// One inline-timed `[ -f X ] && . X` row, capturing the source's
/// exit status and stderr. Same overhead profile as the PATH variant
/// when the sourced file is silent; one extra `[ -s ]` test plus an
/// append when stderr is non-empty.
///
/// Both branches (profiling-active and unprofiled fallback) emit the
/// loud-failure message on a non-zero source exit, so users see the
/// dodot breadcrumb whether or not their shell supports the timing
/// path.
fn emit_timed_source(script: &mut String, pack: &str, target: &Path) {
    let target_str = target.display().to_string();
    let target_q = sh_quote(&target_str);
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    // `_dodot_rc` is initialised to 0 *before* the source attempt so a
    // missing file (the `[ -f … ]` test failing) does not get reported
    // as "exited 1". The compound `&& { … }` only sets `_dodot_rc` from
    // the actual `.` invocation; otherwise it stays 0. Stderr from the
    // source is redirected to `_dodot_err_tmp`; if non-empty, we
    // re-emit it to the user's stderr (preserving the shell's own
    // error display) and append it to the per-shell errors log.
    writeln!(
        script,
        "  _dodot_rc=0; : > \"$_dodot_err_tmp\" 2>/dev/null; _dodot_t0=$EPOCHREALTIME; [ -f \"{target_str}\" ] && {{ . \"{target_str}\" 2>\"$_dodot_err_tmp\"; _dodot_rc=$?; }}; _dodot_t1=$EPOCHREALTIME"
    )
    .unwrap();
    writeln!(
        script,
        "  printf 'source\\t{pack}\\tshell\\t%s\\t%s\\t%s\\t%s\\n' {target_q} \"$_dodot_t0\" \"$_dodot_t1\" \"$_dodot_rc\" >> \"$_dodot_prof_file\" 2>/dev/null"
    )
    .unwrap();
    // Stderr-handling block. Skipped entirely when the sourced file was
    // silent (the common case). When non-empty, we print to the user's
    // stderr and append a record to the errors log. The errors log is
    // seeded with its `v1` header on first use — keeping creation lazy
    // means a clean shell startup leaves no orphan `*.errors.log` on
    // disk. The trailing `\n` after each record guarantees the next
    // record's `@@` header starts on its own line even if the captured
    // stderr didn't end with a newline.
    writeln!(script, "  if [ -s \"$_dodot_err_tmp\" ]; then").unwrap();
    writeln!(script, "    cat \"$_dodot_err_tmp\" >&2").unwrap();
    writeln!(
        script,
        "    [ -f \"$_dodot_err_file\" ] || printf '# dodot shell-init errors v1\\n' > \"$_dodot_err_file\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "    {{").unwrap();
    writeln!(
        script,
        "      printf '@@\\t%s\\t%s\\n' {target_q} \"$_dodot_rc\""
    )
    .unwrap();
    writeln!(script, "      cat \"$_dodot_err_tmp\"").unwrap();
    writeln!(script, "      printf '\\n'").unwrap();
    writeln!(script, "    }} >> \"$_dodot_err_file\" 2>/dev/null").unwrap();
    writeln!(script, "  elif [ \"$_dodot_rc\" -ne 0 ]; then").unwrap();
    // Non-zero exit with empty stderr — still emit the loud breadcrumb
    // so the user knows dodot saw a failure (matches prior behaviour).
    writeln!(
        script,
        "    echo \"dodot: shell source exited $_dodot_rc: {target_str}\" >&2"
    )
    .unwrap();
    writeln!(script, "  fi").unwrap();
    writeln!(script, "else").unwrap();
    writeln!(
        script,
        "  [ -f \"{target_str}\" ] && {{ . \"{target_str}\" || echo \"dodot: shell source exited $?: {target_str}\" >&2; }}"
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
}

/// Closes out the report (writes the `# end_t` marker) and clears
/// every `_dodot_*` shell variable so we don't leak state into the
/// user's interactive shell.
fn emit_profiling_epilogue(script: &mut String) {
    writeln!(script, "# ── dodot shell-init profiling epilogue ──").unwrap();
    writeln!(script, "if [ \"$_dodot_prof\" = \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  printf '# end_t\\t%s\\n' \"$EPOCHREALTIME\" >> \"$_dodot_prof_file\" 2>/dev/null"
    )
    .unwrap();
    // Remove the per-shell stderr scratch file. It's reused across
    // sources within one shell startup; here at exit we tidy up.
    writeln!(
        script,
        "  [ -n \"${{_dodot_err_tmp:-}}\" ] && rm -f \"$_dodot_err_tmp\" 2>/dev/null"
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(
        script,
        "unset _dodot_prof _dodot_prof_dir _dodot_prof_file _dodot_err_file _dodot_err_tmp _dodot_prof_t0 _dodot_t0 _dodot_t1 _dodot_rc 2>/dev/null"
    )
    .unwrap();
}

// ── PATH attribution emitters (path-precedence.lex §5) ───────────────

/// Declares the accumulator the per-pack diffs below append to, plus a
/// literal-newline holder used to join rows without a portable `$'\n'`
/// (a bashism zsh and dash don't share) and a literal-tab holder used
/// to build each `<pack>\t<raw>` row without a `$(printf …)` subshell.
/// Emitted once, right before the first pack's shell scripts, only
/// when there is at least one shell script to wrap — a datastore with
/// PATH additions but no shell scripts can never raw-mutate `$PATH`,
/// so it never pays for this.
fn emit_path_attribution_setup(script: &mut String) {
    writeln!(
        script,
        "_dodot_pattr_buf=\"\" # path-precedence.lex §5.2: raw PATH mutations, one row per pack"
    )
    .unwrap();
    writeln!(script, "_dodot_pattr_nl='").unwrap();
    writeln!(script, "'").unwrap();
    writeln!(script, "_dodot_pattr_tab='\t'").unwrap();
}

/// Captures `$PATH` immediately before a pack's shell scripts run —
/// the "before" half of that pack's diff (§5.2).
fn emit_pack_path_diff_open(script: &mut String) {
    writeln!(script, "_dodot_pattr_before=\"$PATH\"").unwrap();
}

/// Diffs `$PATH` against the capture [`emit_pack_path_diff_open`] took,
/// and — when the pack introduced at least one new directory — appends
/// one `<pack>\t<raw>` row to the accumulator.
///
/// Unchanged `$PATH` is a no-op. Any other mutation — prepend, append,
/// replacement, or mixed — walks the after-value's colon-separated
/// components with `${var%%:*}` / `${var#*:}` and keeps those not
/// present in `$before` (one ordered set-difference, first occurrence
/// wins). A clean prepend of a directory already on `$PATH` is not
/// new, so it produces no row; neither does a change that only removes
/// entries. Pre-existing entries that remain are never attributed.
///
/// Substring matching only (§5.3), never word-splitting on `:` and
/// never forking. `case` patterns that match `$before` or a directory
/// are fully quoted, so special characters are matched literally,
/// never as glob syntax. The row is built by concatenating the quoted
/// pack name, a literal-tab holder, and the raw dirs — no command
/// substitution (`$(...)`) on this path, matching §5.2's "no forks,
/// pure string comparison" bound.
fn emit_pack_path_diff_close(script: &mut String, pack: &str) {
    let pack_q = sh_quote(pack);
    writeln!(script, "case \"$PATH\" in").unwrap();
    writeln!(script, "  \"$_dodot_pattr_before\") ;;").unwrap();
    writeln!(script, "  *)").unwrap();
    writeln!(script, "    _dodot_pattr_raw=").unwrap();
    writeln!(script, "    _dodot_pattr_rest=\"$PATH\"").unwrap();
    writeln!(script, "    while [ -n \"$_dodot_pattr_rest\" ]; do").unwrap();
    writeln!(script, "      case \"$_dodot_pattr_rest\" in").unwrap();
    writeln!(script, "        *:*)").unwrap();
    writeln!(
        script,
        "          _dodot_pattr_dir=\"${{_dodot_pattr_rest%%:*}}\""
    )
    .unwrap();
    writeln!(
        script,
        "          _dodot_pattr_rest=\"${{_dodot_pattr_rest#*:}}\""
    )
    .unwrap();
    writeln!(script, "          ;;").unwrap();
    writeln!(script, "        *)").unwrap();
    writeln!(script, "          _dodot_pattr_dir=\"$_dodot_pattr_rest\"").unwrap();
    writeln!(script, "          _dodot_pattr_rest=").unwrap();
    writeln!(script, "          ;;").unwrap();
    writeln!(script, "      esac").unwrap();
    writeln!(script, "      if [ -n \"$_dodot_pattr_dir\" ]; then").unwrap();
    writeln!(script, "        case \":$_dodot_pattr_before:\" in").unwrap();
    writeln!(script, "          *\":$_dodot_pattr_dir:\"*) ;;").unwrap();
    writeln!(script, "          *)").unwrap();
    writeln!(script, "            case \":$_dodot_pattr_raw:\" in").unwrap();
    writeln!(script, "              *\":$_dodot_pattr_dir:\"*) ;;").unwrap();
    writeln!(script, "              *)").unwrap();
    writeln!(
        script,
        "                _dodot_pattr_raw=\"${{_dodot_pattr_raw:+${{_dodot_pattr_raw}}:}}${{_dodot_pattr_dir}}\""
    )
    .unwrap();
    writeln!(script, "                ;;").unwrap();
    writeln!(script, "            esac").unwrap();
    writeln!(script, "            ;;").unwrap();
    writeln!(script, "        esac").unwrap();
    writeln!(script, "      fi").unwrap();
    writeln!(script, "    done").unwrap();
    emit_path_attribution_commit_row(script, &pack_q);
    writeln!(script, "    ;;").unwrap();
    writeln!(script, "esac").unwrap();
}

/// When `$_dodot_pattr_raw` is non-empty, builds the `<pack>\t<raw>`
/// row by concatenating the quoted pack name, the literal-tab holder,
/// and the raw dirs — no `$(printf …)` — and appends it to the
/// accumulator. `${var:+word}` — POSIX parameter expansion, not a
/// bashism — substitutes `word` only when `var` is set and non-empty,
/// so a single assignment covers both "first row" and "nth row"
/// without a further `if`/`else`.
fn emit_path_attribution_commit_row(script: &mut String, pack_q: &str) {
    writeln!(script, "    if [ -n \"$_dodot_pattr_raw\" ]; then").unwrap();
    writeln!(
        script,
        "      _dodot_pattr_row={pack_q}\"$_dodot_pattr_tab\"\"$_dodot_pattr_raw\""
    )
    .unwrap();
    writeln!(
        script,
        "      _dodot_pattr_buf=\"${{_dodot_pattr_buf:+${{_dodot_pattr_buf}}${{_dodot_pattr_nl}}}}${{_dodot_pattr_row}}\""
    )
    .unwrap();
    writeln!(script, "    fi").unwrap();
}

/// Writes the accumulated buffer to [`Pather::path_attribution_path`],
/// truncating (header-only, when no pack raw-mutated `$PATH` this run —
/// self-healing: a pack that stops mutating `$PATH` disappears from the
/// report on the very next shell start). One write, like the heartbeat
/// (§ activation evidence): a truncating redirect is a correct answer
/// to concurrent shell startups racing, an append or read-modify-write
/// would not be.
///
/// Guarded by the same `_dodot_trace` flag as the heartbeat and
/// profiling writes — a diagnostic trace run still executes pack shell
/// scripts (so the diff still runs, cheaply), but must not overwrite
/// attribution evidence from real shell startups with a trace run's own
/// transient state.
fn emit_path_attribution_write(script: &mut String, attribution_path: &Path) {
    let path_q = sh_quote(&attribution_path.display().to_string());
    writeln!(script, "if [ \"${{_dodot_trace:-0}}\" != \"1\" ]; then").unwrap();
    writeln!(script, "  if [ -n \"$_dodot_pattr_buf\" ]; then").unwrap();
    writeln!(
        script,
        "    printf '%s\\n%s\\n' {marker_q} \"$_dodot_pattr_buf\" >| {path_q} 2>/dev/null || :",
        marker_q = sh_quote(PATH_ATTRIBUTION_MARKER)
    )
    .unwrap();
    writeln!(script, "  else").unwrap();
    writeln!(
        script,
        "    printf '%s\\n' {marker_q} >| {path_q} 2>/dev/null || :",
        marker_q = sh_quote(PATH_ATTRIBUTION_MARKER)
    )
    .unwrap();
    writeln!(script, "  fi").unwrap();
    writeln!(script, "fi").unwrap();
    writeln!(
        script,
        "unset _dodot_pattr_buf _dodot_pattr_nl _dodot_pattr_tab _dodot_pattr_before _dodot_pattr_raw _dodot_pattr_row _dodot_pattr_rest _dodot_pattr_dir 2>/dev/null"
    )
    .unwrap();
}

/// Truncates the attribution file to its header alone — reached when
/// this run's datastore has nothing that could raw-mutate `$PATH`
/// (empty datastore, or packs with no shell scripts): stale attribution
/// from a pack that used to raw-mutate `$PATH` and no longer does must
/// not linger. Same trace guard and truncating-write reasoning as
/// [`emit_path_attribution_write`].
fn emit_path_attribution_clear(script: &mut String, attribution_path: &Path) {
    let path_q = sh_quote(&attribution_path.display().to_string());
    writeln!(script, "if [ \"${{_dodot_trace:-0}}\" != \"1\" ]; then").unwrap();
    writeln!(
        script,
        "  printf '%s\\n' {marker_q} >| {path_q} 2>/dev/null || :",
        marker_q = sh_quote(PATH_ATTRIBUTION_MARKER)
    )
    .unwrap();
    writeln!(script, "fi").unwrap();
}

/// Single-quote a string for safe use in POSIX shell. Embedded single
/// quotes are escaped via the `'\''` idiom.
fn sh_quote(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 2);
    out.push('\'');
    for c in s.chars() {
        if c == '\'' {
            out.push_str("'\\''");
        } else {
            out.push(c);
        }
    }
    out.push('\'');
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::datastore::{CommandOutput, CommandRunner, DataStore, FilesystemDataStore};
    use crate::testing::TempEnvironment;
    use std::sync::Arc;

    /// Pinned generation so emitted scripts are deterministic in
    /// tests; production stamps `activation::current_generation()`.
    const TEST_GEN: u64 = 1_755_200_000;

    struct NoopRunner;
    impl CommandRunner for NoopRunner {
        fn run(&self, _: &str, _: &[String]) -> Result<CommandOutput> {
            Ok(CommandOutput {
                exit_code: 0,
                stdout: String::new(),
                stderr: String::new(),
            })
        }
    }

    fn make_datastore(env: &TempEnvironment) -> FilesystemDataStore {
        FilesystemDataStore::new(env.fs.clone(), env.paths.clone(), Arc::new(NoopRunner))
    }

    #[test]
    fn empty_datastore_produces_helpful_script() {
        let env = TempEnvironment::builder().build();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(script.starts_with("#!/bin/sh"));
        assert!(script.contains("Generated by dodot"));
        assert!(script.contains("No shell scripts or PATH additions"));
        assert!(script.contains("dodot up"));
        assert!(script.contains("dodot status"));
        assert!(!script.contains("export PATH"));
        assert!(!script.contains(". \""));
    }

    #[test]
    fn shell_handler_state_produces_source_lines() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        let source = env.dotfiles_root.join("vim/aliases.sh");
        ds.create_data_link("vim", "shell", &source).unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(script.contains("# Shell scripts"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        // Loud-failure wrapper: existence-guarded source, with a
        // dodot-attributed echo on non-zero exit.
        assert!(
            script.contains(&format!(
                "[ -f \"{p}\" ] && {{ . \"{p}\" || echo \"dodot: shell source exited $?: {p}\" >&2; }}",
                p = source.display()
            )),
            "script:\n{script}"
        );
    }

    #[test]
    fn path_handler_state_produces_path_lines() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        let source = env.dotfiles_root.join("vim/bin");
        ds.create_data_link("vim", "path", &source).unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(script.contains("# PATH additions"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        assert!(
            script.contains(&format!("export PATH=\"{}:$PATH\"", source.display())),
            "script:\n{script}"
        );
    }

    #[test]
    fn multiple_packs_combined() {
        let env = TempEnvironment::builder()
            .pack("git")
            .file("aliases.sh", "alias gs='git status'")
            .done()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/vimrun", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);

        ds.create_data_link("git", "shell", &env.dotfiles_root.join("git/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(script.contains("# [git]"), "script:\n{script}");
        assert!(script.contains("# [vim]"), "script:\n{script}");
        assert!(script.contains("export PATH="), "script:\n{script}");
        let source_count = script.matches(". \"").count();
        assert_eq!(
            source_count, 2,
            "expected 2 source lines, script:\n{script}"
        );
    }

    #[test]
    fn write_init_script_creates_executable_file() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script_path =
            write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();

        assert_eq!(script_path, env.paths.init_script_path());
        env.assert_exists(&script_path);

        let content = env.fs.read_to_string(&script_path).unwrap();
        assert!(content.starts_with("#!/bin/sh"));
        assert!(content.contains("aliases.sh"));

        let meta = std::fs::metadata(&script_path).unwrap();
        use std::os::unix::fs::PermissionsExt;
        assert_eq!(meta.permissions().mode() & 0o111, 0o111);
    }

    /// The init script is *replaced* by rename, never truncated in
    /// place, so a shell that starts mid-`dodot up` can never source
    /// a prefix of the script (#297).
    ///
    /// A hard link is the proof: it shares the file's inode, so an
    /// in-place truncating write rewrites what the link sees, while a
    /// rename swaps the directory entry and leaves the link on the
    /// old inode. Same technique as homebrew's
    /// `persist_replaces_the_cache_by_rename_not_by_truncating_it`.
    #[test]
    fn init_script_is_replaced_by_rename_not_truncated_in_place() {
        let env = TempEnvironment::builder().build();

        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();
        let first = env.fs.read_to_string(&path).unwrap();

        let witness = path.parent().unwrap().join("witness.sh");
        std::fs::hard_link(&path, &witness).unwrap();

        // Different homebrew blocks force different content: the
        // generation stamp is seconds-resolution, so two back-to-back
        // writes could otherwise be byte-identical and prove nothing.
        let blocks = BrewBlocks {
            prefix: PathBuf::from("/opt/homebrew"),
            sh: "export HOMEBREW_PREFIX=/opt/homebrew;\n".to_string(),
            zsh: "export HOMEBREW_PREFIX=/opt/homebrew;\n".to_string(),
        };
        write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, Some(&blocks)).unwrap();

        let second = env.fs.read_to_string(&path).unwrap();
        assert_ne!(
            first, second,
            "the two writes must differ for the witness to prove anything"
        );
        assert_eq!(
            env.fs.read_to_string(&witness).unwrap(),
            first,
            "the old inode was rewritten: the init script is being \
             truncated in place, so a shell starting mid-write can \
             source a prefix of it"
        );

        // A successful write also leaves no temp sibling behind.
        let leftovers: Vec<String> = env
            .fs
            .read_dir(path.parent().unwrap())
            .unwrap()
            .into_iter()
            .map(|entry| entry.name)
            .filter(|name| name.ends_with(".tmp"))
            .collect();
        assert_eq!(leftovers, Vec::<String>::new());
    }

    #[test]
    fn script_regenerated_reflects_current_state() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);

        let script1 =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(!script1.contains("aliases.sh"));

        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script2 =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(script2.contains("aliases.sh"));

        ds.remove_state("vim", "shell").unwrap();

        let script3 =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(!script3.contains("aliases.sh"));
    }

    #[test]
    fn ignores_non_symlink_files_in_handler_dirs() {
        let env = TempEnvironment::builder().build();

        let shell_dir = env.paths.handler_data_dir("vim", "shell");
        env.fs.mkdir_all(&shell_dir).unwrap();
        env.fs
            .write_file(&shell_dir.join("not-a-symlink"), b"noise")
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(!script.contains("not-a-symlink"));
    }

    #[test]
    fn path_additions_come_before_shell_sources() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        let path_pos = script.find("# PATH additions").unwrap();
        let shell_pos = script.find("# Shell scripts").unwrap();
        assert!(
            path_pos < shell_pos,
            "PATH additions should come before shell sources"
        );
    }

    // ── PATH composition (path-precedence.lex §3–§4) ─────────────────

    /// The worked example from Spec §2.3, pinned as a fixture: three
    /// packs staging one directory each, read off disk in ascending
    /// order (`001-foo`, `200-bar`, `baz`), must compose into exactly
    /// that final order — the pack read *last* wins the front of the
    /// string, because prepending above system `$PATH` is what forces
    /// the direction, not a style choice.
    #[test]
    fn pinned_three_pack_worked_example_from_spec_2_3() {
        let env = TempEnvironment::builder().build();
        let ds = make_datastore(&env);

        let foo = env.home.join("dotfiles/001-foo/bin");
        let bar = env.home.join("dotfiles/200-bar/bin");
        let baz = env.home.join("dotfiles/baz/bin");
        ds.create_data_link("001-foo", "path", &foo).unwrap();
        ds.create_data_link("200-bar", "path", &bar).unwrap();
        ds.create_data_link("baz", "path", &baz).unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(
            script.contains(&format!(
                "export PATH=\"{}:{}:{}:$PATH\"",
                baz.display(),
                bar.display(),
                foo.display()
            )),
            "on-disk ascending 001-foo, 200-bar, baz must compose to baz:bar:foo, script:\n{script}"
        );
        // One computed line, not one per directory.
        assert_eq!(
            script.matches("export PATH=\"").count(),
            1,
            "script:\n{script}"
        );
    }

    /// Two packs staging the same directory must resolve to exactly one
    /// entry in the composed line (§3.2) — the higher-precedence pack
    /// (later on disk) keeps it, the earlier pack's repeat is dropped.
    #[test]
    fn two_packs_staging_the_same_directory_produce_one_entry() {
        let env = TempEnvironment::builder().build();
        let ds = make_datastore(&env);

        let shared = env.home.join("shared/bin");
        ds.create_data_link("aaa", "path", &shared).unwrap();
        ds.create_data_link("zzz", "path", &shared).unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert_eq!(
            script.matches(&shared.display().to_string()).count(),
            1,
            "script:\n{script}"
        );
        assert!(script.contains("# [zzz]"), "script:\n{script}");
        assert!(
            !script.contains("# [aaa]"),
            "the earlier pack's duplicate must not survive: script:\n{script}"
        );
    }

    /// A stale `001-homebrew` pack (or any pack) that duplicates the
    /// directory the built-in Homebrew capture already places on
    /// `$PATH` collapses into that one entry rather than adding a
    /// second — the exact case the Spec names by name (§3.2).
    #[test]
    fn stale_pack_duplicating_the_homebrew_bin_dir_is_dropped_from_the_packs_tier() {
        let env = TempEnvironment::builder().build();
        let ds = make_datastore(&env);

        let blocks = sample_brew_blocks();
        let stale_dir = blocks.prefix.join("bin");
        ds.create_data_link("001-homebrew", "path", &stale_dir)
            .unwrap();

        let script = generate_init_script(
            env.fs.as_ref(),
            env.paths.as_ref(),
            false,
            TEST_GEN,
            Some(&blocks),
        )
        .unwrap();

        assert!(
            !script.contains("# PATH additions"),
            "the packs tier must have nothing left once its only entry dedups away: script:\n{script}"
        );
        assert!(
            !script.contains("export PATH=\""),
            "no composed PATH line should be emitted: script:\n{script}"
        );
        assert!(
            script.contains("No shell scripts or PATH additions"),
            "script:\n{script}"
        );
    }

    /// The homebrew/toolchain tier is fixed below every pack regardless
    /// of naming (§3.1) — a pack named to sort *before* anything
    /// Homebrew-related still has its composed export line run after
    /// Homebrew's block, because the ordering is structural (Homebrew's
    /// block always emits first), not a function of on-disk names.
    #[test]
    fn homebrew_tier_stays_below_a_pack_even_when_the_pack_sorts_first() {
        let env = TempEnvironment::builder().build();
        let ds = make_datastore(&env);

        let dir = env.home.join("early/bin");
        ds.create_data_link("000-early", "path", &dir).unwrap();

        let script = generate_init_script(
            env.fs.as_ref(),
            env.paths.as_ref(),
            false,
            TEST_GEN,
            Some(&sample_brew_blocks()),
        )
        .unwrap();

        let brew_pos = script.find("# ── Homebrew environment ──").unwrap();
        let export_pos = script.find("export PATH=\"").unwrap();
        assert!(
            brew_pos < export_pos,
            "a pack named to sort first must still lose to the fixed Homebrew tier: script:\n{script}"
        );
        assert!(
            script.contains(&dir.display().to_string()),
            "script:\n{script}"
        );
    }

    /// The whole point of computing once in Rust: sourced for real, the
    /// shell's resulting `$PATH` must match what [`compose_path_tier`]
    /// computed — tiered, deduplicated, last-pack-wins — under both
    /// bash and zsh.
    #[test]
    fn real_shell_composes_the_pinned_path_matching_the_rust_computed_value() {
        let env = TempEnvironment::builder().build();
        let ds = make_datastore(&env);

        let foo = env.home.join("001-foo/bin");
        let bar = env.home.join("200-bar/bin");
        let baz = env.home.join("baz/bin");
        ds.create_data_link("001-foo", "path", &foo).unwrap();
        ds.create_data_link("200-bar", "path", &bar).unwrap();
        ds.create_data_link("baz", "path", &baz).unwrap();

        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();
        let expected = format!(
            "{}:{}:{}:/preexisting",
            baz.display(),
            bar.display(),
            foo.display()
        );

        // `--noprofile --norc` (bash) / `-f` (zsh, same no-rc guard
        // `trace.rs`'s `HookupShell::Zsh` uses) keep the host's own rc
        // files — which may append their own PATH entries, e.g.
        // `~/.cargo/bin` — from folding into what we're trying to
        // measure here: the script's own composed line, in isolation.
        let shells: &[(&str, &[&str])] = &[
            ("/bin/bash", &["--noprofile", "--norc", "-c"]),
            ("/bin/zsh", &["-f", "-c"]),
        ];
        for (shell, flags) in shells {
            let shell_path = Path::new(shell);
            if !shell_path.exists() {
                continue;
            }
            let out = std::process::Command::new(shell_path)
                .args(*flags)
                .arg(format!(". '{}'; printf '%s' \"$PATH\"", path.display()))
                .env("PATH", "/preexisting")
                .output()
                .expect("the shell runs");
            assert!(out.status.success(), "{shell}: sourcing failed: {out:?}");
            assert_eq!(
                String::from_utf8_lossy(&out.stdout),
                expected,
                "{shell}: composed $PATH did not match the Rust-computed value"
            );
        }
    }

    // ── PATH provenance (path-precedence.lex §5) ─────────────────────

    /// The regression this WS exists to close (§5.1): once composition
    /// stopped being sequential runtime prepend, a raw `export PATH=`
    /// a pack's own shell script issues has nowhere to land unless
    /// something captures it. Sourced for real, under both bash and
    /// zsh, the raw entry must (a) still land in the final `$PATH`,
    /// ahead of the declared entry — the same pack ran its shell
    /// script *after* the composed PATH line, so its own prepend wins
    /// the front, consistent with "last pack wins" (§2.3) — and (b) be
    /// recorded to the attribution file, tagged to the pack that
    /// caused it (§5.2).
    #[test]
    fn raw_path_mutation_survives_and_is_attributed_to_its_pack() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("bin/vim-tool", "#!/bin/sh")
            .file("raw.sh", "export PATH=\"$HOME/rawbin:$PATH\"\n")
            .done()
            .build();

        let ds = make_datastore(&env);
        let declared_dir = env.dotfiles_root.join("vim/bin");
        ds.create_data_link("vim", "path", &declared_dir).unwrap();
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/raw.sh"))
            .unwrap();

        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();

        let raw_dir = env.home.join("rawbin");
        let expected = format!(
            "{}:{}:/preexisting",
            raw_dir.display(),
            declared_dir.display()
        );

        let shells: &[(&str, &[&str])] = &[
            ("/bin/bash", &["--noprofile", "--norc", "-c"]),
            ("/bin/zsh", &["-f", "-c"]),
        ];
        let mut ran_any = false;
        for (shell, flags) in shells {
            let shell_path = Path::new(shell);
            if !shell_path.exists() {
                continue;
            }
            ran_any = true;
            let out = std::process::Command::new(shell_path)
                .args(*flags)
                .arg(format!(". '{}'; printf '%s' \"$PATH\"", path.display()))
                .env("PATH", "/preexisting")
                .env("HOME", &env.home)
                .output()
                .expect("the shell runs");
            assert!(out.status.success(), "{shell}: sourcing failed: {out:?}");
            assert_eq!(
                String::from_utf8_lossy(&out.stdout),
                expected,
                "{shell}: raw PATH mutation did not survive into the final composed PATH"
            );

            let attribution = env
                .fs
                .read_to_string(&env.paths.path_attribution_path())
                .unwrap();
            assert!(
                attribution.contains(&format!("vim\t{}", raw_dir.display())),
                "{shell}: attribution file did not record the raw mutation:\n{attribution}"
            );
        }
        assert!(
            ran_any,
            "neither /bin/bash nor /bin/zsh is available to test against"
        );
    }

    /// A pack whose shell scripts never touch `$PATH` must leave no
    /// attribution row — the common case, and the one this feature must
    /// stay free on (§5.2's "bounded" claim would be hollow if every
    /// ordinary shell script produced a row).
    #[test]
    fn shell_scripts_that_do_not_touch_path_produce_no_attribution_row() {
        let bash = Path::new("/bin/bash");
        if !bash.exists() {
            return;
        }
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim\n")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();
        let status = std::process::Command::new(bash)
            .args(["--noprofile", "--norc", "-c"])
            .arg(format!(". '{}'", path.display()))
            .env("HOME", &env.home)
            .status()
            .expect("bash runs");
        assert!(status.success());

        let attribution = env
            .fs
            .read_to_string(&env.paths.path_attribution_path())
            .unwrap();
        assert_eq!(
            path_attribution::parse_path_attribution(&attribution),
            Vec::new(),
            "attribution:\n{attribution}"
        );
        // On-disk format matches the header-only truncation
        // `emit_path_attribution_write`'s docstring promises — no extra
        // blank line trailing the marker when nothing changed.
        assert_eq!(
            attribution,
            format!("{}\n", path_attribution::PATH_ATTRIBUTION_MARKER),
            "attribution:\n{attribution:?}"
        );
    }

    /// Source `init_script` under each of bash and zsh present on this
    /// host, with `PATH` set to `path_env` and `HOME` to `env.home`.
    /// Returns `(shell, resulting $PATH, attribution file)` per shell
    /// that ran — attribution is read after each source because the
    /// file is truncated per run.
    fn source_init_under_supported_shells(
        env: &TempEnvironment,
        init_script: &Path,
        path_env: &str,
    ) -> Vec<(&'static str, String, String)> {
        let shells: &[(&str, &[&str])] = &[
            ("/bin/bash", &["--noprofile", "--norc", "-c"]),
            ("/bin/zsh", &["-f", "-c"]),
        ];
        let mut results = Vec::new();
        for (shell, flags) in shells {
            let shell_path = Path::new(shell);
            if !shell_path.exists() {
                continue;
            }
            let out = std::process::Command::new(shell_path)
                .args(*flags)
                .arg(format!(
                    ". '{}'; printf '%s' \"$PATH\"",
                    init_script.display()
                ))
                .env("PATH", path_env)
                .env("HOME", &env.home)
                .output()
                .expect("the shell runs");
            assert!(out.status.success(), "{shell}: sourcing failed: {out:?}");
            let attribution = env
                .fs
                .read_to_string(&env.paths.path_attribution_path())
                .unwrap();
            results.push((
                *shell,
                String::from_utf8_lossy(&out.stdout).into_owned(),
                attribution,
            ));
        }
        assert!(
            !results.is_empty(),
            "neither /bin/bash nor /bin/zsh is available to test against"
        );
        results
    }

    fn deploy_vim_raw_sh(env: &TempEnvironment) -> PathBuf {
        let ds = make_datastore(env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/raw.sh"))
            .unwrap();
        write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap()
    }

    /// Append (`PATH="$PATH:…"`) must attribute only the newly
    /// introduced directory, not the pre-existing entries that remain
    /// in `$PATH`. The previous fallback recorded the entire after-value.
    #[test]
    fn raw_path_append_attributes_only_the_new_entry() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"$PATH:$HOME/appended\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);
        let appended = env.home.join("appended");
        let expected_path = format!("/preexisting:{}", appended.display());
        let expected_row = format!("vim\t{}", appended.display());

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting")
        {
            assert_eq!(resulting, expected_path, "{shell}: live $PATH");
            assert!(
                attribution.contains(&expected_row),
                "{shell}: attribution must record only the appended dir:\n{attribution}"
            );
            assert!(
                !attribution.contains("/preexisting"),
                "{shell}: pre-existing entries must not be attributed to the pack:\n{attribution}"
            );
        }
    }

    /// A full replacement attributes the new directory and does not
    /// claim the dropped pre-existing ones.
    #[test]
    fn raw_path_replacement_attributes_only_the_new_entry() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"$HOME/replaced\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);
        let replaced = env.home.join("replaced");
        let expected_row = format!("vim\t{}", replaced.display());

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting:/keep")
        {
            assert_eq!(
                resulting,
                replaced.display().to_string(),
                "{shell}: live $PATH"
            );
            assert!(
                attribution.contains(&expected_row),
                "{shell}: attribution:\n{attribution}"
            );
            assert!(
                !attribution.contains("/preexisting") && !attribution.contains("/keep"),
                "{shell}: dropped entries must not be attributed:\n{attribution}"
            );
        }
    }

    /// A mutation that only removes entries introduces nothing, so it
    /// leaves no attribution row — same on-disk header-only form as a
    /// pack that never touched `$PATH`.
    #[test]
    fn raw_path_removal_produces_no_attribution_row() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"/keep\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting:/keep")
        {
            assert_eq!(resulting, "/keep", "{shell}: live $PATH");
            assert_eq!(
                path_attribution::parse_path_attribution(&attribution),
                Vec::new(),
                "{shell}: removal-only must not attribute leftover entries:\n{attribution}"
            );
        }
    }

    /// Mixed change: prepend one new dir, keep one pre-existing, append
    /// another new dir, drop a third. Only the two new dirs are
    /// attributed, in after-value order.
    #[test]
    fn raw_path_mixed_change_attributes_only_newly_introduced_entries() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"$HOME/new1:/keep:$HOME/new2\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);
        let new1 = env.home.join("new1");
        let new2 = env.home.join("new2");
        let expected_path = format!("{}:/keep:{}", new1.display(), new2.display());
        let expected_row = format!("vim\t{}:{}", new1.display(), new2.display());

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting:/keep")
        {
            assert_eq!(resulting, expected_path, "{shell}: live $PATH");
            assert!(
                attribution.contains(&expected_row),
                "{shell}: attribution must be the two new dirs in after-order:\n{attribution}"
            );
            assert!(
                !attribution.contains("/preexisting")
                    && !attribution.contains("\t/keep")
                    && !attribution.contains(":/keep"),
                "{shell}: kept/dropped pre-existing entries must not be attributed:\n{attribution}"
            );
        }
    }

    /// §5.2 constrains attribution to "no forks, pure string
    /// comparison": the generated per-pack diff must not command-sub
    /// (`$(...)`) or backtick to build a row.
    #[test]
    fn path_attribution_diff_does_not_use_command_substitution() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim\n")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        let start = script.find("_dodot_pattr_buf=").expect("attribution setup");
        let attribution = &script[start..];
        assert!(
            !attribution.contains("$("),
            "attribution must not fork via command substitution:\n{attribution}"
        );
        assert!(
            !attribution.contains('`'),
            "attribution must not fork via backticks:\n{attribution}"
        );
    }

    /// Prepending a directory already on `$PATH` changes the live
    /// string (a duplicate at the front) but introduces nothing new, so
    /// it must not be attributed as a raw contribution.
    #[test]
    fn raw_path_prepend_of_already_present_entry_produces_no_attribution_row() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"/preexisting:$PATH\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting:/keep")
        {
            assert_eq!(
                resulting, "/preexisting:/preexisting:/keep",
                "{shell}: live $PATH"
            );
            assert_eq!(
                path_attribution::parse_path_attribution(&attribution),
                Vec::new(),
                "{shell}: already-present prepend must not be attributed:\n{attribution}"
            );
        }
    }

    /// A clean multi-entry prepend mixing a new dir with one already on
    /// `$PATH` attributes only the new dir.
    #[test]
    fn raw_path_prepend_of_mixed_new_and_existing_attributes_only_the_new_entry() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("raw.sh", "export PATH=\"$HOME/new:/preexisting:$PATH\"\n")
            .done()
            .build();
        let path = deploy_vim_raw_sh(&env);
        let new = env.home.join("new");
        let expected_path = format!("{}:/preexisting:/preexisting:/keep", new.display());
        let expected_row = format!("vim\t{}", new.display());

        for (shell, resulting, attribution) in
            source_init_under_supported_shells(&env, &path, "/preexisting:/keep")
        {
            assert_eq!(resulting, expected_path, "{shell}: live $PATH");
            assert!(
                attribution.contains(&expected_row),
                "{shell}: attribution must record only the new dir:\n{attribution}"
            );
            assert!(
                !attribution.contains("/preexisting") && !attribution.contains("/keep"),
                "{shell}: already-present entries must not be attributed:\n{attribution}"
            );
        }
    }

    // ── Homebrew bootstrap (shell-hookup-ergonomics.lex §4) ─────────

    /// Stand-in for a captured `brew shellenv`, shaped like the real
    /// thing (zsh block carries the zsh-only `fpath` lines).
    fn sample_brew_blocks() -> BrewBlocks {
        BrewBlocks {
            prefix: PathBuf::from("/opt/homebrew"),
            sh: "export HOMEBREW_PREFIX=\"/opt/homebrew\";\n\
                 eval \"$(/usr/bin/env PATH_HELPER_ROOT=\"/opt/homebrew\" /usr/libexec/path_helper -s)\"\n"
                .to_string(),
            zsh: "export HOMEBREW_PREFIX=\"/opt/homebrew\";\n\
                  fpath[1,0]=\"/opt/homebrew/share/zsh/site-functions\";\n\
                  export FPATH;\n"
                .to_string(),
        }
    }

    /// The ordering claim the whole feature rests on, asserted against
    /// the generated script rather than assumed: brew's block lands
    /// above the first pack PATH addition, so dodot's own entries are
    /// prepended *after* brew's and therefore win.
    #[test]
    fn homebrew_block_precedes_the_first_pack_path_addition() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script = generate_init_script(
            env.fs.as_ref(),
            env.paths.as_ref(),
            false,
            TEST_GEN,
            Some(&sample_brew_blocks()),
        )
        .unwrap();

        let brew_pos = script.find("# ── Homebrew environment ──").unwrap();
        let path_pos = script.find("# PATH additions").unwrap();
        let export_pos = script.find("export PATH=\"").unwrap();
        let source_pos = script.find("# Shell scripts").unwrap();
        assert!(
            brew_pos < path_pos && brew_pos < export_pos && brew_pos < source_pos,
            "Homebrew block must come first, script:\n{script}"
        );
    }

    /// The whole emission order in one script, read back as text.
    ///
    /// The version stamp (`shell-hookup-ergonomics.lex` §2.1) and the
    /// Homebrew bootstrap (§4) were written against the same generator
    /// and only meet here, so the order they compose into is asserted
    /// rather than inferred from the fact that both compile: activation
    /// evidence first — all three lines, the version among them —
    /// then brew, then anything a pack contributed.
    #[test]
    fn the_evidence_block_precedes_the_homebrew_block_precedes_the_packs() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/myscript", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script = generate_init_script(
            env.fs.as_ref(),
            env.paths.as_ref(),
            false,
            TEST_GEN,
            Some(&sample_brew_blocks()),
        )
        .unwrap();

        let positions = [
            ("evidence header", "# ── dodot activation evidence ──"),
            ("generation export", "export DODOT_INIT_GEN="),
            ("version export", "export DODOT_INIT_VERSION="),
            ("heartbeat redirect", "echo "),
            ("Homebrew block", "# ── Homebrew environment ──"),
            ("PATH additions", "# PATH additions"),
            ("shell sources", "# Shell scripts"),
        ]
        .map(|(label, needle)| {
            (
                label,
                script
                    .find(needle)
                    .unwrap_or_else(|| panic!("missing {label} ({needle}), script:\n{script}")),
            )
        });

        for pair in positions.windows(2) {
            let [(before, at), (after, then)] = pair else {
                unreachable!()
            };
            assert!(
                at < then,
                "{before} must precede {after}, script:\n{script}"
            );
        }
    }

    /// The bootstrap does not depend on any pack having deployed, so a
    /// datastore with nothing in it still carries it — that is the case
    /// where the user's rc file is empty and brew is all they need.
    #[test]
    fn homebrew_block_survives_an_empty_datastore() {
        let env = TempEnvironment::builder().build();

        let script = generate_init_script(
            env.fs.as_ref(),
            env.paths.as_ref(),
            false,
            TEST_GEN,
            Some(&sample_brew_blocks()),
        )
        .unwrap();

        assert!(
            script.contains("# ── Homebrew environment ──"),
            "script:\n{script}"
        );
        assert!(script.contains("HOMEBREW_PREFIX"), "script:\n{script}");
        // The empty notice is about pack contributions and still holds.
        assert!(script.contains("No shell scripts or PATH additions"));
    }

    /// `off`, a non-macOS host and a brew-less mac all arrive here as
    /// `None`, and none of them may leave a trace in the script.
    #[test]
    fn no_capture_means_no_homebrew_lines_at_all() {
        let env = TempEnvironment::builder().build();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        assert!(!script.contains("Homebrew"), "script:\n{script}");
        assert!(!script.contains("HOMEBREW"), "script:\n{script}");
        assert!(!script.contains("brew"), "script:\n{script}");
    }

    #[test]
    fn targeted_probe_branch_precedes_activation_evidence() {
        let env = TempEnvironment::builder().build();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();

        let probe = script.find("# dodot shell-init-probe v1").unwrap();
        let evidence = script.find("# ── dodot activation evidence ──").unwrap();
        assert!(
            probe < evidence,
            "verification branch must answer before heartbeat/profile setup:\n{script}"
        );
        assert!(script_supports_targeted_probe(&script));
    }

    #[test]
    fn diagnostic_trace_mode_precedes_and_guards_mutating_evidence() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();

        let trace = script.find("# dodot shell-init-trace v1").unwrap();
        let evidence_guard = script
            .find("if [ \"${_dodot_trace:-0}\" != \"1\" ]; then")
            .unwrap();
        let path_or_shell = script.find("# Shell scripts").unwrap();
        assert!(
            trace < evidence_guard && evidence_guard < path_or_shell,
            "diagnostic trace mode must be known before evidence/profile writes but keep contributions:\n{script}"
        );
        assert!(script_supports_diagnostic_trace(&script));
    }

    #[test]
    fn generated_scripts_do_not_leave_trace_state_in_the_shell() {
        let bash = std::path::Path::new("/bin/bash");
        if !bash.exists() {
            return;
        }

        let empty_env = TempEnvironment::builder().build();
        let empty_script = generate_init_script(
            empty_env.fs.as_ref(),
            empty_env.paths.as_ref(),
            false,
            TEST_GEN,
            None,
        )
        .unwrap();
        assert_trace_state_is_cleaned(bash, &empty_env, &empty_script, "empty");

        let env = TempEnvironment::builder()
            .pack("vim")
            .file("bin/tool", "#!/bin/sh\n")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        for (label, profiling) in [("plain", false), ("profiled", true)] {
            let script = generate_init_script(
                env.fs.as_ref(),
                env.paths.as_ref(),
                profiling,
                TEST_GEN,
                None,
            )
            .unwrap();
            assert_trace_state_is_cleaned(bash, &env, &script, label);
        }
    }

    #[test]
    fn diagnostic_trace_mode_stays_sticky_across_repeated_sources() {
        let bash = std::path::Path::new("/bin/bash");
        if !bash.exists() {
            return;
        }

        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        env.fs.mkdir_all(&env.paths.probes_hookup_dir()).unwrap();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();
        let script_path = env.home.join("dodot-init.sh");
        env.fs.write_file(&script_path, script.as_bytes()).unwrap();
        let source_twice = format!(
            ". {path}; . {path}",
            path = sh_quote(&script_path.display().to_string())
        );

        let status = std::process::Command::new(bash)
            .args(["--noprofile", "--norc", "-c", &source_twice])
            .env(trace::DIAGNOSTIC_TRACE_ENV, "1")
            .env("HOME", &env.home)
            .status()
            .expect("bash runs");

        assert!(
            status.success(),
            "generated script failed when sourced twice"
        );
        assert!(
            !env.fs.exists(&env.paths.hookup_heartbeat_path()),
            "the second source wrote activation evidence"
        );
        assert!(
            env.fs
                .read_dir(&env.paths.probes_shell_init_dir())
                .unwrap_or_default()
                .is_empty(),
            "the second source created a startup profile"
        );
    }

    fn assert_trace_state_is_cleaned(
        bash: &std::path::Path,
        env: &TempEnvironment,
        script: &str,
        label: &str,
    ) {
        let script_path = env.home.join(format!("{label}-dodot-init.sh"));
        env.fs.mkdir_all(&env.paths.probes_hookup_dir()).unwrap();
        env.fs.write_file(&script_path, script.as_bytes()).unwrap();
        let status = std::process::Command::new(bash)
            .arg("-c")
            .arg(format!(
                ". {}; test -z \"${{_dodot_trace+x}}\"",
                sh_quote(&script_path.display().to_string())
            ))
            .status()
            .expect("bash runs");
        assert!(
            status.success(),
            "{label}: generated script left _dodot_trace in scope:\n{script}"
        );
    }

    #[test]
    fn eval_probe_response_contains_no_ordinary_init_body() {
        let script = generate_init_probe_response(TEST_GEN);

        assert!(script_supports_targeted_probe(&script));
        assert!(script.contains(&format!("|{TEST_GEN}|{}", activation::running_version())));
        assert!(!script.contains("DODOT_INIT_GEN"), "script:\n{script}");
        assert!(!script.contains("heartbeat"), "script:\n{script}");
        assert!(!script.contains("shell-init profile"), "script:\n{script}");
        assert!(!script.contains("Homebrew"), "script:\n{script}");
    }

    // ── Phase 2: profiling wrapper ──────────────────────────────────

    #[test]
    fn profiling_disabled_omits_the_profile_wrapper() {
        // The contract: when profiling is off, the profile writer is
        // absent. Other top-of-file protocol branches may still be
        // present because they serve verification and tracing.
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(!script.contains("_dodot_prof"));
        assert!(!script.contains("EPOCHREALTIME"));
        assert!(!script.contains("dodot shell-init profile"));
    }

    #[test]
    fn profiling_enabled_emits_runtime_gated_preamble() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();

        assert!(script.contains("BASH_VERSION"));
        assert!(script.contains("ZSH_VERSION"));
        assert!(script.contains("EPOCHREALTIME"));
        assert!(script.contains(env.paths.probes_shell_init_dir().to_str().unwrap()));
        assert!(script.contains("$$"));
        assert!(script.contains("RANDOM"));
        assert!(script.contains("# dodot shell-init profile v1"));
        assert!(script.contains("columns\\tphase\\tpack\\thandler\\ttarget"));
    }

    #[test]
    fn profiling_enabled_wraps_each_source_with_else_path() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "")
            .file("bin/tool", "#!/bin/sh")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();

        // Each entry has an if/else so unprofiled shells still source / set PATH.
        // (One else per entry; scoped to the section before the profiling
        // epilogue, which has its own unrelated if/else for the attribution
        // write's empty-buffer case.)
        let entries_section = script
            .split("dodot shell-init profiling epilogue")
            .next()
            .unwrap();
        let else_count = entries_section.matches("else").count();
        assert_eq!(
            else_count, 2,
            "expected one else-branch per entry; script:\n{script}"
        );

        // Source row carries the captured exit status; PATH row hard-codes 0.
        assert!(script.contains("printf 'source\\tvim\\tshell\\t"));
        assert!(script.contains("printf 'path\\tvim\\tpath\\t"));
        assert!(script.contains("\"$_dodot_rc\""));
    }

    #[test]
    fn profiling_captures_source_stderr_into_errors_log() {
        // The wrapper must redirect each source's stderr to the per-shell
        // scratch file and append a versioned record (`@@\ttarget\texit`)
        // to the errors.log sibling whenever stderr is non-empty.
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();

        assert!(
            script.contains("_dodot_err_file=\"${_dodot_prof_file%.tsv}.errors.log\""),
            "errors-log path must be a sibling of the profile TSV:\n{script}"
        );
        // Versioned header is seeded lazily — only on first stderr from
        // a sourced file, guarded by `[ -f "$_dodot_err_file" ]` so an
        // all-silent shell startup leaves no sidecar on disk.
        assert!(
            script.contains("[ -f \"$_dodot_err_file\" ] || printf '# dodot shell-init errors v1"),
            "errors-log header must be seeded lazily on first stderr:\n{script}"
        );
        assert!(
            script.contains("2>\"$_dodot_err_tmp\""),
            "source must redirect stderr to scratch file:\n{script}"
        );
        // Truncation before each source so a previous source's stderr
        // doesn't leak into the next record.
        assert!(
            script.contains(": > \"$_dodot_err_tmp\""),
            "scratch file must be truncated before each source:\n{script}"
        );
        assert!(
            script.contains("printf '@@\\t%s\\t%s\\n'"),
            "errors-log records must use @@ header format:\n{script}"
        );
    }

    #[test]
    fn profiling_epilogue_writes_end_marker_and_unsets_state() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();
        assert!(script.contains("# end_t"));
        assert!(script.contains("unset _dodot_prof"));
        assert!(script.contains("_dodot_prof_file"));
    }

    #[test]
    fn profiling_enabled_with_empty_datastore_skips_preamble() {
        let env = TempEnvironment::builder().build();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();
        assert!(script.contains("No shell scripts or PATH additions"));
        assert!(!script.contains("_dodot_prof"));
    }

    #[test]
    fn profiled_source_initialises_rc_so_missing_file_isnt_reported_as_failure() {
        // A missing file is not a source failure: initialize rc to zero
        // and only update it when the source command actually runs.
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
                .unwrap();
        assert!(
            script.contains("_dodot_rc=0;"),
            "profiled branch must seed _dodot_rc=0 before the source attempt:\n{script}"
        );
        assert!(
            script.contains("&& { . "),
            "profiled branch must guard the rc update inside `&& {{ … }}`:\n{script}"
        );
    }

    #[test]
    fn loud_failure_wrapper_present_in_both_modes() {
        // A non-zero exit from a sourced file must surface as a
        // dodot-attributed message on stderr, regardless of whether
        // profiling is on. This is the user-facing breadcrumb that
        // says "the dodot-managed source exited non-zero" alongside
        // the shell's own line-numbered error.
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();

        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();

        // Profiling off: inline OR-echo form.
        let plain =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        assert!(
            plain.contains("dodot: shell source exited $?:"),
            "plain script missing loud-failure echo:\n{plain}"
        );

        // Profiling on: timed branch echoes from the elif-empty-stderr
        // arm (silent failure case); the with-stderr arm relies on
        // re-emitting the captured stderr to the user's TTY. Unprofiled
        // fallback uses the OR-echo form like the plain path.
        let timed = generate_init_script(env.fs.as_ref(), env.paths.as_ref(), true, TEST_GEN, None)
            .unwrap();
        assert!(
            timed.contains("echo \"dodot: shell source exited $_dodot_rc:"),
            "timed script missing silent-failure echo:\n{timed}"
        );
        assert!(
            timed.contains("dodot: shell source exited $?:"),
            "timed script missing fallback-branch echo:\n{timed}"
        );
        // Captured stderr is re-emitted to the user's TTY before being
        // appended to the errors log, so they still see it live.
        assert!(
            timed.contains("cat \"$_dodot_err_tmp\" >&2"),
            "timed script must echo captured stderr to user's TTY:\n{timed}"
        );
    }

    // ── Activation evidence (shell-hookup.lex §2.1) ─────────────────

    /// Every shape of generated script must carry both evidence lines:
    /// the evidence is unconditional, which is exactly what separates
    /// it from the opt-in profiling instrumentation.
    #[test]
    fn evidence_is_emitted_unconditionally_in_every_script_shape() {
        let empty = TempEnvironment::builder().build();
        let populated = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .done()
            .build();
        let ds = make_datastore(&populated);
        ds.create_data_link(
            "vim",
            "shell",
            &populated.dotfiles_root.join("vim/aliases.sh"),
        )
        .unwrap();

        let shapes = [
            ("empty datastore", &empty, false),
            ("empty datastore, profiled", &empty, true),
            ("populated", &populated, false),
            ("populated, profiled", &populated, true),
        ];
        for (label, env, profiling) in shapes {
            let script = generate_init_script(
                env.fs.as_ref(),
                env.paths.as_ref(),
                profiling,
                TEST_GEN,
                None,
            )
            .unwrap();
            assert!(
                script.contains(&format!("export DODOT_INIT_GEN={TEST_GEN}")),
                "{label}: missing generation stamp:\n{script}"
            );
            assert!(
                script.contains(&format!(
                    "export DODOT_INIT_VERSION={}",
                    activation::running_version()
                )),
                "{label}: missing version stamp:\n{script}"
            );
            // `>|`, not `>`: under `noclobber` a plain `>` refuses to
            // overwrite the heartbeat once it exists, and the `2>/dev/null
            // || :` guards swallow the refusal — freezing "last loaded"
            // at the first shell that ever ran.
            assert!(
                script.contains(&format!(
                    "echo {TEST_GEN} {} >| '{}' 2>/dev/null || :",
                    activation::running_version(),
                    env.paths.hookup_heartbeat_path().display()
                )),
                "{label}: missing heartbeat write:\n{script}"
            );
            assert_eq!(
                activation::parse_script_generation(&script),
                Some(TEST_GEN),
                "{label}: generation must round-trip out of the script"
            );
        }
    }

    /// `noclobber` is an ordinary rc line, and under it a plain `>`
    /// refuses to write a file that already exists. The heartbeat
    /// exists from the second activation onward, so with `>` every
    /// activation after the first fails — silently, because the
    /// redirect carries `2>/dev/null || :` — and "last loaded" freezes
    /// at the first shell the user ever opened. Three of this epic's
    /// claims read that file, so the freeze surfaces as a confident
    /// wrong answer rather than a missing one.
    ///
    /// Run against every shell that can source the generated script,
    /// because the fix is a redirect operator and its support is the
    /// whole question.
    #[test]
    fn the_heartbeat_write_survives_noclobber_in_every_shell() {
        let env = TempEnvironment::builder().build();
        let heartbeat = env.paths.hookup_heartbeat_path();
        env.fs.mkdir_all(&env.paths.probes_hookup_dir()).unwrap();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();
        let script_path = env.home.join("dodot-init.sh");
        env.fs.write_file(&script_path, script.as_bytes()).unwrap();

        for shell in ["/bin/sh", "/bin/bash", "/bin/zsh"] {
            if !Path::new(shell).exists() {
                continue;
            }
            // A heartbeat from an earlier activation is what a plain
            // `>` would refuse to overwrite.
            env.fs.write_file(&heartbeat, b"1 0.0.0\n").unwrap();
            let status = std::process::Command::new(shell)
                .arg("-c")
                .arg(format!("set -C; . '{}'", script_path.display()))
                .status()
                .expect("the shell runs");
            assert!(status.success(), "{shell}: sourcing the script failed");
            assert_eq!(
                env.fs.read_to_string(&heartbeat).unwrap().trim(),
                format!("{TEST_GEN} {}", activation::running_version()),
                "{shell}: noclobber must not freeze the heartbeat"
            );
        }
    }

    /// The hot-path budget: the version rides along inside the shape
    /// INS01 set — exports and one redirect — and nothing that costs a
    /// process. A `mkdir -p` or a `dodot` call here would be paid on
    /// every shell start, forever.
    #[test]
    fn evidence_costs_two_exports_and_one_redirect() {
        let env = TempEnvironment::builder().build();
        let script =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, TEST_GEN, None)
                .unwrap();

        let evidence: Vec<&str> = script
            .lines()
            .filter(|l| l.contains("DODOT_INIT") || l.contains("heartbeat"))
            .collect();
        assert_eq!(evidence.len(), 3, "evidence block: {evidence:?}");
        assert!(evidence[0]
            .trim_start()
            .starts_with("export DODOT_INIT_GEN="));
        assert!(evidence[1]
            .trim_start()
            .starts_with("export DODOT_INIT_VERSION="));
        assert!(evidence[2].trim_start().starts_with("echo "));
        for forbidden in ["mkdir", "dodot ", "date", "$(", "`"] {
            assert!(
                !evidence.iter().any(|l| l.contains(forbidden)),
                "evidence must not run `{forbidden}`: {evidence:?}"
            );
        }
    }

    /// `write_init_script` owns the heartbeat directory so the emitted
    /// redirect never has to create it, and stamps a real generation
    /// that reads back through the same parser `status` uses.
    #[test]
    fn write_init_script_stamps_generation_and_creates_heartbeat_dir() {
        let env = TempEnvironment::builder().build();

        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();

        assert!(
            env.fs.is_dir(&env.paths.probes_hookup_dir()),
            "heartbeat dir must exist before any shell writes the marker"
        );
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref())
            .expect("written script must carry a generation");
        assert!(gen > 1_700_000_000, "generation should be a unix ts: {gen}");
        let content = env.fs.read_to_string(&path).unwrap();
        assert!(content.contains(&format!("export DODOT_INIT_GEN={gen}")));
        // No shell has run yet, so there is no heartbeat — that
        // absence is the "never activated" signal.
        assert!(!env.fs.exists(&env.paths.hookup_heartbeat_path()));
    }

    /// Portability leg: the emitted script must parse under POSIX sh,
    /// bash, and zsh — the shells dodot generates init for.
    #[test]
    fn generated_script_parses_in_sh_bash_and_zsh() {
        let env = TempEnvironment::builder()
            .pack("vim")
            .file("aliases.sh", "alias vi=vim")
            .file("bin/tool", "#!/bin/sh")
            .done()
            .build();
        let ds = make_datastore(&env);
        ds.create_data_link("vim", "shell", &env.dotfiles_root.join("vim/aliases.sh"))
            .unwrap();
        ds.create_data_link("vim", "path", &env.dotfiles_root.join("vim/bin"))
            .unwrap();

        // The Homebrew arm matters most here: its block is the one
        // place the script carries zsh-only syntax (`fpath[1,0]=`), and
        // `sh -n` is what proves the guard keeps that syntax out of the
        // branch a POSIX shell parses.
        let brew = sample_brew_blocks();
        for profiling in [false, true] {
            for homebrew in [None, Some(&brew)] {
                let path =
                    write_init_script(env.fs.as_ref(), env.paths.as_ref(), profiling, homebrew)
                        .unwrap();
                for shell in ["sh", "bash", "zsh"] {
                    let out = std::process::Command::new(shell)
                        .arg("-n")
                        .arg(&path)
                        .output();
                    let Ok(out) = out else {
                        continue; // interpreter not installed on this host
                    };
                    assert!(
                        out.status.success(),
                        "{shell} -n rejected the generated script (profiling={profiling}, homebrew={}): {}",
                        homebrew.is_some(),
                        String::from_utf8_lossy(&out.stderr)
                    );
                }
            }
        }
    }

    /// The evidence is only worth anything if sourcing the script
    /// actually leaves it: run the real thing under `sh` and read
    /// every signal back — both exports and both heartbeat fields.
    #[test]
    fn sourcing_the_script_exports_the_stamp_and_writes_the_heartbeat() {
        let env = TempEnvironment::builder().build();
        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref()).unwrap();
        let version = activation::running_version();

        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(format!(
                ". '{}'; printf '%s %s' \"$DODOT_INIT_GEN\" \"$DODOT_INIT_VERSION\"",
                path.display()
            ))
            .env_remove(activation::INIT_GEN_ENV)
            .env_remove(activation::INIT_VERSION_ENV)
            .output()
            .expect("sh is required to run dodot's own init script");
        assert!(out.status.success(), "sourcing failed: {out:?}");
        assert_eq!(
            String::from_utf8_lossy(&out.stdout),
            format!("{gen} {version}"),
            "sourcing must export both the generation and the version"
        );

        let heartbeat = activation::read_heartbeat(env.fs.as_ref(), env.paths.as_ref())
            .expect("sourcing must leave a heartbeat");
        assert_eq!(heartbeat.generation, gen);
        assert_eq!(heartbeat.version.as_deref(), Some(version));
    }

    /// The one rule that tells "wired and deploying nothing" from
    /// "wired and working" — the footer's, and `down`'s, whole basis.
    #[test]
    fn an_empty_script_is_readable_as_having_no_contributions() {
        let env = TempEnvironment::builder().build();
        let empty =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, 100, None).unwrap();
        assert!(!script_has_contributions(&empty), "{empty}");

        let env = TempEnvironment::builder().build();
        let shell_dir = env.paths.handler_data_dir("vim", "shell");
        env.fs.mkdir_all(&shell_dir).unwrap();
        let target = env.home.join("aliases.sh");
        env.fs.write_file(&target, b"alias v=vim").unwrap();
        env.fs
            .symlink(&target, &shell_dir.join("aliases.sh"))
            .unwrap();
        let deployed =
            generate_init_script(env.fs.as_ref(), env.paths.as_ref(), false, 100, None).unwrap();
        assert!(script_has_contributions(&deployed), "{deployed}");
    }

    /// Parsing the guard is not the same as honouring it: source the
    /// script for real under `sh` and confirm the shell took the `sh`
    /// branch — brew's environment set, the zsh-only `fpath` line never
    /// executed (it would print a `command not found` to stderr) and no
    /// `FPATH` left behind.
    #[test]
    fn sourcing_under_sh_takes_the_sh_branch_of_the_homebrew_block() {
        let env = TempEnvironment::builder().build();
        let blocks = BrewBlocks {
            prefix: PathBuf::from("/fake/brew"),
            sh: "export HOMEBREW_PREFIX=\"/fake/brew\";\n".to_string(),
            zsh: "export HOMEBREW_PREFIX=\"/fake/brew\";\n\
                  fpath[1,0]=\"/fake/brew/share/zsh/site-functions\";\n\
                  export FPATH;\n"
                .to_string(),
        };
        let path =
            write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, Some(&blocks)).unwrap();

        let out = std::process::Command::new("sh")
            .arg("-c")
            .arg(format!(
                ". '{}'; printf '%s|%s' \"$HOMEBREW_PREFIX\" \"${{FPATH:-}}\"",
                path.display()
            ))
            .env_remove("HOMEBREW_PREFIX")
            .env_remove("FPATH")
            .output()
            .expect("sh is required to run dodot's own init script");

        assert!(out.status.success(), "sourcing failed: {out:?}");
        assert_eq!(String::from_utf8_lossy(&out.stdout), "/fake/brew|");
        assert!(
            out.stderr.is_empty(),
            "the sh branch must not touch zsh-only lines: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// Concurrency: many shells starting at once each truncate the
    /// same marker with the same static content, so the marker is
    /// always exactly one generation — never interleaved bytes.
    #[test]
    fn concurrent_sources_leave_an_intact_heartbeat() {
        let env = TempEnvironment::builder().build();
        let path = write_init_script(env.fs.as_ref(), env.paths.as_ref(), false, None).unwrap();
        let gen = activation::read_script_generation(env.fs.as_ref(), env.paths.as_ref()).unwrap();

        let children: Vec<_> = (0..8)
            .filter_map(|_| {
                std::process::Command::new("sh")
                    .arg("-c")
                    .arg(format!(". '{}'", path.display()))
                    .spawn()
                    .ok()
            })
            .collect();
        for mut child in children {
            let _ = child.wait();
        }

        assert_eq!(
            activation::read_heartbeat(env.fs.as_ref(), env.paths.as_ref()).map(|h| h.generation),
            Some(gen)
        );
    }

    #[test]
    fn shell_quoting_handles_paths_with_single_quotes() {
        // A path with a single quote in it must round-trip safely
        // through the printf args. Embedded `'` becomes `'\''`.
        assert_eq!(sh_quote("plain"), "'plain'");
        assert_eq!(sh_quote("it's"), "'it'\\''s'");
        assert_eq!(sh_quote(""), "''");
    }
}