tracevault-cli 0.29.4

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

/// Which Claude Code settings file to install hooks into.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ClaudeSettingsTarget {
    /// .claude/settings.json — typically committed/shared with the team.
    Shared,
    /// .claude/settings.local.json — personal, conventionally git-ignored.
    Local,
}

impl ClaudeSettingsTarget {
    pub fn filename(self) -> &'static str {
        match self {
            ClaudeSettingsTarget::Shared => "settings.json",
            ClaudeSettingsTarget::Local => "settings.local.json",
        }
    }

    pub fn gitignore_entry(self) -> &'static str {
        match self {
            ClaudeSettingsTarget::Shared => ".claude/settings.json",
            ClaudeSettingsTarget::Local => ".claude/settings.local.json",
        }
    }
}

/// Resolve which settings file to use. If the caller passed an explicit
/// choice, honor it. Otherwise prompt interactively when stdin is a TTY,
/// or fall back to Shared for non-interactive callers (CI, scripts, tests).
fn resolve_claude_target(
    explicit: Option<ClaudeSettingsTarget>,
) -> io::Result<ClaudeSettingsTarget> {
    if let Some(target) = explicit {
        return Ok(target);
    }
    if !io::stdin().is_terminal() {
        return Ok(ClaudeSettingsTarget::Shared);
    }

    let stdout = io::stdout();
    let mut stdout = stdout.lock();
    write!(
        stdout,
        "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
    )?;
    stdout.flush()?;

    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    let answer = line.trim().to_lowercase();
    Ok(match answer.as_str() {
        "l" | "local" => ClaudeSettingsTarget::Local,
        _ => ClaudeSettingsTarget::Shared,
    })
}

/// If `dir` is inside a LINKED git worktree (not the primary checkout), return
/// the primary worktree root. Returns `None` for the primary checkout or a
/// non-git directory.
///
/// A linked worktree has `git --git-dir` (e.g. `<primary>/.git/worktrees/<name>`)
/// distinct from `git --git-common-dir` (`<primary>/.git`); in the primary
/// checkout the two are equal. The primary root is the parent of the common dir.
fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--git-dir", "--git-common-dir"])
        .current_dir(dir)
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }
    let stdout = String::from_utf8(output.stdout).ok()?;
    let mut lines = stdout.lines();
    let git_dir = lines.next()?.trim();
    let git_common_dir = lines.next()?.trim();

    // git may return paths relative to `dir`; join (absolute args replace the
    // base) then canonicalize so the comparison is robust.
    let git_dir = dir.join(git_dir).canonicalize().ok()?;
    let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;

    if git_dir == git_common_dir {
        None // primary checkout
    } else {
        git_common_dir.parent().map(Path::to_path_buf)
    }
}

/// Validate init flag combinations against the selected agent. `--claude-settings`
/// selects between `.claude/settings.json` and `settings.local.json`, so it only
/// applies to the Claude Code agent — `--agent codex` always writes
/// `.codex/hooks.json`. Returns a human-readable error for an incompatible combo
/// so the CLI rejects it instead of silently ignoring the flag.
pub fn validate_init_flags(
    agent: crate::agent::Agent,
    claude_settings_set: bool,
) -> Result<(), String> {
    if matches!(
        agent,
        crate::agent::Agent::Codex
            | crate::agent::Agent::Gsd
            | crate::agent::Agent::OpenCode
            | crate::agent::Agent::Amp
    ) && claude_settings_set
    {
        return Err("--claude-settings only applies to --agent claude-code".to_string());
    }
    Ok(())
}

/// Set up TraceVault in `project_root`. An existing `.tracevault/config.toml`
/// is kept and only overridden where this run says so: `server_url` and
/// `user_context` (`None` = no flag given) replace the stored values; every
/// other field, and any field not overridden, survives (VIS-1046).
pub async fn init_in_directory(
    project_root: &Path,
    server_url: Option<&str>,
    claude_settings: Option<ClaudeSettingsTarget>,
    no_gitignore: bool,
    user_context: Option<UserContext>,
    agent: crate::agent::Agent,
) -> Result<String, io::Error> {
    // Check for git repository
    if !project_root.join(".git").exists() {
        return Err(io::Error::new(
            io::ErrorKind::NotFound,
            "Not a git repository. Run 'git init' first.",
        ));
    }

    // Refuse to initialize from a linked worktree: TraceVault's `.tracevault/`,
    // git hooks, and Claude settings all belong in the primary checkout (which
    // every worktree shares). Initializing here would create a stray
    // `.tracevault/` in this worktree instead. (In a linked worktree `.git` is a
    // file, so the check above passes — this guard is what catches it.)
    if let Some(primary) = linked_worktree_primary(project_root) {
        return Err(io::Error::new(
            io::ErrorKind::Unsupported,
            format!(
                "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
                 cd there and run it again — all worktrees share the primary's .tracevault/.",
                primary.display()
            ),
        ));
    }

    // Re-running `init` keeps the existing config (VIS-1046), so one that
    // cannot be parsed stops it here, before anything is written: replacing
    // it with defaults would throw away whatever the user had in it.
    let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
                 then run `tracevault init` again."
            ),
        )
    })?;

    // Credentials are resolved before anything is written. Without one the
    // repo is never registered, no `repo_id` is persisted, and the hooks
    // installed below would drop every event silently — so `init` refuses
    // instead of leaving a setup that looks installed but records nothing
    // (VIS-1045). A credential/URL mismatch aborts `init` too: it would
    // otherwise register the repo against whichever instance the env var
    // names while holding another instance's session.
    // `io::Error::other` because this function's error type is `io::Error`.
    let (resolved_url, resolved_credential) =
        crate::credentials::resolve_credentials_quiet(project_root)
            .map_err(|e| io::Error::other(e.to_string()))?;
    let effective_url = server_url.map(String::from).or(resolved_url.clone());
    if resolved_credential.is_none() {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            not_logged_in_message(effective_url.as_deref()),
        ));
    }

    // Migrate a legacy `default_project` NAME to `project_id` (VIS-1256)
    // before anything is written, so an unknown/ambiguous name stops `init`
    // with the config unchanged. The migrated value is persisted by the
    // `config.save` below.
    let mut existing_config = existing_config;
    if let (Some(cfg), Some(url)) = (existing_config.as_mut(), effective_url.as_deref()) {
        if cfg.default_project.is_some() {
            // The credential was resolved for `resolved_url`; the lookup must
            // not hand it to a different `--server-url`.
            match credential_url_mismatch(resolved_url.as_deref(), server_url) {
                Some(msg) => eprintln!(
                    "Warning: not migrating default_project: {msg}. Run `tracevault sync` \
                     once logged in to that server."
                ),
                None => {
                    let client = ApiClient::with_credential(url, resolved_credential.clone());
                    migrate_config_in_init(cfg, &client).await?;
                }
            }
        }
    }

    // Resolve the hook-file gitignore entry per agent. Claude has a
    // shared/local settings choice; Codex has a single .codex/hooks.json.
    let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
    {
        crate::agent::Agent::ClaudeCode => {
            let target = resolve_claude_target(claude_settings)?;
            (Some(target), target.gitignore_entry().to_string())
        }
        crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
        // GSD (pi) itself creates `.gsd/settings.json` in the repo when
        // `install_gsd_extension` shells out to `gsd install <dir> -l` (a
        // project-local package registration, analogous to Claude's
        // `.claude/settings.local.json`) — that's GSD's own local install
        // state, not something the user should commit.
        crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
        // The OpenCode plugin is installed project-locally as
        // `.opencode/plugins/tracevault.ts` — ignore the whole `.opencode/`
        // directory rather than just the plugin file, in case OpenCode
        // itself later writes other local state there.
        crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
        // Only the plugin's own directory: `.amp/` also holds the project's
        // Amp settings, which a team may well commit.
        crate::agent::Agent::Amp => (None, AMP_PLUGIN_GITIGNORE_ENTRY.to_string()),
    };

    // Create .tracevault/ directory
    let config_dir = TracevaultConfig::config_dir(project_root);
    fs::create_dir_all(&config_dir)?;
    fs::create_dir_all(config_dir.join("sessions"))?;
    fs::create_dir_all(config_dir.join("cache"))?;
    // Self-contained ignore for runtime artifacts, so this `.tracevault/` is
    // safe even if the root .gitignore doesn't cover it.
    TracevaultConfig::ensure_gitignore(&config_dir)?;

    // Keep tracevault's files local — update root .gitignore (unless opted out)
    if !no_gitignore {
        update_root_gitignore(project_root, &hook_gitignore_entry)?;
    }

    // Register repo on server if authenticated, server URL known, and git remote available
    let remote_url = git_remote_url(project_root);
    if remote_url.is_none() {
        eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
        eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
    }

    // Write config: the existing one with this run's flags applied, defaults
    // only for what it lacks (`user_context` on, unless a flag says
    // otherwise). Its `repo_id` stays in the file until registration below
    // binds another one, so a re-run that cannot reach the server keeps it.
    let mut config = existing_config.unwrap_or_default();
    if let Some(url) = server_url {
        config.server_url = Some(url.to_string());
    }
    config.user_context = user_context
        .or(config.user_context)
        .or(Some(UserContext::Toggle(true)));
    config.save(project_root)?;

    // The repo a previous `init` bound: re-running `init` keeps it if its
    // codebase still links it.
    let previous_repo_id = config
        .repo_id
        .as_deref()
        .and_then(|id| id.parse::<uuid::Uuid>().ok());

    // Install the selected agent's hooks.
    match agent {
        crate::agent::Agent::ClaudeCode => {
            // `claude_target` is `Some` for the Claude agent by construction above.
            let target =
                claude_target.expect("claude settings target is resolved for the Claude agent");
            install_claude_hooks(project_root, target)?;
        }
        crate::agent::Agent::Codex => {
            install_codex_hooks(project_root)?;
            println!("{}", codex_hook_trust_notice());
        }
        crate::agent::Agent::Gsd => {
            // GSD (pi) loads extensions from the user-global ~/.gsd/, not from
            // anything in the repo, so even the repo-local `init` path installs
            // there — the repo itself only needs the .tracevault/ binding + git
            // hooks set up above, which the extension shells out to `tracevault`
            // to use. `Some(project_root)` makes `install_gsd_extension` run
            // `gsd install -l` from this repo, registering the extension as a
            // project-local install.
            install_gsd_extension(Some(project_root))?;
        }
        crate::agent::Agent::OpenCode => {
            install_opencode_plugin(Some(project_root))?;
        }
        crate::agent::Agent::Amp => {
            let path = install_amp_plugin(Some(project_root))?;
            println!("Installed the TraceVault Amp plugin in {}", path.display());
            println!("{}", amp_headless_notice());
        }
    }

    // Install git hooks
    install_git_hook(project_root)?;
    install_post_commit_hook(project_root)?;

    // Detect AI tools in the project
    let detected = crate::hooks::detect_tools(project_root);
    for tool in &detected {
        println!("  Detected: {}", tool.name());
    }

    if let (Some(url), Some(remote)) = (effective_url, remote_url) {
        let client = ApiClient::with_credential(&url, resolved_credential);
        let repo_name = git_repo_name(project_root);
        // Captured before `remote` is moved into the request below, so the
        // codebase-resolve step doesn't need to shell out to git again.
        let origin_url = remote.clone();

        // A remote whose codebase already has a repo record binds to it:
        // registering would upsert by THIS checkout's directory name, i.e. a
        // second record for the same codebase whenever the names differ.
        match crate::resolution::plan_registration(
            &client,
            &origin_url,
            &repo_name,
            previous_repo_id,
        )
        .await
        {
            Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
                println!(
                    "Bound to existing repo {} (id: {repo_id}); not registering another record \
                     for this codebase",
                    codebase
                        .repos
                        .iter()
                        .find(|r| r.id == repo_id)
                        .map_or("", |r| r.name.as_str())
                );
                println!(
                    "{}",
                    crate::resolution::codebase_line(
                        codebase.remote.name.as_deref(),
                        &codebase.remote.normalized_url,
                        &codebase.remote.clone_status
                    )
                );
                persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
            }
            Ok(RegistrationPlan::Ambiguous(codebase)) => {
                eprintln!(
                    "Warning: codebase {} already has {} repo records ({}) and none is named \
                     '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
                     .tracevault/config.toml to the one this checkout belongs to.",
                    codebase.display_name(),
                    codebase.repos.len(),
                    codebase.repo_list()
                );
            }
            Ok(RegistrationPlan::Register) => {
                register_new_repo(&client, project_root, repo_name, origin_url).await;
            }
            // Without knowing what the server already has, registering could
            // create the duplicate this check exists to prevent.
            Err(e) => {
                eprintln!(
                    "Warning: could not check the server for an existing repo of this remote \
                     ({e}); not registering. Run `tracevault init` again once the server is \
                     reachable."
                );
            }
        }
    }

    Ok(hook_gitignore_entry)
}

/// `init`'s step of the `default_project` → `project_id` migration
/// (VIS-1256), on the in-memory config the caller then saves. An unknown or
/// ambiguous name is an error (nothing has been written yet); an unreachable
/// server is a warning and leaves the legacy key for a later `init`/`sync`.
async fn migrate_config_in_init(
    config: &mut TracevaultConfig,
    client: &ApiClient,
) -> Result<(), io::Error> {
    use crate::commands::migrate::{migrate_default_project, migration_report, ResolveNameError};
    match migrate_default_project(config, client).await {
        Ok(migration) => {
            if let Some(line) = migration_report(&migration) {
                println!("{line}");
            }
            Ok(())
        }
        Err(ResolveNameError::Unreachable(e)) => {
            eprintln!(
                "Warning: could not migrate default_project (could not list projects: {e}); \
                 it stays unused for capture until `tracevault sync` succeeds."
            );
            Ok(())
        }
        Err(e @ ResolveNameError::Name(_)) => {
            Err(io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))
        }
    }
}

/// `init --global`'s step of the `default_project` migration (VIS-1256: it
/// runs in `init` in any mode). A global install has no project config of its
/// own, so it migrates the config the hooks would read from the current
/// directory (`resolve_project_root`), if that config still carries a legacy
/// `default_project`. Runs before anything is installed: an unknown or
/// ambiguous name is an error; no login or an unreachable server is a warning
/// (the legacy key stays for a later `sync`).
pub async fn migrate_cwd_config(cwd: &Path) -> Result<(), io::Error> {
    let root = crate::paths::resolve_project_root(cwd).root;
    let Ok(Some(mut config)) = TracevaultConfig::try_load(&root) else {
        return Ok(());
    };
    if config.default_project.is_none() {
        return Ok(());
    }
    let Ok((Some(url), credential @ Some(_))) =
        crate::credentials::resolve_credentials_quiet(&root)
    else {
        eprintln!(
            "Warning: {} has a legacy default_project that needs a login to migrate; run \
             `tracevault sync` there once logged in.",
            TracevaultConfig::config_path(&root).display()
        );
        return Ok(());
    };
    let client = ApiClient::with_credential(&url, credential);
    migrate_config_in_init(&mut config, &client).await?;
    if config.default_project.is_none() {
        config.save(&root)?;
    }
    Ok(())
}

/// `Some(reason)` when an explicit `--server-url` names a different
/// TraceVault instance than the one the credential was resolved for: a
/// lookup there would hand that instance's token or key to another host.
/// `None` when there is no explicit URL, no resolved one, or both agree —
/// and when the key comes from `TRACEVAULT_API_KEY`: like
/// `credentials::resolve_credentials`, a key named on this invocation is a
/// deliberate pairing with the URL named next to it, not a stored login.
fn credential_url_mismatch(resolved: Option<&str>, explicit: Option<&str>) -> Option<String> {
    let env_key = std::env::var("TRACEVAULT_API_KEY")
        .ok()
        .is_some_and(|k| !k.trim().is_empty());
    if env_key {
        return None;
    }
    let (resolved, explicit) = (resolved?, explicit?);
    (!crate::credentials::same_server(resolved, explicit)).then(|| {
        format!(
            "the credential in use is for {resolved}, not --server-url {explicit}; log in \
             there first (`tracevault login --server-url {explicit}`) or omit --server-url"
        )
    })
}

/// What `init --workspace` bound.
#[derive(Debug)]
pub struct WorkspaceInit {
    pub project_id: uuid::Uuid,
    pub project_name: String,
    /// The `.tracevault/config.toml` written.
    pub config_path: PathBuf,
}

/// `tracevault init --workspace --project <name>` (VIS-1256): bind every
/// session started under `dir` to one project, with no per-session step.
///
/// Meant for an umbrella directory that is not itself a repo (e.g. a folder
/// of checkouts), so it does not require git. It creates `dir/.tracevault/`
/// if missing — the stream hook's `resolve_project_root` ancestor walk then
/// finds it from any non-git directory below — resolves `project_name` to its
/// id ONCE against the server, and writes `project_id` + `project_name`. The
/// hook reads that id locally: no network call per event. No `repo_id` is
/// written; an existing config's other keys are kept, and a legacy
/// `default_project` is dropped (the new `project_id` supersedes it).
///
/// Installs no hooks: an umbrella directory is covered by a global install
/// (`tracevault init --global`). Refused inside a git repo below its root:
/// the hook would read the repo root's config, never this one.
pub async fn init_workspace(
    dir: &Path,
    project_name: &str,
    server_url: Option<&str>,
) -> Result<WorkspaceInit, io::Error> {
    let resolved = crate::paths::resolve_project_root(dir);
    if resolved.source == crate::paths::ProjectRootSource::Git {
        let same = match (resolved.root.canonicalize(), dir.canonicalize()) {
            (Ok(a), Ok(b)) => a == b,
            _ => resolved.root == dir,
        };
        if !same {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                format!(
                    "{} is inside the git repo {}; sessions here read that repo's \
                     .tracevault/config.toml, so a workspace binding here would never be used. \
                     Run `tracevault init --workspace` from the repo root or from a directory \
                     that is not inside a repo.",
                    dir.display(),
                    resolved.root.display()
                ),
            ));
        }
    }

    let existing = TracevaultConfig::try_load(dir).map_err(|e| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!(
                "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
                 then run `tracevault init --workspace` again."
            ),
        )
    })?;

    let (resolved_url, credential) = crate::credentials::resolve_credentials_quiet(dir)
        .map_err(|e| io::Error::other(e.to_string()))?;
    // The credential was resolved for `resolved_url`: never hand it to a
    // different `--server-url`.
    if let Some(msg) = credential_url_mismatch(resolved_url.as_deref(), server_url) {
        return Err(io::Error::new(io::ErrorKind::PermissionDenied, msg));
    }
    let url = server_url.map(String::from).or(resolved_url);
    let (Some(url), Some(_)) = (url.as_deref(), credential.as_ref()) else {
        return Err(io::Error::new(
            io::ErrorKind::PermissionDenied,
            format!(
                "Not logged in. `init --workspace` resolves the project name on the server, \
                 so nothing was written.\nLog in, then run it again:\n\n    \
                 tracevault login --server-url {}\n    \
                 tracevault init --workspace --project {project_name}",
                url.as_deref().unwrap_or("<URL>")
            ),
        ));
    };
    let client = ApiClient::with_credential(url, credential);
    let project = crate::commands::migrate::resolve_project_by_name(&client, project_name)
        .await
        .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;

    let config_dir = TracevaultConfig::config_dir(dir);
    fs::create_dir_all(&config_dir)?;
    TracevaultConfig::ensure_gitignore(&config_dir)?;

    let mut config = existing.unwrap_or_default();
    if let Some(url) = server_url {
        config.server_url = Some(url.to_string());
    }
    config.project_id = Some(project.id.to_string());
    config.project_name = Some(project.name.clone());
    config.default_project = None;
    config.save(dir)?;

    Ok(WorkspaceInit {
        project_id: project.id,
        project_name: project.name,
        config_path: TracevaultConfig::config_path(dir),
    })
}

/// The error `init` fails with when no credential resolves: what went wrong,
/// that nothing was installed, and the exact commands that fix it. `url` is
/// the server URL already known (`--server-url`, `TRACEVAULT_SERVER_URL` or
/// the project config), filled into the `login` command when present.
pub fn not_logged_in_message(url: Option<&str>) -> String {
    let url = url.unwrap_or("<URL>");
    format!(
        "Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
         would record nothing, so nothing was installed.\n\
         Log in, then run init again:\n\
         \n    tracevault login --server-url {url}\n    tracevault init\n\n\
         (In CI, set TRACEVAULT_API_KEY instead of logging in.)"
    )
}

/// Record the repo this checkout binds — and its codebase, display-only — in
/// an existing `.tracevault/config.toml`, returning whether it was written.
///
/// Never creates the config: a checkout without one is in workspace mode (a
/// global install binds sessions with `repo switch`), and writing one would
/// silently pin it to bound mode. A failed write never fails the caller.
pub(crate) fn persist_repo_binding(
    project_root: &Path,
    repo_id: uuid::Uuid,
    codebase: Option<&crate::api_client::ResolveRemoteResponse>,
) -> bool {
    let Some(mut cfg) = TracevaultConfig::load(project_root) else {
        return false;
    };
    cfg.repo_id = Some(repo_id.to_string());
    if let Some(remote) = codebase {
        cfg.remote_id = Some(remote.remote_id.to_string());
        cfg.codebase_name = remote.name.clone();
    }
    cfg.save(project_root).is_ok()
}

/// Register a repo for a remote the server has no live repo for, and persist
/// its id (plus the codebase, display-only) to config.toml. Failure is a
/// warning, never a failed `init`.
async fn register_new_repo(
    client: &ApiClient,
    project_root: &Path,
    repo_name: String,
    origin_url: String,
) {
    match client
        .register_repo(crate::api_client::RegisterRepoRequest {
            repo_name,
            github_url: Some(origin_url.clone()),
        })
        .await
    {
        Ok(resp) => {
            println!("Repo registered on server (id: {})", resp.repo_id);
            // Save repo_id to config
            if let Some(mut cfg) = TracevaultConfig::load(project_root) {
                cfg.repo_id = Some(resp.repo_id.to_string());
                // Best-effort: resolve the codebase (deduped by normalized
                // remote URL) and surface it to the user. Must never fail
                // init — `repo_id` above stays authoritative for ingest;
                // `remote_id`/`codebase_name` here are recorded for
                // display only.
                if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
                    println!(
                        "{}",
                        crate::resolution::codebase_line(
                            remote.name.as_deref(),
                            &remote.normalized_url,
                            &remote.clone_status
                        )
                    );
                    cfg.remote_id = Some(remote.remote_id.to_string());
                    cfg.codebase_name = remote.name.clone();
                }
                let _ = cfg.save(project_root);
            }
        }
        Err(e) => {
            eprintln!("{}", registration_failure_message(e.as_ref()));
        }
    }
}

/// The warning line for a failed repo registration during `init`. A 403 means
/// the token is valid but not authorized to register this repo — distinct
/// from a network/server fault, so it gets its own actionable wording; a 404
/// means this server build doesn't recognize the registration route at all,
/// which most plausibly means the CLI is newer than the server (a CLI/server
/// version mismatch). Registration failure is non-fatal to `init` either
/// way (a warning, not an aborted init — the repo can be registered later
/// via `tracevault sync`).
///
/// Matches on the exact status-prefix shape `ApiClient::register_repo`
/// produces (`"Server returned {status} ..."`, from its `authed_send_json`
/// call) rather than a bare `.contains("403")`/`.contains("404")` — a
/// response body that happens to contain that digit string (e.g. a proxy
/// error page) must not be misclassified.
fn registration_failure_message(err: &dyn std::error::Error) -> String {
    let msg = err.to_string();
    if msg.starts_with("Server returned 403 ") {
        "Warning: you are not authorized to register this repo.".to_string()
    } else if msg.starts_with("Server returned 404 ") {
        "Warning: could not register repo on server (404) — this endpoint may not exist on \
         this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
         once the server is upgraded."
            .to_string()
    } else {
        format!("Warning: could not register repo on server: {err}")
    }
}

fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
    let path = project_root.join(".gitignore");
    let existing = if path.exists() {
        fs::read_to_string(&path)?
    } else {
        String::new()
    };

    // Only ignore what `init` actually creates or modifies: the `.tracevault/`
    // directory and the single settings file we wrote hooks into. The
    // other settings file is left untouched, so we don't add it here. An
    // empty `settings_entry` means the agent writes nothing into the repo at
    // all — skip it rather than appending a blank line.
    let needed: Vec<&str> = [".tracevault/", settings_entry]
        .iter()
        .copied()
        .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
        .collect();

    if needed.is_empty() {
        return Ok(());
    }

    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    content.push_str("\n# TraceVault — local only, do not commit\n");
    for entry in needed {
        content.push_str(entry);
        content.push('\n');
    }

    fs::write(path, content)
}

const HOOK_MARKER: &str = "# tracevault:enforce";
const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";

fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
    let hooks_dir = project_root.join(".git/hooks");
    fs::create_dir_all(&hooks_dir)?;

    let hook_path = hooks_dir.join("pre-push");
    // Capture git's pre-push ref list once, then feed it to `check` explicitly
    // rather than relying on it inheriting stdin from the hook process. `sync`
    // never reads stdin, so today it reaches `check` anyway — this only drops
    // the dependency on that inheritance for hooks installed from here on;
    // already-installed hooks keep working without re-running `tracevault
    // init`.
    let tracevault_block = format!(
        "{HOOK_MARKER}\n\
         # Capture git's pre-push ref list once; `check` uses it to determine\n\
         # which files are being pushed.\n\
         tracevault_prepush_stdin=$(cat)\n\
         tracevault sync 2>/dev/null || true\n\
         printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
    );

    if hook_path.exists() {
        let existing = fs::read_to_string(&hook_path)?;

        // Already has new-style hook
        if existing.contains(HOOK_MARKER) {
            return Ok(());
        }

        // Replace old-style hook block if present
        if existing.contains(OLD_HOOK_MARKER) {
            let mut new_content = String::new();
            let mut skip = false;
            for line in existing.lines() {
                if line.contains(OLD_HOOK_MARKER) {
                    skip = true;
                    continue;
                }
                if skip {
                    // Skip old tracevault lines (they start with "tracevault " or are empty continuations)
                    if line.starts_with("tracevault ") {
                        continue;
                    }
                    skip = false;
                }
                new_content.push_str(line);
                new_content.push('\n');
            }
            if !new_content.ends_with('\n') {
                new_content.push('\n');
            }
            new_content.push_str(&tracevault_block);
            fs::write(&hook_path, new_content)?;
        } else {
            // Append to existing hook
            let mut content = existing;
            if !content.ends_with('\n') {
                content.push('\n');
            }
            content.push_str(&tracevault_block);
            fs::write(&hook_path, content)?;
        }
    } else {
        let content = format!("#!/bin/sh\n{tracevault_block}");
        fs::write(&hook_path, content)?;
    }

    // Make executable
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&hook_path, perms)?;
    }

    Ok(())
}

const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";

fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
    let hooks_dir = project_root.join(".git/hooks");
    fs::create_dir_all(&hooks_dir)?;

    let hook_path = hooks_dir.join("post-commit");
    let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");

    if hook_path.exists() {
        let existing = fs::read_to_string(&hook_path)?;

        if existing.contains(POST_COMMIT_MARKER) {
            return Ok(());
        }

        let mut content = existing;
        if !content.ends_with('\n') {
            content.push('\n');
        }
        content.push_str(&tracevault_block);
        fs::write(&hook_path, content)?;
    } else {
        let content = format!("#!/bin/sh\n{tracevault_block}");
        fs::write(&hook_path, content)?;
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let mut perms = fs::metadata(&hook_path)?.permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&hook_path, perms)?;
    }

    Ok(())
}

fn install_claude_hooks(
    project_root: &Path,
    target: ClaudeSettingsTarget,
) -> Result<(), io::Error> {
    let claude_dir = project_root.join(".claude");
    fs::create_dir_all(&claude_dir)?;
    merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
}

pub fn tracevault_hooks() -> serde_json::Value {
    serde_json::json!({
        "PreToolUse": [{
            "matcher": "Write|Edit|Bash",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event pre-tool-use",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming pre-tool event"
            }]
        }],
        "PostToolUse": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event post-tool-use",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming post-tool event"
            }]
        }],
        "Notification": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event notification",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming notification"
            }]
        }],
        "Stop": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event stop",
                "timeout": 10,
                "statusMessage": "TraceVault: finalizing session"
            }]
        }],
        // Claude Code writes its `cost-state` line at exit, after `Stop`; this
        // sends it (VIS-1108).
        "SessionEnd": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event session-end",
                "timeout": 10,
                "statusMessage": "TraceVault: sending session cost"
            }]
        }],
        // Every hook above also sends new subagent transcript lines; this one
        // catches a background subagent that finishes after the last `Stop`.
        "SubagentStop": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault stream --event subagent-stop",
                "timeout": 10,
                "statusMessage": "TraceVault: streaming subagent transcript"
            }]
        }],
        "SessionStart": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault session-start",
                "timeout": 10,
                "statusMessage": "TraceVault: session start"
            }]
        }],
        "UserPromptSubmit": [{
            "matcher": "",
            "hooks": [{
                "type": "command",
                "command": "tracevault user-prompt",
                "timeout": 10,
                "statusMessage": "TraceVault: policy reinforcement"
            }]
        }]
    })
}

/// Codex CLI hook set, mirroring `tracevault_hooks()` but with Codex commands.
/// What to tell the user after Codex hooks are installed.
///
/// Writing `hooks.json` is only half the setup: Codex >= 0.153 gates hooks
/// behind persisted *hook trust*, and a non-interactive `codex exec` skips
/// untrusted hooks without printing anything — so capture looks installed and
/// silently produces no sessions until trust is granted once. Observed on
/// Codex 0.153.4, where neither `codex doctor` nor `codex features` reports
/// the trust state, which is why the CLI has to say it here.
pub fn codex_hook_trust_notice() -> &'static str {
    "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
     silently and no session is captured. Run `codex` once interactively in a repo and \
     approve the hook-trust prompt; unattended runs (CI) can pass \
     `--dangerously-bypass-hook-trust` instead."
}

/// Capture hooks carry `--agent codex`; the injection hooks (session-start /
/// user-prompt) are agent-agnostic. Matchers are `""` (all tools).
///
/// We intentionally do NOT register a `PreToolUse` hook for Codex. Unlike Claude
/// Code — whose `PreToolUse` is scoped to `Write|Edit|Bash` — the CLI does no
/// Codex-specific pre-tool work, and `PostToolUse` + `Stop` already stream the
/// (incremental, offset-tracked) rollout. A pre-tool hook on every tool call
/// would only double the per-call streaming for no added capture. No
/// `Notification` event either (Codex has none).
pub fn codex_hooks() -> serde_json::Value {
    serde_json::json!({
        "SessionStart": [{
            "matcher": "",
            "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
        }],
        "UserPromptSubmit": [{
            "matcher": "",
            "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
        }],
        "PostToolUse": [{
            "matcher": "",
            "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
        }],
        "Stop": [{
            "matcher": "",
            "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
        }]
    })
}

/// Embedded pi/GSD extension source (bundled at build time — see
/// `assets/gsd-extension/{index.ts,package.json,extension-manifest.json}`,
/// the checked-in source this installer writes verbatim).
const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
const GSD_EXT_MANIFEST_JSON: &str =
    include_str!("../../assets/gsd-extension/extension-manifest.json");

/// Path of the stable directory (under the user's config dir) that holds the
/// TraceVault GSD extension source, shared by `install_gsd_extension` so the
/// write and the `gsd install` invocation always agree on where it lives.
fn gsd_extension_source_dir() -> io::Result<PathBuf> {
    let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
    let config_dir = config_dir
        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
    Ok(config_dir.join("tracevault").join("gsd-extension"))
}

/// Install the TraceVault pi/GSD extension and register it with GSD so it
/// actually loads.
///
/// GSD (pi) only loads an extension that (a) has an `extension-manifest.json`
/// in its directory *and* (b) was registered via `gsd install <dir>` — a
/// hand-written `registry.json` entry is inert (`gsd list` won't show it).
/// So this writes the extension source (`index.ts`, `package.json`,
/// `extension-manifest.json`) to a stable, idempotent source directory
/// (`<config_dir>/tracevault/gsd-extension`), best-effort cleans up any
/// stale/inert registration left behind by an older version of this
/// installer, and then shells out to `gsd install` to register + load it.
///
/// `project_root` selects how `gsd install` is invoked:
/// - `Some(repo)`: project-local install (`gsd install <dir> -l`, run with
///   `repo` as the working directory) — used by `tracevault init`.
/// - `None`: global install (`gsd install <dir>`, applies to all GSD
///   sessions on this machine) — used by `tracevault init --global`.
///
/// If the `gsd` binary can't be found or the install command fails, this
/// does NOT fail `init`: it prints a warning explaining how to finish the
/// registration by hand and returns `Ok(())`. The extension source is still
/// written either way, so the user (or a later retry) has something to
/// register.
pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
    let home =
        dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
    let gsd_home = home.join(".gsd");

    let source_dir = gsd_extension_source_dir()?;
    fs::create_dir_all(&source_dir)?;
    fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
    fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
    fs::write(
        source_dir.join("extension-manifest.json"),
        GSD_EXT_MANIFEST_JSON,
    )?;

    // Best-effort cleanup of the OLD, broken install (hand-written registry
    // entries that GSD never actually loaded). Never blocks the rest of the
    // install — see `cleanup_stale_gsd_registration`.
    if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
        eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
    }

    // Register + load the extension via the `gsd` CLI. `gsd install` is what
    // actually makes GSD load the extension; our own registry.json edits
    // never did.
    let local_flag = project_root.is_some();
    let mut cmd = std::process::Command::new("gsd");
    cmd.arg("install").arg(&source_dir);
    if let Some(root) = project_root {
        cmd.arg("-l");
        cmd.current_dir(root);
    }

    let retry_hint = format!(
        "gsd install {}{}",
        source_dir.display(),
        if local_flag { " -l" } else { "" }
    );

    match cmd.output() {
        Ok(output) if output.status.success() => {
            println!(
                "TraceVault: installed and registered the GSD extension ({}).",
                source_dir.display()
            );
        }
        Ok(output) => {
            eprintln!(
                "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
                source_dir.display(),
                String::from_utf8_lossy(&output.stderr),
            );
        }
        Err(e) => {
            eprintln!(
                "TraceVault: installed the GSD extension source to {}, but could not run `gsd install` ({e}). Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
                source_dir.display(),
            );
        }
    }

    Ok(())
}

/// TraceVault OpenCode plugin source, embedded from the checked-in assets
/// this installer writes verbatim (mirrors the GSD extension embeds above).
const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");

/// Install the TraceVault OpenCode plugin. `project_root = Some(dir)` installs
/// project-local at `<dir>/.opencode/plugins/tracevault.ts`; `None` installs
/// global at `~/.config/opencode/plugins/tracevault.ts` (using the same
/// config-dir resolution as `gsd_extension_source_dir` above). OpenCode
/// auto-loads `*.ts` modules from that directory — no separate "install"
/// command. Returns an error on failure (unresolvable config dir, or a write
/// error) so the caller aborts init loudly, consistent with the Codex/GSD arms
/// — a swallowed failure would make `init` report success while no plugin was
/// written, silently disabling capture.
///
/// A FLAT `.ts` file is used rather than a `tracevault/` package directory: a
/// package subdir (index.ts + package.json) makes OpenCode try to resolve it as
/// an npm package and stalls at startup offline, whereas a flat module loads
/// directly (both confirmed during the capture spike). The plugin only imports
/// the `node:child_process` builtin, so it needs no package manifest.
pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
    let plugins_dir = match project_root {
        Some(root) => root.join(".opencode").join("plugins"),
        None => {
            let config_dir =
                dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
            config_dir
                .ok_or_else(|| {
                    io::Error::new(
                        io::ErrorKind::NotFound,
                        "could not determine the config directory for the OpenCode plugin install",
                    )
                })?
                .join("opencode")
                .join("plugins")
        }
    };

    write_opencode_plugin_files(&plugins_dir)
}

fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
    fs::create_dir_all(plugins_dir)?;
    fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
    Ok(())
}

/// TraceVault Amp plugin source, embedded from the checked-in assets and
/// written verbatim by `install_amp_plugin`.
pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");

/// Root `.gitignore` entry for the repo-local Amp plugin.
const AMP_PLUGIN_GITIGNORE_ENTRY: &str = ".amp/plugins/tracevault/";

/// Install the TraceVault Amp plugin as `tracevault/index.ts` in an Amp
/// plugins directory: `<project_root>/.amp/plugins/` for a repo, or with
/// `None` the user-level one Amp loads for every session,
/// `$XDG_CONFIG_HOME/amp/plugins/` or `~/.config/amp/plugins/`. Amp uses
/// that XDG path on every platform, so this does not use `dirs::config_dir`
/// (which is `~/Library/Application Support` on macOS). Returns the path
/// written. Fails loudly, like the other agents' installers: a swallowed
/// error would report success with no plugin in place.
pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
    let plugins_dir = match project_root {
        Some(root) => root.join(".amp").join("plugins"),
        None => amp_user_config_dir()
            .ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::NotFound,
                    "could not determine the config directory for the Amp plugin install",
                )
            })?
            .join("plugins"),
    };
    let plugin_dir = plugins_dir.join("tracevault");
    fs::create_dir_all(&plugin_dir)?;
    let path = plugin_dir.join("index.ts");
    fs::write(&path, AMP_PLUGIN_INDEX)?;
    Ok(path)
}

/// Amp's user config directory: `$XDG_CONFIG_HOME/amp` when that is set to
/// an absolute path (the XDG spec says to ignore a relative one), otherwise
/// `~/.config/amp`.
fn amp_user_config_dir() -> Option<PathBuf> {
    let xdg = std::env::var_os("XDG_CONFIG_HOME")
        .map(PathBuf::from)
        .filter(|p| p.is_absolute());
    xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
        .map(|c| c.join("amp"))
}

/// What `init --agent amp` prints after installing the plugin: headless runs
/// need a flag, or Amp may start the turn before the plugin is ready and
/// skip its `agent.start` / `agent.end` hooks; and the injected policies are
/// stored in the thread, where whoever can read the thread sees them.
pub fn amp_headless_notice() -> &'static str {
    "Amp loads the plugin in interactive sessions. For headless runs use \
`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
path), so allow what it needs up front.\n\
The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
ampcode.com, or exports it, can read them."
}

/// Best-effort cleanup of the extension registration left behind by an OLDER
/// version of this installer: the `tracevault-tracker` directory (an earlier,
/// incorrect Codex-clone `hooks.json` shim that impersonated this extension
/// under the wrong name) and any registry entries for `tracevault-tracker` or
/// `tracevault` — both are inert now that `gsd install` manages registration.
///
/// If `registry.json` is missing, there's nothing to clean up. If it exists
/// but fails to parse, or its shape is not a valid registry (root not an
/// object, or a non-object `entries` field), it is structurally corrupt: we
/// leave it byte-for-byte untouched (skip cleanup) rather than risk
/// destroying every other extension the user has registered.
pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
    let ext_root = gsd_home.join("extensions");
    let reg_path = ext_root.join("registry.json");

    // Validate the registry BEFORE mutating anything under ~/.gsd. If it exists
    // but is structurally corrupt (unparseable, or a non-object root/`entries`),
    // leave the extensions directory entirely untouched — not even the stale
    // tracker dir is removed — so a corrupt registry yields zero mutation.
    let reg: Option<serde_json::Value> = if reg_path.exists() {
        let content = fs::read_to_string(&reg_path)?;
        let parsed: serde_json::Value = match serde_json::from_str(&content) {
            Ok(v) => v,
            Err(_) => return Ok(()), // corrupt: touch nothing
        };
        let corrupt = match parsed.as_object() {
            None => true,
            Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
        };
        if corrupt {
            return Ok(()); // structurally corrupt: touch nothing
        }
        Some(parsed)
    } else {
        None
    };

    // Registry is valid or absent — now safe to remove the superseded tracker shim.
    let stale = ext_root.join("tracevault-tracker");
    if stale.exists() {
        fs::remove_dir_all(&stale)?;
    }

    // Drop stale registry entries (only when a valid registry exists).
    if let Some(mut reg) = reg {
        if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
            let removed_tracker = entries.remove("tracevault-tracker").is_some();
            let removed_inert = entries.remove("tracevault").is_some();
            if removed_tracker || removed_inert {
                // Atomic write (temp file + rename), pretty-printed.
                let tmp = reg_path.with_extension("json.tmp");
                fs::write(&tmp, serde_json::to_string_pretty(&reg)?)?;
                fs::rename(&tmp, &reg_path)?;
            }
        }
    }
    Ok(())
}

/// Bring the TraceVault hooks in `hooks_path` to `ours` via [`merge_hooks`]
/// (foreign hooks and other keys are kept), written through
/// [`update_json_file`]. The one
/// install path for every hook file — per-repo Claude (`settings.json` or
/// `settings.local.json`), global Claude and Codex (`hooks.json`), whose roots
/// are the object `merge_hooks` mutates (`root["hooks"]`). A file that is
/// already current is not rewritten, so its formatting survives a re-run. On a
/// merge error (malformed existing file) it returns before writing, so the
/// target is never clobbered and no temp file is left behind.
fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
    update_json_file(hooks_path, "its hooks", |root| {
        merge_hooks(root, ours, hooks_path)
    })
}

/// Read `path` as JSON (or `{}` if absent), apply `mutate`, and write the
/// result back atomically (sibling temp file + rename), keeping the file's
/// mode, a symlink's target, and — when `mutate` changed nothing — the file
/// untouched. A missing file that `mutate` leaves as `{}` is not created. On a
/// `mutate` error (malformed existing file) it returns before writing, so the
/// target is never clobbered and no temp file is left behind. `what` names
/// what is being updated, for the error when the file keeps changing.
pub(crate) fn update_json_file(
    path: &Path,
    what: &str,
    mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
) -> io::Result<()> {
    // Defense-in-depth against path traversal: callers pass a constant filename
    // joined to a home/cwd base (global callers additionally go through
    // `safe_join`), so a `..` component should never appear — reject it outright
    // rather than read/write through it.
    if path
        .components()
        .any(|c| c == std::path::Component::ParentDir)
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("refusing to use path with '..': {}", path.display()),
        ));
    }
    // A settings file symlinked to a centrally managed config is updated at its
    // target, so the link survives (renaming over it would replace it with a
    // regular file). A dangling link fails here instead of being overwritten.
    let target = match fs::symlink_metadata(path) {
        Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
        _ => path.to_path_buf(),
    };
    // Another writer (a second `init`, Claude Code saving a permission) may
    // change the file between our read and our rename; publishing then would
    // drop its change. So the file is re-read just before the rename and the
    // merge redone if it moved. This narrows the window, it cannot close it:
    // Claude Code takes no lock we could share.
    for _ in 0..3 {
        let existing = read_existing(&target)?;
        let mut root: serde_json::Value = match &existing {
            Some((_, content)) => serde_json::from_str(content).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Failed to parse {}: {e}", path.display()),
                )
            })?,
            None => serde_json::json!({}),
        };

        let before = existing.is_some().then(|| root.to_string());
        mutate(&mut root)?;
        if before.as_deref() == Some(root.to_string().as_str())
            || (existing.is_none() && root == serde_json::json!({}))
        {
            return Ok(());
        }

        let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
            io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
        })?;
        let tmp = unique_temp_sibling(&target);
        let published = write_owner_only(&tmp, formatted.as_bytes())
            .and_then(|()| {
                // Keep the mode the user gave the file (a 0600 settings.local.json
                // may carry credentials in `env`); a new file stays owner-only.
                match &existing {
                    Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
                    None => Ok(()),
                }
            })
            .and_then(|()| {
                let unchanged = read_existing(&target)?.map(|(_, c)| c)
                    == existing.as_ref().map(|(_, c)| c.clone());
                if unchanged {
                    fs::rename(&tmp, &target).map(|()| true)
                } else {
                    Ok(false)
                }
            });
        match published {
            Ok(true) => return Ok(()),
            Ok(false) => {
                let _ = fs::remove_file(&tmp);
            }
            Err(e) => {
                let _ = fs::remove_file(&tmp);
                return Err(e);
            }
        }
    }
    Err(io::Error::other(format!(
        "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
        path.display()
    )))
}

/// The permissions and contents of `path`, or `None` when it does not exist.
fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
    let permissions = match fs::metadata(path) {
        Ok(meta) => meta.permissions(),
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    Ok(Some((permissions, fs::read_to_string(path)?)))
}

/// A temp path next to `target` that no other install — in this process or a
/// concurrent one — uses, so two `init`s never write or publish each other's
/// half-written file.
fn unique_temp_sibling(target: &Path) -> PathBuf {
    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos())
        .unwrap_or_default();
    let mut name = target.file_name().unwrap_or_default().to_os_string();
    name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
    target.with_file_name(name)
}

/// Create `path` (which must not exist), readable only by its owner on Unix,
/// and write `contents` — so the temp copy of a settings file never exposes
/// it while being written.
fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
    let mut options = fs::OpenOptions::new();
    options.write(true).create_new(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    options.open(path)?.write_all(contents)
}

/// Deep-merge the Codex hook set into `<project_root>/.codex/hooks.json`,
/// creating it if absent (idempotent, never clobbers existing hooks/keys,
/// atomic write). Repo-local counterpart of [`install_global_codex_hooks`].
pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
    let codex_dir = project_root.join(".codex");
    fs::create_dir_all(&codex_dir)?;
    merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
}

/// Install TraceVault's Codex hooks into `<codex_dir>/hooks.json` and append a
/// workspace-mode instruction block to `<codex_dir>/AGENTS.md` (idempotent,
/// atomic), mirroring the Claude global install's `settings.json` + `CLAUDE.md`.
/// Intended for `tracevault init --global --agent codex`. Codex reads `AGENTS.md`
/// for agent instructions, so the workspace-mode block reaches detached Codex
/// sessions the same way the `CLAUDE.md` block reaches Claude ones.
pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
    fs::create_dir_all(codex_dir)?;
    // Canonicalize the base so safe_join keeps target files directly within it.
    let base = codex_dir.canonicalize()?;
    merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
    append_workspace_md(&safe_join(&base, "AGENTS.md")?)
}

// Workspace-mode instruction block. Agent-agnostic (it only references
// `tracevault repo …`), so it's shared verbatim between the Claude global
// install's `CLAUDE.md` and the Codex global install's `AGENTS.md`.
const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";

const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
A session started in a registered repo's checkout is bound to that repo automatically. To work
on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
one-off. Repos must already be registered with TraceVault. In a directory bound to a project
with `tracevault init --workspace`, sessions are recorded to that project without it, so
`repo switch` there is optional: it only adds the repo and its policies.
";

/// Every earlier text of [`GLOBAL_CLAUDE_MD_BLOCK`] an install may have
/// written, oldest first. Only an exact match is upgraded: the block has no
/// end marker, so anything else after the start marker may be the user's.
const PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS: &[&str] = &[
    "\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
You may be running detached from any single repository. Before working on a repo, run
`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
already be registered with TraceVault.
",
    "\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
A session started in a registered repo's checkout is bound to that repo automatically. To work
on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
one-off. Repos must already be registered with TraceVault.
",
];

/// `content` with an earlier install's block (an exact
/// [`PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS`] text) replaced by the current
/// [`GLOBAL_CLAUDE_MD_BLOCK`]. A block that matches none of them — the
/// current one, or one the user edited — is left exactly as it is.
fn replace_managed_block(content: &str) -> String {
    if content.contains(GLOBAL_CLAUDE_MD_BLOCK) {
        return content.to_string();
    }
    PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS
        .iter()
        .find(|old| content.contains(*old))
        .map_or_else(
            || content.to_string(),
            |old| content.replacen(old, GLOBAL_CLAUDE_MD_BLOCK, 1),
        )
}

/// Append the workspace-mode instruction block to `md_path` (creating it if
/// absent), idempotently — guarded by [`GLOBAL_CLAUDE_MD_MARKER`], so a re-run
/// never duplicates it and any existing user content is preserved. A block an
/// earlier version installed is replaced with the current text in place. Shared by
/// the Claude global install (`CLAUDE.md`) and the Codex global install
/// (`AGENTS.md`).
fn append_workspace_md(md_path: &Path) -> io::Result<()> {
    // Defense-in-depth against path traversal (see `merge_hooks_into_file`).
    if md_path
        .components()
        .any(|c| c == std::path::Component::ParentDir)
    {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("refusing to use path with '..': {}", md_path.display()),
        ));
    }
    let existing = if md_path.exists() {
        fs::read_to_string(md_path)?
    } else {
        String::new()
    };
    if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
        // An earlier install's block: bring it to the current text in place
        // (VIS-1256 changed it), leaving everything around it untouched.
        let replaced = replace_managed_block(&existing);
        if replaced != existing {
            fs::write(md_path, replaced)?;
        }
        return Ok(());
    }
    let mut content = existing;
    if !content.is_empty() && !content.ends_with('\n') {
        content.push('\n');
    }
    if !content.is_empty() {
        content.push('\n');
    }
    content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
    fs::write(md_path, content)
}

/// Join a constant file name to `base` and confirm the result stays directly
/// within `base` — defense-in-depth so a path derived from the environment
/// ($HOME) cannot escape the intended `.claude` directory.
pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
    let joined = base.join(name);
    if joined.parent() != Some(base) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            format!(
                "refusing to access path outside {}: {}",
                base.display(),
                joined.display()
            ),
        ));
    }
    Ok(joined)
}

/// An inner hook belongs to TraceVault when its `command` starts with
/// `tracevault ` — every hook command `init` has ever installed does, and a
/// user's own hook running something else never does. This is what lets a
/// re-run replace exactly our entries (old matcher, timeout, status message,
/// a dropped event) and nothing else.
const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";

fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
    hook.get("command")
        .and_then(|c| c.as_str())
        .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
}

/// Remove TraceVault-owned inner hooks from one event's matcher groups. A
/// group that held only our hooks is dropped; a group shared with foreign
/// hooks keeps them and everything else it had. Groups without any of our
/// hooks are left untouched. Returns the position of the first dropped group,
/// so the current set can go back where the old one was — which keeps a
/// re-run on an up-to-date file a no-op.
fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
    let mut slot = None;
    let mut kept = Vec::with_capacity(entries.len());
    for mut entry in entries.drain(..) {
        if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
            let before = inner.len();
            inner.retain(|hook| !is_tracevault_hook(hook));
            if inner.is_empty() && before > 0 {
                slot.get_or_insert(kept.len());
                continue;
            }
        }
        kept.push(entry);
    }
    *entries = kept;
    slot
}

/// Bring `settings["hooks"]` to exactly `ours` for TraceVault's entries while
/// keeping every foreign hook: our inner hooks (see [`is_tracevault_hook`])
/// are removed from every event, then the current `ours` entries are put back
/// in their place (appended for an event that had none). Re-running converges
/// to the current hook set, and events we no longer install lose our entries.
/// Top-level keys and foreign hooks are never touched.
///
/// Absent values (no `hooks` key, no entry for a given event) are created
/// fresh — that's fine; a missing file reaches here as `{}`. But if an
/// EXISTING value has an unexpected shape (top-level `settings` isn't an
/// object — `null` included —, an existing `hooks` isn't an object, or one of
/// our events isn't an array), this errors loudly instead of silently
/// discarding it. A foreign event whose value isn't an array is left as it is.
fn merge_hooks(
    settings: &mut serde_json::Value,
    ours: &serde_json::Value,
    path: &Path,
) -> io::Result<()> {
    let settings_obj = settings.as_object_mut().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{} is not a JSON object", path.display()),
        )
    })?;

    let hooks_value = settings_obj
        .entry("hooks")
        .or_insert_with(|| serde_json::json!({}));
    let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidData,
            format!("{} \"hooks\" key is not a JSON object", path.display()),
        )
    })?;

    let empty = serde_json::Map::new();
    let ours_obj = ours.as_object().unwrap_or(&empty);

    // Validate before mutating anything, so an error leaves `settings` as read.
    for event in ours_obj.keys() {
        if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!(
                    "{} \"hooks\".\"{event}\" is not a JSON array",
                    path.display()
                ),
            ));
        }
    }

    let mut emptied = Vec::new();
    for (event, value) in hooks_obj.iter_mut() {
        let Some(existing) = value.as_array_mut() else {
            continue;
        };
        let had_entries = !existing.is_empty();
        let slot = strip_tracevault_hooks(existing);
        let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
        match our_entries {
            Some(our_entries) => {
                let at = slot.unwrap_or(existing.len());
                existing.splice(at..at, our_entries.iter().cloned());
            }
            None if had_entries && existing.is_empty() => emptied.push(event.clone()),
            None => {}
        }
    }
    // An event that only ever held our (now retired) hooks goes away entirely.
    hooks_obj.retain(|event, _| !emptied.contains(event));

    for (event, our_array) in ours_obj {
        if !hooks_obj.contains_key(event) {
            hooks_obj.insert(event.clone(), our_array.clone());
        }
    }

    Ok(())
}

/// Whether the Claude Code settings file at `path` holds any TraceVault hook.
/// A missing file holds none; one that cannot be read or parsed is an error
/// (it may hold some).
pub(crate) fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
    let text = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
        Err(e) => return Err(e),
    };
    let settings: serde_json::Value =
        serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
    Ok(settings
        .get("hooks")
        .and_then(|h| h.as_object())
        .into_iter()
        .flat_map(|events| events.values())
        .filter_map(|groups| groups.as_array())
        .flatten()
        .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
        .flatten()
        .any(is_tracevault_hook))
}

/// Bring the TraceVault hooks in the Claude Code settings file at `path` to
/// the current set ([`tracevault_hooks`]), exactly as `init` would. Used by
/// the upgrade step (VIS-1109) on a file that already holds our hooks.
pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
    merge_hooks_into_file(path, &tracevault_hooks())
}

/// Install TraceVault's Claude Code hooks into `claude_dir/settings.json`
/// (deep-merged, never clobbering existing hooks/keys) and append a
/// workspace-mode instruction block to `claude_dir/CLAUDE.md` (idempotent,
/// guarded by a marker comment). Intended for `tracevault init --global`,
/// installing once for all Claude Code sessions rather than per-repo.
pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
    fs::create_dir_all(claude_dir)?;

    // Canonicalize the base to defend against path traversal attacks.
    // safe_join will verify that target files stay directly within this base.
    let base = claude_dir.canonicalize()?;

    // --- settings.json: deep-merge hooks (atomic) ---
    merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;

    // --- CLAUDE.md: append the workspace-mode instruction block, idempotently ---
    append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
}

/// Write the user-level `config.toml` (under `config_root`) carrying the
/// user-context setting. An EXISTING user config is preserved (this mirrors the
/// "don't clobber" contract of the global-hooks install): `requested` overrides
/// the user_context when a flag was given; otherwise an existing value is kept,
/// and only a first-time setup (no existing config) defaults to enabled.
/// When the resulting layer is enabled, the referenced context file is seeded
/// (empty) if absent — a custom `--user-context <path>` seeds THAT file, a
/// disabled layer seeds nothing. Returns the active context file path (the file
/// the hook will read), or `None` when the layer is disabled. Used by `init --global`.
pub fn write_global_user_config_in(
    config_root: &Path,
    requested: Option<UserContext>,
) -> io::Result<Option<PathBuf>> {
    fs::create_dir_all(config_root)?;
    // Preserve an existing (valid) user config; malformed/missing → start fresh.
    let mut config = crate::config::try_load_user_config_in(config_root)
        .ok()
        .flatten()
        .unwrap_or_default();
    // Requested flag wins; else keep an existing value; else first-run default = enabled.
    let user_context = requested
        .or_else(|| config.user_context.clone())
        .unwrap_or(UserContext::Toggle(true));
    let active = user_context
        .resolve()
        .map(|_| user_context.path_in(config_root));
    config.user_context = Some(user_context);
    fs::write(user_config_path_in(config_root), config.to_toml())?;
    if let Some(ref ctx_path) = active {
        if !ctx_path.exists() {
            Context::default().save_to(ctx_path)?;
        }
    }
    Ok(active)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::{BufRead, BufReader, Write};
    use std::net::TcpListener;
    use std::thread;

    /// Installing the hooks is not enough on Codex >= 0.153: they are gated
    /// behind persisted hook trust, and `codex exec` skips untrusted hooks
    /// silently. The notice must say how to grant that trust interactively and
    /// name the flag that unblocks unattended runs — otherwise a user (or a CI
    /// image) reads "Installed" and gets no capture at all.
    #[test]
    fn codex_hook_trust_notice_explains_how_to_grant_trust() {
        let notice = codex_hook_trust_notice();
        assert!(
            notice.contains("hook trust"),
            "notice must name what is missing: {notice}"
        );
        assert!(
            notice.contains("codex") && notice.contains("approve"),
            "notice must tell the user to run codex and approve the prompt: {notice}"
        );
        assert!(
            notice.contains("--dangerously-bypass-hook-trust"),
            "notice must name the flag for unattended/CI runs: {notice}"
        );
        assert!(
            notice.contains("silently"),
            "notice must say the failure is silent, which is why it needs saying: {notice}"
        );
    }

    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
    /// request it accepts (mirrors `commands::repo`'s test module).
    fn spawn_once(response: String) -> String {
        let response: &'static str = Box::leak(response.into_boxed_str());
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        thread::spawn(move || {
            if let Ok((stream, _)) = listener.accept() {
                let mut reader = BufReader::new(stream);
                let mut request_line = String::new();
                let _ = reader.read_line(&mut request_line);
                let mut stream = reader.into_inner();
                let _ = stream.write_all(response.as_bytes());
                let _ = stream.flush();
            }
        });
        format!("http://{addr}")
    }

    /// Format a raw HTTP/1.1 response with the given `status` line and a
    /// correct `Content-Length` for `body`.
    fn http_response(status: &str, body: &str) -> String {
        format!(
            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            status,
            body.len(),
            body
        )
    }

    fn add_origin_remote(dir: &Path, url: &str) {
        let ok = std::process::Command::new("git")
            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
            .status()
            .expect("git remote add failed")
            .success();
        assert!(ok, "git remote add must succeed");
    }

    #[test]
    fn linked_worktree_primary_detects_linked_and_primary() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let wt = tmp.path().join("linked-wt");
        std::fs::create_dir_all(&repo).unwrap();
        crate::test_helpers::init_git_repo(&repo);
        crate::test_helpers::add_worktree(&repo, &wt);

        // Primary checkout → None.
        assert!(
            linked_worktree_primary(&repo).is_none(),
            "primary checkout must not be flagged as a linked worktree"
        );
        // Linked worktree → Some(primary root).
        let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
        assert_eq!(
            primary.canonicalize().unwrap(),
            repo.canonicalize().unwrap(),
            "must resolve to the primary repo root"
        );
    }

    #[test]
    fn linked_worktree_primary_none_for_non_git() {
        let tmp = tempfile::tempdir().unwrap();
        assert!(
            linked_worktree_primary(tmp.path()).is_none(),
            "a non-git directory is not a linked worktree"
        );
    }

    /// The inner `hooks[0].command` of a hook-event entry, if present.
    fn entry_command(entry: &serde_json::Value) -> Option<&str> {
        entry.get("hooks")?.get(0)?.get("command")?.as_str()
    }

    #[test]
    fn merge_hooks_into_empty_settings_adds_all_our_events() {
        let mut settings = serde_json::json!({});
        let ours = tracevault_hooks();
        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();

        let hooks = settings.get("hooks").unwrap();
        for event in [
            "PreToolUse",
            "PostToolUse",
            "Notification",
            "Stop",
            "SessionEnd",
            "SubagentStop",
            "SessionStart",
            "UserPromptSubmit",
        ] {
            assert!(hooks.get(event).is_some(), "missing event {event}");
        }
    }

    #[test]
    fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
        let mut settings = serde_json::json!({
            "model": "opus",
            "hooks": {
                "PreToolUse": [{
                    "matcher": "",
                    "hooks": [{ "type": "command", "command": "my-own-hook" }]
                }]
            }
        });
        let ours = tracevault_hooks();
        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();

        // Other top-level keys preserved.
        assert_eq!(settings.get("model").unwrap(), "opus");

        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
        // Both the user's own hook and ours are present.
        assert_eq!(pre_tool_use.len(), 2);
        let commands: Vec<&str> = pre_tool_use
            .iter()
            .map(|e| entry_command(e).unwrap())
            .collect();
        assert!(commands.contains(&"my-own-hook"));
        assert!(commands.contains(&"tracevault stream --event pre-tool-use"));

        // Other events were added fresh.
        assert!(settings["hooks"]["SessionStart"].is_array());
    }

    #[test]
    fn merge_hooks_is_idempotent() {
        let mut settings = serde_json::json!({});
        let ours = tracevault_hooks();
        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
        merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();

        for event in [
            "PreToolUse",
            "PostToolUse",
            "Notification",
            "Stop",
            "SessionEnd",
            "SubagentStop",
            "SessionStart",
            "UserPromptSubmit",
        ] {
            let arr = settings["hooks"][event].as_array().unwrap();
            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
        }
    }

    #[test]
    fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
        // Our command sits at hooks[1] of a group the user owns: the group,
        // its matcher and the user's hook must survive unchanged, and our
        // command must end up exactly once — in its own current group.
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{
                    "matcher": "Write|Edit|Bash",
                    "hooks": [
                        { "type": "command", "command": "other", "timeout": 3 },
                        { "type": "command", "command": "tracevault stream --event pre-tool-use" }
                    ]
                }]
            }
        });
        merge_hooks(
            &mut settings,
            &tracevault_hooks(),
            Path::new("settings.json"),
        )
        .unwrap();

        let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(
            pre_tool_use[0],
            serde_json::json!({
                "matcher": "Write|Edit|Bash",
                "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
            })
        );
        assert_eq!(
            &pre_tool_use[1..],
            tracevault_hooks()["PreToolUse"].as_array().unwrap()
        );
    }

    /// A hook set as an older `init` wrote it: narrower PreToolUse matcher,
    /// timeout 5, no status messages and no SessionStart/UserPromptSubmit.
    fn stale_tracevault_hooks() -> serde_json::Value {
        let entry = |matcher: &str, event: &str| {
            serde_json::json!([{
                "matcher": matcher,
                "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
            }])
        };
        serde_json::json!({
            "PreToolUse": entry("Write|Edit", "pre-tool-use"),
            "PostToolUse": entry("", "post-tool-use"),
            "Notification": entry("", "notification"),
            "Stop": entry("", "stop"),
        })
    }

    #[test]
    fn merge_hooks_upgrades_stale_tracevault_entries() {
        let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
        merge_hooks(
            &mut settings,
            &tracevault_hooks(),
            Path::new("settings.json"),
        )
        .unwrap();
        assert_eq!(settings["hooks"], tracevault_hooks());
    }

    #[test]
    fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
        // An older Codex install with a PreToolUse hook we have since dropped,
        // next to a foreign event and a foreign non-array value we don't own.
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
                "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
                "Custom": "left alone"
            }
        });
        merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();

        let hooks = settings["hooks"].as_object().unwrap();
        assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
        assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
        assert_eq!(hooks["Custom"], "left alone");
        for (event, entries) in codex_hooks().as_object().unwrap() {
            assert_eq!(&hooks[event], entries, "{event}");
        }
    }

    #[test]
    fn merge_hooks_rerun_keeps_our_entry_in_place() {
        // Ours first, a user hook added after it: a re-run must not move ours
        // behind the user's (that would rewrite an up-to-date file).
        let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
        settings["hooks"]["Stop"]
            .as_array_mut()
            .unwrap()
            .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
        let before = settings.clone();
        merge_hooks(
            &mut settings,
            &tracevault_hooks(),
            Path::new("settings.json"),
        )
        .unwrap();
        assert_eq!(settings.to_string(), before.to_string());
    }

    #[test]
    fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
        let foreign = serde_json::json!({
            "matcher": "",
            "hooks": [
                { "type": "command", "command": "tracevault-wrapper stream" },
                { "type": "command", "command": "echo tracevault stream" },
                { "type": "command", "command": " tracevault check" }
            ]
        });
        let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
        merge_hooks(
            &mut settings,
            &tracevault_hooks(),
            Path::new("settings.json"),
        )
        .unwrap();
        assert_eq!(settings["hooks"]["Stop"][0], foreign);
        assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
    }

    #[test]
    fn merge_hooks_errors_on_non_object_top_level() {
        let mut settings = serde_json::json!([1, 2, 3]);
        let ours = tracevault_hooks();
        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("settings.json"));
    }

    #[test]
    fn merge_hooks_errors_on_non_object_top_level_number() {
        let mut settings = serde_json::json!(42);
        let ours = tracevault_hooks();
        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
    }

    #[test]
    fn merge_hooks_errors_on_non_object_hooks() {
        let mut settings = serde_json::json!({ "hooks": "not-an-object" });
        let ours = tracevault_hooks();
        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("hooks"));
    }

    #[test]
    fn merge_hooks_errors_on_non_array_event_value() {
        let mut settings = serde_json::json!({
            "hooks": {
                "PreToolUse": "not-an-array"
            }
        });
        let ours = tracevault_hooks();
        let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);
        assert!(err.to_string().contains("PreToolUse"));
    }

    #[test]
    fn install_global_hooks_writes_settings_and_claude_md() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");

        install_global_hooks(&claude_dir).unwrap();

        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
        for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
            assert!(settings["hooks"].get(event).is_some(), "missing {event}");
        }

        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
    }

    #[test]
    fn install_global_hooks_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");

        install_global_hooks(&claude_dir).unwrap();
        install_global_hooks(&claude_dir).unwrap();

        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
        for event in [
            "PreToolUse",
            "PostToolUse",
            "Notification",
            "Stop",
            "SessionEnd",
            "SubagentStop",
            "SessionStart",
            "UserPromptSubmit",
        ] {
            let arr = settings["hooks"][event].as_array().unwrap();
            assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
        }

        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
        let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
        assert_eq!(
            marker_count, 1,
            "CLAUDE.md marker should appear exactly once"
        );
    }

    #[test]
    fn install_global_hooks_preserves_existing_claude_md_content() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");
        fs::create_dir_all(&claude_dir).unwrap();
        fs::write(
            claude_dir.join("CLAUDE.md"),
            "# My existing notes\nSome content.\n",
        )
        .unwrap();

        install_global_hooks(&claude_dir).unwrap();

        let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
        assert!(claude_md.contains("# My existing notes"));
        assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
    }

    #[test]
    fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");

        install_global_hooks(&claude_dir).unwrap();

        let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
        let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
        assert!(settings["hooks"].get("SessionStart").is_some());

        let leftover = fs::read_dir(&claude_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
        assert!(
            !leftover,
            "no settings.json.tmp should remain after install"
        );
    }

    #[test]
    fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");
        fs::create_dir_all(&claude_dir).unwrap();
        let settings_path = claude_dir.join("settings.json");
        let original = "[1, 2, 3]";
        fs::write(&settings_path, original).unwrap();

        let err = install_global_hooks(&claude_dir).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);

        // The original (malformed-for-our-purposes but validly-JSON) file
        // must be untouched, and no stray tmp file left behind.
        let after = fs::read_to_string(&settings_path).unwrap();
        assert_eq!(after, original);
        let leftover = fs::read_dir(&claude_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
        assert!(!leftover, "no tmp file should be left behind on error");
    }

    #[test]
    fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");
        fs::create_dir_all(&claude_dir).unwrap();
        let settings_path = claude_dir.join("settings.json");
        let original = r#"{"hooks": "oops"}"#;
        fs::write(&settings_path, original).unwrap();

        let err = install_global_hooks(&claude_dir).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);

        let after = fs::read_to_string(&settings_path).unwrap();
        assert_eq!(after, original);
    }

    #[test]
    fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");
        fs::create_dir_all(&claude_dir).unwrap();
        let settings_path = claude_dir.join("settings.json");
        let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
        fs::write(&settings_path, original).unwrap();

        let err = install_global_hooks(&claude_dir).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidData);

        let after = fs::read_to_string(&settings_path).unwrap();
        assert_eq!(after, original);
    }

    #[test]
    fn safe_join_allows_direct_child_file() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path();
        let result = safe_join(base, "settings.json").unwrap();
        assert_eq!(result.parent(), Some(base));
        assert_eq!(result.file_name().unwrap(), "settings.json");
    }

    #[test]
    fn safe_join_rejects_path_traversal() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path();
        let result = safe_join(base, "../evil");
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
        assert!(err.to_string().contains("refusing to access path outside"));
    }

    #[test]
    fn safe_join_rejects_absolute_path() {
        let tmp = tempfile::tempdir().unwrap();
        let base = tmp.path();
        let result = safe_join(base, "/etc/passwd");
        // An absolute path joined to a base will replace the base,
        // so parent will not equal base.
        assert!(result.is_err());
    }

    #[test]
    fn write_global_user_config_enables_and_creates_context() {
        let root = tempfile::tempdir().unwrap();
        let active = write_global_user_config_in(root.path(), None).unwrap();
        let cfg = crate::config::try_load_user_config_in(root.path())
            .unwrap()
            .unwrap();
        // Validate against the INJECTED root (resolve_in), not tv_config_root():
        // a first-run default enables at the `context.json` under `root`.
        assert_eq!(
            cfg.user_context.unwrap().resolve_in(root.path()),
            Some(crate::config::default_user_context_path_in(root.path()))
        );
        let ctx = crate::config::default_user_context_path_in(root.path());
        assert_eq!(active, Some(ctx.clone()));
        assert!(ctx.exists());
    }

    #[test]
    fn write_global_user_config_can_disable() {
        let root = tempfile::tempdir().unwrap();
        let active = write_global_user_config_in(
            root.path(),
            Some(crate::config::UserContext::Toggle(false)),
        )
        .unwrap();
        let cfg = crate::config::try_load_user_config_in(root.path())
            .unwrap()
            .unwrap();
        assert!(matches!(
            cfg.user_context,
            Some(crate::config::UserContext::Toggle(false))
        ));
        assert_eq!(active, None, "disabled → no active context path");
        // A disabled layer must NOT seed a context file.
        assert!(
            !crate::config::default_user_context_path_in(root.path()).exists(),
            "disabled user context must not create a context.json"
        );
    }

    #[test]
    fn write_global_user_config_custom_path_seeds_that_file_only() {
        let root = tempfile::tempdir().unwrap();
        let custom = root.path().join("custom-ctx.json");
        let active = write_global_user_config_in(
            root.path(),
            Some(crate::config::UserContext::Path(
                custom.to_string_lossy().into_owned(),
            )),
        )
        .unwrap();
        assert_eq!(active, Some(custom.clone()));
        assert!(custom.exists(), "the configured custom path must be seeded");
        assert!(
            !crate::config::default_user_context_path_in(root.path()).exists(),
            "the default context.json must NOT be created when a custom path is configured"
        );
    }

    #[test]
    fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
        let root = tempfile::tempdir().unwrap();
        let custom = root.path().join("custom-ctx.json");
        // First run pins a custom path.
        write_global_user_config_in(
            root.path(),
            Some(crate::config::UserContext::Path(
                custom.to_string_lossy().into_owned(),
            )),
        )
        .unwrap();
        // Re-run with NO flags must NOT reset it back to the default.
        let active = write_global_user_config_in(root.path(), None).unwrap();
        assert_eq!(
            active,
            Some(custom.clone()),
            "re-run without flags must preserve the custom path"
        );
        let cfg = crate::config::try_load_user_config_in(root.path())
            .unwrap()
            .unwrap();
        assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
    }

    #[test]
    fn install_global_codex_hooks_writes_and_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_dir = tmp.path().join(".codex");

        install_global_codex_hooks(&codex_dir).unwrap();
        install_global_codex_hooks(&codex_dir).unwrap();

        let v: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
                .unwrap();
        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
            let arr = v["hooks"][event].as_array().unwrap();
            assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
        }
        assert!(v["hooks"].get("PreToolUse").is_none());
        // AGENTS.md carries the workspace-mode block exactly once across re-runs.
        let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
        assert_eq!(
            agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
            1,
            "AGENTS.md workspace-mode block must appear exactly once"
        );
        // No stray temp file left behind.
        let leftover = fs::read_dir(&codex_dir)
            .unwrap()
            .filter_map(|e| e.ok())
            .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
        assert!(!leftover);
    }

    #[test]
    fn codex_hooks_has_expected_events_and_commands() {
        let h = codex_hooks();
        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
            assert!(h.get(event).is_some(), "missing codex event {event}");
        }
        // No PreToolUse (intentionally dropped — PostToolUse + Stop capture the
        // rollout; a pre-tool hook would only double per-call streaming) and no
        // Notification event (Codex has none).
        assert!(h.get("PreToolUse").is_none());
        assert!(h.get("Notification").is_none());
        // Capture commands carry --agent codex; injection hooks do not need it.
        let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
        assert_eq!(
            cmd("PostToolUse"),
            "tracevault stream --event post-tool-use --agent codex"
        );
        assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
        assert_eq!(cmd("SessionStart"), "tracevault session-start");
        assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
        // Matchers are "" (all tools) — Codex edits arrive via the transcript.
        assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
    }

    #[test]
    fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
        let tmp = tempfile::tempdir().unwrap();
        install_codex_hooks(tmp.path()).unwrap();
        install_codex_hooks(tmp.path()).unwrap();

        let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
        let v: serde_json::Value = serde_json::from_str(&content).unwrap();
        for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
            let arr = v["hooks"][event].as_array().unwrap();
            assert_eq!(
                arr.len(),
                1,
                "event {event} must not be duplicated on re-run"
            );
        }
        assert!(v["hooks"].get("PreToolUse").is_none());
    }

    #[test]
    fn install_codex_hooks_preserves_existing_user_hook() {
        let tmp = tempfile::tempdir().unwrap();
        let codex_dir = tmp.path().join(".codex");
        fs::create_dir_all(&codex_dir).unwrap();
        // Seed a user hook under an event we install (PostToolUse) plus one under
        // an event we DON'T (PreToolUse) — both must survive the merge.
        fs::write(
            codex_dir.join("hooks.json"),
            r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
        )
        .unwrap();

        install_codex_hooks(tmp.path()).unwrap();

        let v: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
                .unwrap();
        // Our PostToolUse command is merged in alongside the user's own.
        let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
            .collect();
        assert!(
            post_cmds.contains(&"my-own"),
            "user PostToolUse hook preserved"
        );
        assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
        // The user's PreToolUse hook is left untouched (we install no PreToolUse).
        let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
            .as_array()
            .unwrap()
            .iter()
            .map(|e| e["hooks"][0]["command"].as_str().unwrap())
            .collect();
        assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
    }

    /// A settings file a user might really have: other keys, foreign hooks in
    /// their own groups and in a group shared with ours, keys in non-sorted
    /// order, and a stale TraceVault install.
    const FOREIGN_SETTINGS: &str = r#"{
  "permissions": { "allow": ["Bash(ls)"] },
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
      { "matcher": "Write|Edit", "hooks": [
        { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
        { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
      ] }
    ],
    "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
    "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
  },
  "model": "opus"
}"#;

    /// Serialised forms of the foreign entries in [`FOREIGN_SETTINGS`], as
    /// they must appear after an install: unchanged values, unchanged key
    /// order; the shared group just loses our hook.
    fn expected_foreign_entries() -> Vec<String> {
        [
            r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
            r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
            r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
        ]
        .map(String::from)
        .to_vec()
    }

    fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
        entry["hooks"]
            .as_array()
            .unwrap()
            .iter()
            .any(is_tracevault_hook)
    }

    fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
        let v: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
        assert_eq!(
            v.as_object().unwrap().keys().collect::<Vec<_>>(),
            ["permissions", "hooks", "model"],
            "top-level keys kept, in their order"
        );
        assert_eq!(
            v["permissions"],
            serde_json::json!({ "allow": ["Bash(ls)"] })
        );
        let hooks = v["hooks"].as_object().unwrap();
        let foreign: Vec<String> = hooks
            .values()
            .flat_map(|entries| entries.as_array().unwrap())
            .filter(|e| !holds_tracevault_hook(e))
            .map(|e| e.to_string())
            .collect();
        assert_eq!(foreign, expected_foreign_entries());
        let ours = ours.as_object().unwrap();
        for (event, entries) in hooks {
            let mine: Vec<&serde_json::Value> = entries
                .as_array()
                .unwrap()
                .iter()
                .filter(|e| holds_tracevault_hook(e))
                .collect();
            let want: Vec<&serde_json::Value> = ours
                .get(event)
                .map(|o| o.as_array().unwrap().iter().collect())
                .unwrap_or_default();
            assert_eq!(mine, want, "TraceVault entries under {event}");
        }
        for event in ours.keys() {
            assert!(hooks.contains_key(event), "missing {event}");
        }
    }

    #[test]
    fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
        for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
            let tmp = tempfile::tempdir().unwrap();
            let path = tmp.path().join(".claude").join(target.filename());
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(&path, FOREIGN_SETTINGS).unwrap();

            install_claude_hooks(tmp.path(), target).unwrap();
            assert_installed_over_foreign(&path, &tracevault_hooks());

            // A second run finds the file current and leaves its bytes alone.
            let after_first = fs::read(&path).unwrap();
            install_claude_hooks(tmp.path(), target).unwrap();
            assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
        }
    }

    #[test]
    fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
        let tmp = tempfile::tempdir().unwrap();
        let claude_dir = tmp.path().join(".claude");
        fs::create_dir_all(&claude_dir).unwrap();
        fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();

        install_global_hooks(&claude_dir).unwrap();
        assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
    }

    #[test]
    fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
        for global in [false, true] {
            let tmp = tempfile::tempdir().unwrap();
            let codex_dir = tmp.path().join(".codex");
            fs::create_dir_all(&codex_dir).unwrap();
            fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();

            if global {
                install_global_codex_hooks(&codex_dir).unwrap();
            } else {
                install_codex_hooks(tmp.path()).unwrap();
            }
            assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
        }
    }

    #[test]
    fn up_to_date_hook_file_is_not_rewritten() {
        // Hand-formatted (4-space indent) but already current: no reformatting.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join(".claude/settings.json");
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        let mut body = Vec::new();
        let fmt = serde_json::ser::PrettyFormatter::with_indent(b"    ");
        let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
        serde::Serialize::serialize(
            &serde_json::json!({ "hooks": tracevault_hooks() }),
            &mut ser,
        )
        .unwrap();
        fs::write(&path, &body).unwrap();

        install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
        assert_eq!(fs::read(&path).unwrap(), body);
    }

    #[test]
    fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
        for (target, body) in [
            (ClaudeSettingsTarget::Shared, "{ not json"),
            (ClaudeSettingsTarget::Local, "[1, 2]"),
            (ClaudeSettingsTarget::Shared, "null"),
            (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
            (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
        ] {
            let tmp = tempfile::tempdir().unwrap();
            let path = tmp.path().join(".claude").join(target.filename());
            fs::create_dir_all(path.parent().unwrap()).unwrap();
            fs::write(&path, body).unwrap();

            let err = install_claude_hooks(tmp.path(), target).unwrap_err();
            assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
            assert_eq!(
                fs::read_to_string(&path).unwrap(),
                body,
                "file must be untouched"
            );
            assert_eq!(
                fs::read_dir(path.parent().unwrap()).unwrap().count(),
                1,
                "no temp file left behind"
            );
        }
    }

    #[test]
    fn concurrent_installs_never_publish_a_partial_file() {
        // Two writers flip the file between two hook sets, so every call
        // rewrites it, while a reader keeps parsing it: the file must always
        // be there and complete, and no temp file may remain. A writer that
        // keeps losing the race gives up with the "kept changing" error
        // rather than publishing a stale snapshot.
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join("settings.json");
        fs::write(&path, FOREIGN_SETTINGS).unwrap();
        let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let reader = {
            let (path, done) = (path.clone(), done.clone());
            std::thread::spawn(move || {
                while !done.load(std::sync::atomic::Ordering::Relaxed) {
                    let body = fs::read_to_string(&path).unwrap();
                    serde_json::from_str::<serde_json::Value>(&body).unwrap();
                }
            })
        };
        let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
            .into_iter()
            .map(|ours| {
                let path = path.clone();
                std::thread::spawn(move || {
                    for _ in 0..200 {
                        if let Err(e) = merge_hooks_into_file(&path, &ours) {
                            assert!(e.to_string().contains("kept changing"), "{e}");
                        }
                    }
                })
            })
            .collect();
        for writer in writers {
            writer.join().unwrap();
        }
        done.store(true, std::sync::atomic::Ordering::Relaxed);
        reader.join().unwrap();
        let v: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(v["model"], "opus");
        assert_eq!(
            fs::read_dir(tmp.path()).unwrap().count(),
            1,
            "no temp file left"
        );
    }

    #[cfg(unix)]
    #[test]
    fn install_claude_hooks_keeps_file_permissions() {
        use std::os::unix::fs::PermissionsExt;
        let tmp = tempfile::tempdir().unwrap();
        let path = tmp.path().join(".claude/settings.local.json");
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(&path, FOREIGN_SETTINGS).unwrap();
        fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();

        install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();

        let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600);
        assert_installed_over_foreign(&path, &tracevault_hooks());
    }

    #[cfg(unix)]
    #[test]
    fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
        let tmp = tempfile::tempdir().unwrap();
        let central = tmp.path().join("central/claude-settings.json");
        fs::create_dir_all(central.parent().unwrap()).unwrap();
        fs::write(&central, FOREIGN_SETTINGS).unwrap();
        let link = tmp.path().join("repo/.claude/settings.json");
        fs::create_dir_all(link.parent().unwrap()).unwrap();
        std::os::unix::fs::symlink(&central, &link).unwrap();

        install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();

        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
        assert_installed_over_foreign(&central, &tracevault_hooks());
    }

    #[cfg(unix)]
    #[test]
    fn install_claude_hooks_refuses_dangling_symlink() {
        let tmp = tempfile::tempdir().unwrap();
        let link = tmp.path().join(".claude/settings.json");
        fs::create_dir_all(link.parent().unwrap()).unwrap();
        std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();

        assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
        assert!(fs::symlink_metadata(&link)
            .unwrap()
            .file_type()
            .is_symlink());
        assert!(!tmp.path().join("gone.json").exists());
    }

    #[test]
    fn validate_init_flags_rejects_claude_settings_with_codex() {
        assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
    }

    #[test]
    fn validate_init_flags_allows_codex_without_claude_settings() {
        assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
    }

    #[test]
    fn validate_init_flags_allows_claude_with_claude_settings() {
        assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
    }

    #[test]
    fn merge_hooks_into_file_rejects_parent_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let bad = tmp.path().join("..").join("hooks.json");
        let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[test]
    fn append_workspace_md_rejects_parent_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let bad = tmp.path().join("..").join("AGENTS.md");
        let err = append_workspace_md(&bad).unwrap_err();
        assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
    }

    #[tokio::test]
    async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        crate::test_helpers::init_git_repo(root);
        // `init` refuses to run without a credential; a per-repo one keeps
        // this test independent of the process env and the user's login.
        fs::create_dir_all(root.join(".tracevault")).unwrap();
        fs::write(
            root.join(".tracevault/config.toml"),
            "api_key = \"tvk_test\"\n",
        )
        .unwrap();

        let entry = init_in_directory(
            root,
            None,
            None,
            false,
            Some(crate::config::UserContext::Toggle(false)),
            crate::agent::Agent::Codex,
        )
        .await
        .unwrap();

        // Codex hooks file written; Claude settings NOT created.
        assert!(root.join(".codex").join("hooks.json").exists());
        assert!(!root.join(".claude").join("settings.json").exists());
        assert_eq!(entry, ".codex/hooks.json");

        // .gitignore covers the codex hooks file.
        let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
        assert!(gi.contains(".codex/hooks.json"));
        assert!(gi.contains(".tracevault/"));
    }

    /// A successful `POST /api/v1/repos` during `init` must persist the
    /// returned `repo_id` into `.tracevault/config.toml` — this is the
    /// "everything worked" happy path of the registration step at the end of
    /// `init_in_directory`, previously untested.
    ///
    /// `XDG_CONFIG_HOME` is redirected so this doesn't read/write the
    /// developer's real `~/.config/tracevault/credentials.json`;
    /// `TRACEVAULT_API_KEY` is pinned directly since `resolve_credentials`
    /// checks it before the credentials file. `_env_lock` serializes this
    /// against other tests in the crate that mutate the same env vars
    /// (see `test_helpers::lock_env_mutation`).
    #[tokio::test]
    async fn init_in_directory_registers_repo_and_persists_repo_id() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        crate::test_helpers::init_git_repo(root);
        add_origin_remote(root, "git@github.com:org/repo.git");

        let repo_id = "11111111-1111-4111-8111-111111111111";
        let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
        // The remote is unknown (domain 404), so init registers; the resolve
        // after registering may fail, it is display-only.
        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
            http_response("404 Not Found", NO_REMOTE),
            http_response("200 OK", &body),
        ]);

        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        init_in_directory(
            root,
            Some(&base),
            None,
            true,
            Some(crate::config::UserContext::Toggle(false)),
            crate::agent::Agent::Codex,
        )
        .await
        .unwrap();

        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
        assert_eq!(
            cfg.repo_id,
            Some(repo_id.to_string()),
            "successful registration must persist repo_id to config.toml"
        );
    }

    /// A 403 on `POST /api/v1/repos` must be a non-fatal warning (`init`
    /// still succeeds and installs hooks) and must NOT persist a `repo_id` —
    /// there's nothing valid to persist. The exact wording of the warning is
    /// covered by `registration_failure_message_flags_403_as_not_authorized`
    /// below.
    #[tokio::test]
    async fn init_in_directory_registration_403_does_not_persist_repo_id() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path();
        crate::test_helpers::init_git_repo(root);
        add_origin_remote(root, "git@github.com:org/repo.git");

        let (base, _rx) = crate::test_helpers::spawn_seq(vec![
            http_response("404 Not Found", NO_REMOTE),
            http_response("403 Forbidden", ""),
        ]);

        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        let entry = init_in_directory(
            root,
            Some(&base),
            None,
            true,
            Some(crate::config::UserContext::Toggle(false)),
            crate::agent::Agent::Codex,
        )
        .await
        .expect("a registration failure (403) must not abort init itself");
        assert_eq!(entry, ".codex/hooks.json");

        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
        assert!(
            cfg.repo_id.is_none(),
            "a 403 registration failure must not persist a repo_id"
        );
    }

    /// The actual error shape `ApiClient::register_repo` produces for a 403
    /// response (via the same mock-server harness) must be recognized by
    /// `registration_failure_message` as a not-authorized case, not a
    /// generic server fault.
    #[tokio::test]
    async fn registration_failure_message_flags_403_as_not_authorized() {
        let base = spawn_once(http_response("403 Forbidden", ""));
        let client = ApiClient::new(&base, Some("tok"));
        let err = client
            .register_repo(crate::api_client::RegisterRepoRequest {
                repo_name: "repo".into(),
                github_url: Some("git@github.com:org/repo.git".into()),
            })
            .await
            .unwrap_err();
        let msg = registration_failure_message(err.as_ref());
        assert!(
            msg.contains("not authorized"),
            "403 registration failure must surface a not-authorized message; got: {msg}"
        );
    }

    /// A non-403 registration failure (e.g. a 500) keeps the generic
    /// "could not register" wording, distinguishing it from the 403 case.
    #[tokio::test]
    async fn registration_failure_message_generic_for_non_403() {
        let base = spawn_once(http_response("500 Internal Server Error", ""));
        let client = ApiClient::new(&base, Some("tok"));
        let err = client
            .register_repo(crate::api_client::RegisterRepoRequest {
                repo_name: "repo".into(),
                github_url: Some("git@github.com:org/repo.git".into()),
            })
            .await
            .unwrap_err();
        let msg = registration_failure_message(err.as_ref());
        assert!(
            msg.contains("could not register repo on server"),
            "got: {msg}"
        );
        assert!(!msg.contains("not authorized"), "got: {msg}");
    }

    /// A 500 whose BODY happens to contain the digits "403" (e.g. a proxy
    /// error page quoting an unrelated status) must not be misclassified as
    /// a 403-not-authorized failure — the match must key on the actual
    /// status prefix, not a bare substring search over the whole message.
    #[tokio::test]
    async fn registration_failure_message_does_not_misclassify_403_in_body() {
        let base = spawn_once(http_response(
            "500 Internal Server Error",
            "upstream error 403 from proxy",
        ));
        let client = ApiClient::new(&base, Some("tok"));
        let err = client
            .register_repo(crate::api_client::RegisterRepoRequest {
                repo_name: "repo".into(),
                github_url: Some("git@github.com:org/repo.git".into()),
            })
            .await
            .unwrap_err();
        let msg = registration_failure_message(err.as_ref());
        assert!(
            !msg.contains("not authorized"),
            "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
        );
        assert!(
            msg.contains("could not register repo on server"),
            "got: {msg}"
        );
    }

    /// A 404 (the registration route doesn't exist on this server) surfaces a
    /// CLI/server version-mismatch hint rather than the generic wording, so
    /// the user has an actionable next step instead of an opaque status code.
    #[tokio::test]
    async fn registration_failure_message_flags_404_as_version_mismatch() {
        let base = spawn_once(http_response("404 Not Found", ""));
        let client = ApiClient::new(&base, Some("tok"));
        let err = client
            .register_repo(crate::api_client::RegisterRepoRequest {
                repo_name: "repo".into(),
                github_url: Some("git@github.com:org/repo.git".into()),
            })
            .await
            .unwrap_err();
        let msg = registration_failure_message(err.as_ref());
        assert!(
            msg.to_lowercase().contains("version mismatch"),
            "a 404 registration failure should hint at a version mismatch; got: {msg}"
        );
    }

    // ── VIS-1018: init never registers a second repo for a known remote ───────

    /// The server's domain-404 body for an untracked remote.
    const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
    const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
    const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
    const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";

    fn resolve_remote_ok() -> String {
        http_response(
            "200 OK",
            &format!(
                r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
            ),
        )
    }

    fn remote_detail(repos: &[(&str, &str)]) -> String {
        let repos: Vec<String> = repos
            .iter()
            .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
            .collect();
        http_response(
            "200 OK",
            &format!(
                r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
                repos.join(",")
            ),
        )
    }

    /// Run `init` against `responses` and return the persisted repo_id and
    /// every request the server saw.
    async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
        let (base, rx) = crate::test_helpers::spawn_seq(responses);
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", root);
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        init_in_directory(
            root,
            Some(&base),
            None,
            true,
            Some(crate::config::UserContext::Toggle(false)),
            crate::agent::Agent::Codex,
        )
        .await
        .expect("init succeeds");

        let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
        (cfg.repo_id, rx.try_iter().collect())
    }

    fn registered(requests: &[String]) -> bool {
        requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
    }

    /// The prod incident: the checkout's directory is not named like the
    /// remote's existing repo. init binds that repo, and registers nothing.
    #[tokio::test]
    async fn init_binds_the_existing_repo_of_a_known_remote() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                resolve_remote_ok(),
                remote_detail(&[(CANONICAL, "tracevault")]),
            ],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
        assert!(!registered(&requests), "requests: {requests:?}");
    }

    /// Several records and one is named like this checkout: that one — the
    /// record registering would have upserted anyway.
    #[tokio::test]
    async fn init_binds_the_record_named_like_the_checkout() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
        let dir_name = crate::resolution::git_repo_name(tmp.path());

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                resolve_remote_ok(),
                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
            ],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(STRAY));
        assert!(!registered(&requests));
    }

    /// Re-running init keeps the repo the previous config.toml bound.
    #[tokio::test]
    async fn init_rerun_keeps_the_previously_bound_repo() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
        fs::write(
            tmp.path().join(".tracevault/config.toml"),
            format!("repo_id = \"{STRAY}\"\n"),
        )
        .unwrap();

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                resolve_remote_ok(),
                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
            ],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(STRAY));
        assert!(!registered(&requests));
    }

    /// Recording the binding keeps the rest of the config, including a
    /// hand-written `api_key` the struct never serializes (VIS-1046).
    #[tokio::test]
    async fn init_binding_keeps_the_rest_of_the_config() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
        fs::write(
            tmp.path().join(".tracevault/config.toml"),
            "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
        )
        .unwrap();

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                // The legacy `default_project` is migrated first (VIS-1256).
                http_response(
                    "200 OK",
                    &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
                ),
                resolve_remote_ok(),
                remote_detail(&[(CANONICAL, "tracevault")]),
            ],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
        assert!(
            requests[0].starts_with("GET /api/v1/projects"),
            "{requests:?}"
        );
        let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
        assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
        assert_eq!(cfg.default_project, None);
        assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
        assert_eq!(cfg.project_name.as_deref(), Some("payments"));
    }

    const PROJECT: &str = "00000000-0000-4000-8000-0000000000aa";

    /// An unknown `default_project` stops `init` before anything is written,
    /// naming the value (VIS-1256).
    #[tokio::test]
    async fn init_unknown_default_project_errors_and_writes_nothing() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
        let content = "default_project = \"typo\"\n";
        fs::write(tmp.path().join(".tracevault/config.toml"), content).unwrap();
        let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
            "200 OK",
            &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
        )]);
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        let err = init_in_directory(
            tmp.path(),
            Some(&base),
            None,
            true,
            None,
            crate::agent::Agent::Codex,
        )
        .await
        .unwrap_err();

        assert!(err.to_string().contains("'typo'"), "{err}");
        assert_eq!(
            fs::read_to_string(tmp.path().join(".tracevault/config.toml")).unwrap(),
            content
        );
        assert!(!tmp.path().join(".codex/hooks.json").exists());
    }

    /// `init --workspace --project <name>` in a non-git directory creates
    /// `.tracevault/`, resolves the name once, and writes `project_id` +
    /// `project_name` with no `repo_id` (VIS-1256).
    #[tokio::test]
    async fn init_workspace_binds_a_non_git_dir_to_a_project() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("umbrella");
        fs::create_dir_all(&dir).unwrap();
        let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response(
            "200 OK",
            &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
        )]);
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        let bound = init_workspace(&dir, "visdom", Some(&base)).await.unwrap();

        assert_eq!(bound.project_id.to_string(), PROJECT);
        assert_eq!(bound.project_name, "visdom");
        let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
        assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
        assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
        assert_eq!(cfg.repo_id, None);
        assert_eq!(cfg.server_url.as_deref(), Some(base.as_str()));
        assert!(dir.join(".tracevault/.gitignore").exists());
        let requests: Vec<String> = rx.try_iter().collect();
        assert_eq!(requests.len(), 1, "{requests:?}");
        // A sub-directory resolves to this config, as the stream hook does.
        let sub = dir.join("notes");
        fs::create_dir_all(&sub).unwrap();
        assert_eq!(
            crate::paths::resolve_project_root(&sub)
                .root
                .canonicalize()
                .unwrap(),
            dir.canonicalize().unwrap()
        );
    }

    /// Re-binding an existing workspace config replaces the project, drops a
    /// legacy `default_project`, and keeps unrelated keys.
    #[tokio::test]
    async fn init_workspace_rebinds_and_keeps_other_keys() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path();
        fs::create_dir_all(dir.join(".tracevault")).unwrap();
        fs::write(
            dir.join(".tracevault/config.toml"),
            "default_project = \"old\"\nproject_id = \"00000000-0000-4000-8000-000000000001\"\nuser_context = false\n",
        )
        .unwrap();
        let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
            "200 OK",
            &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
        )]);
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", dir);
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        init_workspace(dir, "visdom", Some(&base)).await.unwrap();

        let cfg = crate::config::TracevaultConfig::load(dir).unwrap();
        assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
        assert_eq!(cfg.default_project, None);
        assert!(matches!(
            cfg.user_context,
            Some(crate::config::UserContext::Toggle(false))
        ));
    }

    /// An older install's workspace-mode block is replaced in place with the
    /// current text; content before and after it is kept, and a re-run is a
    /// no-op.
    #[test]
    fn append_workspace_md_upgrades_an_older_block_in_place() {
        let tmp = tempfile::tempdir().unwrap();
        let md = tmp.path().join("CLAUDE.md");
        for old in PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS {
            // User text right after the block, with no blank line between.
            fs::write(
                &md,
                format!("# Mine\nkeep me\n\n{old}## After\nalso keep\n"),
            )
            .unwrap();

            append_workspace_md(&md).unwrap();
            let got = fs::read_to_string(&md).unwrap();
            assert_eq!(
                got,
                format!("# Mine\nkeep me\n\n{GLOBAL_CLAUDE_MD_BLOCK}## After\nalso keep\n")
            );
            append_workspace_md(&md).unwrap();
            assert_eq!(fs::read_to_string(&md).unwrap(), got);
        }

        // A block the user edited is never touched.
        let edited = "x\n\n<!-- tracevault:workspace-mode -->\n## T\nmy own words\n";
        fs::write(&md, edited).unwrap();
        append_workspace_md(&md).unwrap();
        assert_eq!(fs::read_to_string(&md).unwrap(), edited);
    }

    /// `--server-url` naming another instance than the credential's never
    /// gets that credential: `init --workspace` refuses before any request.
    #[tokio::test]
    async fn init_workspace_refuses_a_server_url_the_credential_is_not_for() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response("200 OK", "[]")]);
        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
        fs::write(
            tmp.path().join(".tracevault/config.toml"),
            "server_url = \"http://other.example.invalid\"\napi_key = \"tvk_x\"\n",
        )
        .unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.remove("TRACEVAULT_API_KEY");
        _guard.remove("TRACEVAULT_SERVER_URL");

        let err = init_workspace(tmp.path(), "visdom", Some(&base))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("not --server-url"), "{err}");
        assert_eq!(rx.try_iter().count(), 0, "no request may be sent");
    }

    #[tokio::test]
    async fn credential_url_mismatch_only_for_a_different_explicit_server() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_API_KEY");
        assert!(credential_url_mismatch(Some("https://a/"), Some("https://a")).is_none());
        assert!(credential_url_mismatch(None, Some("https://b")).is_none());
        assert!(credential_url_mismatch(Some("https://a"), None).is_none());
        assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_some());
        // An explicitly supplied key is paired with the explicit URL.
        _guard.set("TRACEVAULT_API_KEY", "tvk_for_b");
        assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_none());
    }

    /// `init --global` migrates the current directory's legacy
    /// `default_project` (VIS-1256: `init` in any mode).
    #[tokio::test]
    async fn migrate_cwd_config_migrates_the_dirs_config() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("umbrella");
        fs::create_dir_all(dir.join(".tracevault")).unwrap();
        let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
            "200 OK",
            &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
        )]);
        fs::write(
            dir.join(".tracevault/config.toml"),
            format!("server_url = \"{base}\"\napi_key = \"tvk_x\"\ndefault_project = \"visdom\"\n"),
        )
        .unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.remove("TRACEVAULT_API_KEY");
        _guard.remove("TRACEVAULT_SERVER_URL");

        migrate_cwd_config(&dir).await.unwrap();

        let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
        assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
        assert_eq!(cfg.default_project, None);
    }

    /// Unknown and ambiguous names fail with nothing written.
    #[tokio::test]
    async fn init_workspace_unknown_or_ambiguous_name_writes_nothing() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        for name in ["nope", "dup"] {
            let tmp = tempfile::tempdir().unwrap();
            let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
                "200 OK",
                r#"[{"id":"00000000-0000-4000-8000-000000000001","name":"dup"},{"id":"00000000-0000-4000-8000-000000000002","name":"dup"}]"#,
            )]);
            let mut _guard = crate::test_helpers::EnvVarGuard::new();
            _guard.set("XDG_CONFIG_HOME", tmp.path());
            _guard.set("TRACEVAULT_API_KEY", "tok");
            _guard.remove("TRACEVAULT_SERVER_URL");

            let err = init_workspace(tmp.path(), name, Some(&base))
                .await
                .unwrap_err();
            assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
            assert!(!tmp.path().join(".tracevault").exists(), "{name}");
        }
    }

    /// Inside a git repo, only its root may be bound: the hook reads the
    /// repo root's config, so a binding in a sub-directory would be dead.
    #[tokio::test]
    async fn init_workspace_refuses_a_git_subdirectory() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        let sub = tmp.path().join("pkg");
        fs::create_dir_all(&sub).unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("TRACEVAULT_API_KEY", "tok");
        _guard.remove("TRACEVAULT_SERVER_URL");

        let err = init_workspace(&sub, "visdom", Some("http://127.0.0.1:9"))
            .await
            .unwrap_err();
        assert!(err.to_string().contains("inside the git repo"), "{err}");
        assert!(!sub.join(".tracevault").exists());
    }

    /// A re-run that cannot reach the server keeps the bound `repo_id`: it is
    /// never dropped, not even until registration would re-add it.
    #[tokio::test]
    async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
        fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
        fs::write(
            tmp.path().join(".tracevault/config.toml"),
            format!("repo_id = \"{STRAY}\"\n"),
        )
        .unwrap();

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![http_response("500 Internal Server Error", "{}")],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(STRAY));
        assert!(!registered(&requests));
    }

    /// Several records, nothing says which: no guess, no new record.
    #[tokio::test]
    async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                resolve_remote_ok(),
                remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
            ],
        )
        .await;

        assert_eq!(repo_id, None);
        assert!(!registered(&requests));
    }

    /// A known codebase with no live repo (e.g. its last one was tombstoned)
    /// still registers.
    #[tokio::test]
    async fn init_registers_for_a_codebase_without_live_repos() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![
                resolve_remote_ok(),
                remote_detail(&[]),
                http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
            ],
        )
        .await;

        assert_eq!(repo_id.as_deref(), Some(CANONICAL));
        assert!(registered(&requests));
    }

    /// If the server cannot say what it has, init does not register blind.
    #[tokio::test]
    async fn init_does_not_register_when_the_remote_check_fails() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        crate::test_helpers::init_git_repo(tmp.path());
        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");

        let (repo_id, requests) = init_against(
            tmp.path(),
            vec![http_response("500 Internal Server Error", "{}")],
        )
        .await;

        assert_eq!(repo_id, None);
        assert!(!registered(&requests));
    }
}