tracevault-cli 0.29.6

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
3503
//! `tracevault status` — surface every piece of state a user might need to
//! debug "why doesn't it work". The command runs read-only checks across
//! credentials, the project tree, and the server, and prints a grouped
//! report with ✓ / ✗ / ! markers. Exits non-zero if anything actionable is
//! broken.

use crate::api_client::{ApiClient, GetMeError};
use crate::config::TracevaultConfig;
use crate::credentials::{Credential, Credentials};
use crate::resolution::{
    effective_project, git_remote_url, resolve_effective_project, ProjectResolveInputs,
    ProjectSource,
};
use std::fs;
use std::path::{Path, PathBuf};

const ANSI_GREEN: &str = "\x1b[32m";
const ANSI_RED: &str = "\x1b[31m";
const ANSI_YELLOW: &str = "\x1b[33m";
const ANSI_DIM: &str = "\x1b[2m";
const ANSI_RESET: &str = "\x1b[0m";

/// Severity classification of a single check. Anything at `Error` level
/// bumps the final exit code to 1.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Level {
    Ok,
    Warn,
    Error,
    /// Check skipped because a prerequisite failed (e.g. can't validate
    /// token if no token was found). Does not affect exit code.
    Skip,
}

#[derive(Debug)]
struct Check {
    label: String,
    level: Level,
    detail: String,
}

impl Check {
    fn ok(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Ok,
            detail: detail.into(),
        }
    }
    fn warn(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Warn,
            detail: detail.into(),
        }
    }
    fn err(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Error,
            detail: detail.into(),
        }
    }
    fn skip(label: impl Into<String>, detail: impl Into<String>) -> Self {
        Self {
            label: label.into(),
            level: Level::Skip,
            detail: detail.into(),
        }
    }
}

fn marker(l: Level) -> &'static str {
    match l {
        Level::Ok => "\x1b[32m✓\x1b[0m",
        Level::Warn => "\x1b[33m!\x1b[0m",
        Level::Error => "\x1b[31m✗\x1b[0m",
        Level::Skip => "\x1b[2m·\x1b[0m",
    }
}

fn print_section(title: &str, checks: &[Check]) {
    println!("{ANSI_DIM}──{ANSI_RESET} {title}");
    for c in checks {
        if c.detail.is_empty() {
            println!("  {} {}", marker(c.level), c.label);
        } else {
            println!(
                "  {} {:<32} {ANSI_DIM}{}{ANSI_RESET}",
                marker(c.level),
                c.label,
                c.detail
            );
        }
    }
    println!();
}

// --- Authentication ---

struct AuthContext {
    server_url: Option<String>,
    /// The resolved credential, if any. Cloned per client construction
    /// because a Keycloak session may be refreshed by the checks below.
    credential: Option<Credential>,
    source: &'static str, // "env", "credentials", or "none"
    email_from_creds: Option<String>,
    /// `(file's server_url, TRACEVAULT_SERVER_URL)` when the saved credential
    /// is for a different instance than the env var targets.
    ///
    /// This inspector deliberately reports the FILE's URL (that is the
    /// credential it validates), so without this field `status` would print a
    /// green "Logged in" while every other command refuses to run — the exact
    /// situation someone runs `status` to diagnose.
    url_override_mismatch: Option<(String, String)>,
}

/// `config_server_url`/`config_api_key` are the lowest rung, mirroring
/// `credentials::resolve_credentials`. Without them this inspector reported a
/// repo authenticated purely through `.tracevault/config.toml` as "no
/// credentials found" and exited non-zero, while every command using that same
/// config worked — the inspector called a working setup broken.
fn resolve_auth(config_server_url: Option<&str>, config_api_key: Option<&str>) -> AuthContext {
    // Env var wins. Match the server-side resolution order in
    // resolve_credentials (env > creds), except we treat the env var as
    // authoritative without looking at the credentials file email.
    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
    let env_url = std::env::var("TRACEVAULT_SERVER_URL").ok();

    if let Some(token) = env_key {
        return AuthContext {
            // `.or(config)` because `resolve_credentials` resolves the URL and
            // the credential independently: an env key with the URL pinned only
            // in the config is a working setup, not "no server URL".
            server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
            credential: Some(Credential::ApiKey(token)),
            source: "env (TRACEVAULT_API_KEY)",
            email_from_creds: None,
            // An explicitly supplied API key may target any URL by design.
            url_override_mismatch: None,
        };
    }

    let creds = Credentials::load();
    if let Some(c) = creds {
        let source = match &c.auth {
            Some(_) => "credentials file (Keycloak session)",
            None => "credentials file (API key)",
        };
        // Any credential read from the FILE is instance-bound — a `tvk_` key as
        // much as a Keycloak session (see `api_client::resolve_credentials`,
        // which refuses this pairing for both).
        let url_override_mismatch = env_url.filter(|env| {
            c.credential().is_some() && !crate::credentials::same_server(&c.server_url, env)
        });
        return AuthContext {
            server_url: Some(c.server_url.clone()),
            credential: c.credential(),
            source,
            // An empty email means a login saved credentials before
            // `/auth/me` could resolve the identity (e.g. the account lacks
            // a `tracevault` grant); there is nothing to compare against.
            email_from_creds: Some(c.email).filter(|e| !e.is_empty()),
            url_override_mismatch: url_override_mismatch.map(|env| (c.server_url, env)),
        };
    }

    // Lowest rung: a hand-authored `config.toml` may carry `api_key` and
    // `server_url`. Only reached when the env and the credentials file yielded
    // nothing, exactly as in `resolve_credentials`.
    AuthContext {
        server_url: env_url.or_else(|| config_server_url.map(str::to_string)),
        credential: config_api_key.map(|k| Credential::ApiKey(k.to_string())),
        source: if config_api_key.is_some() {
            "project config (.tracevault/config.toml)"
        } else {
            "none"
        },
        email_from_creds: None,
        url_override_mismatch: None,
    }
}

async fn auth_checks(auth: &AuthContext, config_server_url: Option<&str>) -> Vec<Check> {
    let mut out = Vec::new();

    match (auth.credential.as_ref(), auth.server_url.as_ref()) {
        (None, _) => {
            out.push(Check::err(
                "Logged in",
                "no credentials found. Run `tracevault login --server-url <URL>`.",
            ));
            out.push(Check::skip("Token valid", "no token to check"));
            return out;
        }
        (Some(_), None) => {
            out.push(Check::err(
                "Logged in",
                "token found but no server URL (set TRACEVAULT_SERVER_URL)",
            ));
            out.push(Check::skip("Token valid", "no server URL to call"));
            return out;
        }
        (Some(_), Some(url)) => {
            out.push(Check::ok("Logged in", format!("{url} via {}", auth.source)));
        }
    }

    // Reported as an ERROR, not a warning: in this state every command that
    // needs auth refuses to run (see `api_client::resolve_credentials`), so
    // "everything is fine except this note" would be misleading.
    if let Some((file_url, env_url)) = &auth.url_override_mismatch {
        out.push(Check::err(
            "Server URL",
            format!(
                "TRACEVAULT_SERVER_URL is '{env_url}' but the saved login is for '{file_url}'. \
                 Commands will refuse to run rather than send that session's token to another \
                 instance. Unset TRACEVAULT_SERVER_URL, or run `tracevault login --server-url \
                 {env_url}`."
            ),
        ));
    }

    // Reported as a WARNING, not an error: unlike the override above, commands
    // still run — they just use the login's instance while the repo's config
    // says otherwise. Without this the inspector is actively misleading: it
    // reads only the credentials file, so it would print a green "Logged in"
    // against a URL the repo never asked for. Shares
    // `credentials::config_url_conflict` with the resolution itself so the two
    // cannot drift apart.
    if let Some((file_url, config_url)) = crate::credentials::config_url_conflict(
        config_server_url,
        auth.server_url.as_deref(),
        std::env::var("TRACEVAULT_SERVER_URL").is_ok(),
    ) {
        out.push(Check::warn(
            "Server URL",
            format!(
                ".tracevault/config.toml pins '{config_url}' but the saved login is for \
                 '{file_url}'. The config URL is ignored — commands use '{file_url}'. Run \
                 `tracevault login --server-url {config_url}` to use the repo's instance, or \
                 remove `server_url` from .tracevault/config.toml."
            ),
        ));
    }

    let server_url = auth.server_url.as_ref().unwrap();
    let client = ApiClient::with_credential(server_url, auth.credential.clone());
    match client.get_me().await {
        Ok(me) => {
            let who = me.name.unwrap_or_else(|| me.email.clone());
            let detail = match &me.role {
                Some(role) => format!("{who} <{}> (role: {role})", me.email),
                None => format!("{who} <{}>", me.email),
            };
            out.push(Check::ok("Token valid", detail));

            if let Some(cached) = &auth.email_from_creds {
                if cached != &me.email {
                    out.push(Check::warn(
                        "Credentials cache",
                        format!(
                            "cached email '{cached}' differs from server '{}' — re-run login",
                            me.email
                        ),
                    ));
                }
            }
        }
        Err(GetMeError::Unauthorized) => {
            out.push(Check::err(
                "Token valid",
                "rejected by server (expired or revoked). Run `tracevault login` again.",
            ));
        }
        // A valid token whose account isn't authorized. Re-running login
        // would NOT help, so this must not say "log in again".
        Err(GetMeError::Forbidden(_)) => {
            out.push(Check::err(
                "Account authorized",
                "the token is valid but this account has no `tracevault` grant in Control Plane — \
                 ask an administrator to grant it (or the `ai-tracing-admin` realm role).",
            ));
        }
        Err(GetMeError::Network(msg)) => {
            out.push(Check::warn(
                "Server reachable",
                format!("{msg} — cannot confirm token validity"),
            ));
        }
        Err(GetMeError::Server(msg)) => {
            out.push(Check::warn("Token valid", format!("server error: {msg}")));
        }
    }
    out
}

// --- Project ---

/// Subset of project checks that don't need network. Returns the loaded
/// config if present so later sections can reuse it.
fn project_checks(
    project_root: &Path,
    global_settings: Option<&Path>,
    has_global: bool,
    has_binding: bool,
) -> (Vec<Check>, Option<TracevaultConfig>) {
    let mut out = Vec::new();

    let is_git = project_root.join(".git").exists();
    if is_git {
        out.push(Check::ok(
            "Git repository",
            project_root.display().to_string(),
        ));
    } else if has_global || has_binding {
        out.push(Check::skip(
            "Git repository",
            "not a git repo (global/workspace mode)",
        ));
    } else {
        out.push(Check::err(
            "Git repository",
            "current directory is not a git repo",
        ));
    }

    let tv_present = project_root.join(".tracevault").exists();
    out.push(tracevault_init_check(tv_present, has_global, has_binding));

    // Distinguish "no config.toml" (expected in workspace/detached mode —
    // just a warning) from "config.toml present but malformed" (a genuine
    // error) via `try_load`, rather than the lenient `load` which collapses
    // both cases to `None`.
    let config = match TracevaultConfig::try_load(project_root) {
        Ok(Some(c)) => {
            let url = c.server_url.as_deref().unwrap_or("<unset>");
            out.push(Check::ok("Project config", format!("server={url}")));
            Some(c)
        }
        Ok(None) => {
            if tv_present {
                out.push(Check::warn(
                    "Project config",
                    "No .tracevault/config.toml — run `tracevault init`, or use workspace mode (`tracevault repo status`).",
                ));
            }
            None
        }
        Err(e) => {
            out.push(Check::err(
                "Project config",
                format!(".tracevault/config.toml malformed: {e}"),
            ));
            None
        }
    };

    if tv_present {
        // Hooks — presence of our markers, not just existence of the hook file.
        out.push(git_hook_check(
            project_root,
            "pre-push",
            "# tracevault:enforce",
        ));
        out.push(git_hook_check(
            project_root,
            "post-commit",
            "# tracevault:post-commit",
        ));
    } else if has_global || has_binding {
        out.push(Check::skip(
            "Git hooks",
            "not used in global/workspace mode",
        ));
    } else {
        out.push(Check::skip(
            "Git hooks",
            "not installed (no .tracevault/ — run `tracevault init`)",
        ));
    }

    out.push(claude_hook_check_in(
        &project_root.join(".claude"),
        global_settings,
    ));

    (out, config)
}

fn git_hook_check(project_root: &Path, name: &str, marker: &str) -> Check {
    let path = project_root.join(".git/hooks").join(name);
    let label = format!("Git hook: {name}");
    if !path.exists() {
        return Check::warn(
            label,
            format!(".git/hooks/{name} missing — rerun `tracevault init`"),
        );
    }
    match fs::read_to_string(&path) {
        Ok(s) if s.contains(marker) => Check::ok(label, "installed"),
        Ok(_) => Check::warn(
            label,
            format!("{name} exists but no tracevault block — rerun `tracevault init`"),
        ),
        Err(e) => Check::warn(label, format!("cannot read hook: {e}")),
    }
}

/// True if a Claude settings.json body wires any tracevault hook command.
fn settings_has_tracevault_hooks(contents: &str) -> bool {
    contents.contains("tracevault stream")
        || contents.contains("tracevault session-start")
        || contents.contains("tracevault user-prompt")
}

/// Whether a Claude `settings.json` wires tracevault hooks — distinguishing a
/// genuinely-absent file from one that exists but can't be read, so an
/// IO/permission error isn't silently reported as "not installed".
enum SettingsHooks {
    Present,
    NoHooks,
    Missing,
    Unreadable(String),
}

fn read_settings_hooks(path: &Path) -> SettingsHooks {
    match fs::read_to_string(path) {
        Ok(s) if settings_has_tracevault_hooks(&s) => SettingsHooks::Present,
        Ok(_) => SettingsHooks::NoHooks,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => SettingsHooks::Missing,
        Err(e) => SettingsHooks::Unreadable(e.to_string()),
    }
}

/// Check a global `~/.claude/settings.json` for the `init --global` install.
/// Absent / no tracevault hooks → Skip (a global install is optional); an
/// existing-but-unreadable file → Warn (don't hide a permission/IO problem).
fn global_hook_check_in(settings_path: &Path) -> Check {
    match read_settings_hooks(settings_path) {
        SettingsHooks::Present => Check::ok(
            "Global install",
            "hooks installed in ~/.claude/settings.json",
        ),
        SettingsHooks::NoHooks => Check::skip(
            "Global install",
            "~/.claude/settings.json has no tracevault hooks",
        ),
        SettingsHooks::Missing => Check::skip("Global install", "no ~/.claude/settings.json"),
        SettingsHooks::Unreadable(e) => Check::warn(
            "Global install",
            format!("cannot read ~/.claude/settings.json: {e}"),
        ),
    }
}

/// Whether Claude Code's cost reaches TraceVault over OpenTelemetry
/// (`init --claude-telemetry`), read from `~/.claude/settings.json` and this
/// process's `OTEL_*` environment. Off or exported elsewhere → Skip (both are
/// legitimate); an incomplete install, one for another server than the login,
/// or our token also going to someone else's exporter → Warn.
fn claude_telemetry_check_in(
    settings_path: &Path,
    server_url: Option<&str>,
    env: &crate::commands::claude_telemetry::Environment,
) -> Check {
    use crate::commands::claude_telemetry::{inspect, logs_endpoint, TelemetryState};
    const LABEL: &str = "Claude Code telemetry";
    let settings = match fs::read_to_string(settings_path) {
        Ok(s) => match serde_json::from_str::<serde_json::Value>(&s) {
            Ok(v) => v,
            Err(e) => {
                return Check::warn(LABEL, format!("cannot parse ~/.claude/settings.json: {e}"))
            }
        },
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => serde_json::json!({}),
        Err(e) => return Check::warn(LABEL, format!("cannot read ~/.claude/settings.json: {e}")),
    };
    let expected = server_url.map(logs_endpoint);
    match inspect(&settings, env, expected.as_deref()) {
        TelemetryState::Off => Check::skip(LABEL, "off (enable with `tracevault telemetry on`)"),
        TelemetryState::Foreign { reasons, ours_too } => {
            let detail = format!("exported elsewhere: {}", reasons.join("; "));
            if ours_too {
                Check::warn(
                    LABEL,
                    format!(
                        "{detail} — these exporters also receive TraceVault's otel-headers \
                         token; remove them or TraceVault's otelHeadersHelper"
                    ),
                )
            } else {
                Check::skip(LABEL, format!("{detail} (see README: collector route)"))
            }
        }
        TelemetryState::Ours { missing, .. } if !missing.is_empty() => Check::warn(
            LABEL,
            format!(
                "incomplete ({} missing or changed): re-run `tracevault init --claude-telemetry`",
                missing.join(", ")
            ),
        ),
        TelemetryState::Ours { endpoint, .. } => {
            let endpoint = endpoint.unwrap_or_default();
            match expected {
                Some(expected) if expected != endpoint => Check::warn(
                    LABEL,
                    format!(
                        "exports to {endpoint}, but you are logged in to {}: re-run \
                         `tracevault init --claude-telemetry`",
                        server_url.unwrap_or_default()
                    ),
                ),
                _ => Check::ok(LABEL, format!("exports cost to {endpoint}")),
            }
        }
    }
}

/// Add what the install state knows to the telemetry check (VIS-1109): that
/// the user opted out (so it stays off across upgrades), or that an upgrade
/// turned it on without being asked.
fn with_telemetry_choice(mut check: Check, state: &crate::install_state::InstallState) -> Check {
    match check.level {
        Level::Skip if state.claude_telemetry_opt_out && check.detail.starts_with("off") => {
            check.detail =
                "off — you opted out, upgrades keep it off (`tracevault telemetry on` to enable)"
                    .to_string();
        }
        Level::Ok => {
            if let Some(version) = &state.telemetry_auto_enabled {
                check.detail.push_str(&format!(
                    " — turned on automatically by the upgrade to {version} \
                     (`tracevault telemetry off` to disable)"
                ));
            }
        }
        _ => {}
    }
    check
}

/// The telemetry check as `status` shows it, on one line, for `tracevault
/// telemetry status`.
pub fn telemetry_status_line(server_url: Option<&str>) -> String {
    let Some(settings) = dirs::home_dir().map(|h| h.join(".claude").join("settings.json")) else {
        return "Claude Code telemetry: cannot determine home directory".to_string();
    };
    let check = with_telemetry_choice(
        claude_telemetry_check_in(
            &settings,
            server_url,
            &crate::commands::claude_telemetry::Environment::current(
                settings.parent().unwrap_or(&settings),
            ),
        ),
        &crate::install_state::load_in(&crate::config::tv_config_root()),
    );
    format!("{}: {}", check.label, check.detail)
}

/// The per-repo Claude settings files `init` can write hooks into
/// (`--claude-settings shared|local`), in the order they are reported.
const REPO_CLAUDE_SETTINGS: [&str; 2] = ["settings.json", "settings.local.json"];

/// Claude Code hooks may live per-repo (`<repo>/.claude/settings.json` or
/// `settings.local.json`, per `init --claude-settings`) OR globally
/// (`~/.claude/settings.json`, `init --global`). Ok if ANY of them wires
/// tracevault; an existing-but-unreadable settings file is surfaced as a Warn
/// with the path (not a generic "not registered"); Warn if none wires it.
fn claude_hook_check_in(repo_claude_dir: &Path, global_settings: Option<&Path>) -> Check {
    let repo: Vec<(&str, SettingsHooks)> = REPO_CLAUDE_SETTINGS
        .iter()
        .map(|name| (*name, read_settings_hooks(&repo_claude_dir.join(name))))
        .collect();
    if let Some((name, _)) = repo
        .iter()
        .find(|(_, h)| matches!(h, SettingsHooks::Present))
    {
        return Check::ok("Claude Code hooks", format!("registered in .claude/{name}"));
    }
    let global = global_settings.map(read_settings_hooks);
    if matches!(global, Some(SettingsHooks::Present)) {
        return Check::ok("Claude Code hooks", "via global install (see Installation)");
    }
    for (name, hooks) in &repo {
        if let SettingsHooks::Unreadable(e) = hooks {
            return Check::warn(
                "Claude Code hooks",
                format!("cannot read <repo>/.claude/{name}: {e}"),
            );
        }
    }
    if let Some(SettingsHooks::Unreadable(e)) = &global {
        return Check::warn(
            "Claude Code hooks",
            format!("cannot read ~/.claude/settings.json: {e}"),
        );
    }
    Check::warn(
        "Claude Code hooks",
        "not registered in <repo>/.claude/settings.json, <repo>/.claude/settings.local.json or ~/.claude/settings.json (capture will miss some events)",
    )
}

/// Severity of the "TraceVault initialized" check. A per-repo `.tracevault/`
/// present is always Ok. Absent is EXPECTED (Skip) when the user has a global
/// install or an active workspace binding; only a truly-unconfigured setup
/// (none of the three) is an Error.
fn tracevault_init_check(tv_dir_present: bool, has_global: bool, has_binding: bool) -> Check {
    if tv_dir_present {
        Check::ok("TraceVault initialized", ".tracevault/ present")
    } else if has_global || has_binding {
        Check::skip(
            "TraceVault initialized",
            "no per-repo .tracevault/ — global/workspace mode",
        )
    } else {
        Check::err(
            "TraceVault initialized",
            "not set up: run `tracevault init` (per-repo) or `tracevault init --global`",
        )
    }
}

/// The most-recently-modified session in `sessions_dir` that HAS an active
/// binding, as `(session_id, binding)`. Scans ALL session files (newest first)
/// rather than only the newest file, so a real binding isn't missed when the
/// most-recently-touched session happens to have none. `None` if no session
/// carries an active binding.
fn latest_active_binding_in(
    sessions_dir: &Path,
) -> Option<(String, crate::session_state::RepoBinding)> {
    let mut sessions: Vec<(std::time::SystemTime, String)> = Vec::new();
    for entry in fs::read_dir(sessions_dir).ok()?.flatten() {
        let name = entry.file_name();
        let name = name.to_str().unwrap_or("");
        let Some(id) = name.strip_suffix(".toml") else {
            continue;
        };
        if id.is_empty() {
            continue;
        }
        let Ok(mtime) = entry.metadata().and_then(|m| m.modified()) else {
            continue;
        };
        sessions.push((mtime, id.to_string()));
    }
    sessions.sort_by_key(|(mtime, _)| std::cmp::Reverse(*mtime)); // newest first
    for (_, id) in sessions {
        if let Some(b) = crate::session_state::load_from(sessions_dir, &id).active {
            return Some((id, b));
        }
    }
    None
}

/// One clear rule for the "Workspace repo" check, shared by both arms of
/// [`workspace_binding_check_in`] below: `Ok` only when
/// `binding_repo_id_is_valid` — the SAME predicate `attribution_for` filters
/// through before honoring a repo binding — passes. A corrupted/hand-edited
/// session-state file can carry a `repo_id` that isn't a real UUID;
/// `attribution_for` silently drops such a binding, so showing it as `Ok`
/// here would be green for something the hook will not honor.
/// `detail_suffix` carries the arm-specific "(session {id})" / "most recent
/// session..." wording; the base "repo {id} via repo switch" text stays
/// identical to before this check existed.
fn workspace_repo_binding_check(
    b: &crate::session_state::RepoBinding,
    detail_suffix: &str,
) -> Check {
    let base = format!("repo {} via repo switch{detail_suffix}", b.repo_id);
    if crate::commands::stream::binding_repo_id_is_valid(&b.repo_id) {
        Check::ok("Workspace repo", base)
    } else {
        Check::warn(
            "Workspace repo",
            format!(
                "{base} — this repo_id is not a valid id and will be dropped at capture time; run `tracevault repo switch <path>` to rewrite it"
            ),
        )
    }
}

/// Resolve the workspace binding for `status` — the repo axis of
/// attribution. With an explicit session id the user named a target, but a
/// missing binding is only a Skip here: this check sees the repo axis alone,
/// so it cannot tell a genuinely unbound machine (nothing will record) from
/// one that's fully attributed via the project axis (`project switch
/// --user`). Only [`recording_check`], which sees both axes, can make that
/// call — so it also owns the escalation and the remediation hint; this
/// check states the bare fact and stops (in particular, it does NOT suggest
/// `tracevault repo switch …`: since v0.28.0 that command takes a checkout
/// path and rejects binding by session name, which is exactly the situation
/// on the repo-less machine this check is describing).
///
/// Without an explicit id, best-effort scan across all sessions (state is
/// global): show the most recent that HAS a binding, and stay quiet (Skip)
/// when none does — so a bound-mode user with a stray empty session file
/// isn't warned. Returns the Check AND the resolved binding (reused by the
/// caller as the `has_binding` mode signal).
fn workspace_binding_check_in(
    sessions_dir: &Path,
    explicit_session_id: Option<&str>,
) -> (Check, Option<crate::session_state::RepoBinding>) {
    match explicit_session_id {
        Some(id) => {
            let state = crate::session_state::load_from(sessions_dir, id);
            match state.active {
                Some(b) => {
                    let check = workspace_repo_binding_check(&b, &format!(" (session {id})"));
                    (check, Some(b))
                }
                None => (
                    Check::skip(
                        "Workspace repo",
                        format!("session {id} has no active binding"),
                    ),
                    None,
                ),
            }
        }
        None => match latest_active_binding_in(sessions_dir) {
            Some((id, b)) => {
                let suffix = format!(
                    " — most recent session with a binding: {id} (may be another repo; pass --session-id to target one)"
                );
                let check = workspace_repo_binding_check(&b, &suffix);
                (check, Some(b))
            }
            None => (
                Check::skip("Workspace repo", "no active workspace binding found"),
                None,
            ),
        },
    }
}

// --- Attribution: project axis + the combined recording verdict ---

/// The already-resolved project-attribution outcome consumed by
/// [`project_binding_check`]: either the full server-aware chain
/// (`resolve_effective_project`) or, when no API client is available, the
/// pure local tiers (`effective_project`) wrapped in `Ok` so both code paths
/// in `run_status` produce the same shape. Reuses `resolution.rs`'s own
/// `Option<(ProjectBinding, ProjectSource)>`/`Box<dyn Error>` types rather
/// than introducing a parallel enum, so `ProjectSource`'s tier labels (and
/// its `Display` impl) stay the single source of truth.
type ProjectOutcome = Result<
    Option<(crate::session_state::ProjectBinding, ProjectSource)>,
    Box<dyn std::error::Error>,
>;

/// Display label for a project binding: the friendly name, falling back to
/// the id when unset. A `Deduced` binding carries an empty `project_name`
/// (`resolve_effective_project` doesn't enrich it) and is shown by id rather
/// than name: the credentialed arm below only ever calls `list_projects`
/// when a config `default_project` is set, so a name lookup for `Deduced` is
/// not reliably available — falling back to the id keeps this consistent
/// across both cases rather than sometimes showing a name and sometimes an
/// id depending on unrelated config state.
fn project_label(binding: &crate::session_state::ProjectBinding) -> &str {
    if binding.project_name.is_empty() {
        &binding.project_id
    } else {
        &binding.project_name
    }
}

/// Maps the resolved project-attribution outcome to the "Project" check.
/// Network-free — the resolution already happened in `run_status`. It does
/// read `TRACEVAULT_PROJECT` (via `env_project_binding`) for the `Env` arm;
/// see the rule below for why that read is the point.
/// DISPLAY ONLY: this outcome never feeds [`recording_check`]'s verdict — see
/// that function's doc comment for why.
///
/// One rule decides `Ok`: the tier must be one `capture_project` itself
/// honors (flag/subagent/`Env`/session-active/user-default — NOT
/// `ConfigDefault` or `Deduced`, which it excludes/never produces), AND the
/// binding must be one `capture_project` would not then drop. It drops a
/// `project_id` that fails `.parse::<uuid::Uuid>()` (its own last act before
/// returning the binding), and — at the `Env` rung specifically — it never
/// forms a binding at all unless the RAW `TRACEVAULT_PROJECT` value is a
/// UUID, because `env_project_binding` is UUID-only by design (a name would
/// need a per-event `list_projects` round trip).
///
/// That last condition is why the `Env` arm consults
/// [`crate::commands::stream::env_project_binding`] rather than testing the
/// RESOLVED binding's id: a NAME in `TRACEVAULT_PROJECT` is resolved here for
/// display (this command has a client; the hook does not), so its resolved id
/// IS a valid UUID and would sail through an id-only test — reporting green
/// for a tier the wire silently ignores. Asking the capture path's own reader
/// is what makes the two unable to drift.
///
/// Any of those failures renders `Warn`, not `Ok` — showing green for a
/// binding the capture path will not honor is the exact confusion this
/// command exists to eliminate (a hand-edited or corrupted
/// `user_project.toml` with a garbage `project_id` is a real way to hit the
/// id-validity half of this).
///
/// `Err` — the ambiguous "this repo belongs to multiple projects" case, or
/// any transport/5xx failure of the deduction call (`resolve_effective_project`
/// propagates both the same way via `?`) — is also at most a `Warn`, never an
/// `Error`: this axis is display-only, so a network blip must never be able
/// to redden the exit code on its own. Matches how the rest of `status`
/// treats transport failure (`GetMeError::Network`, a failed `list_repos`) as
/// Warn, not Error.
///
/// `None` (nothing bound on this axis) is a `Skip` — severity for "nothing
/// will be recorded" is [`recording_check`]'s job, since only it consults the
/// actual recording gate.
///
/// DELIBERATE GAP — this reports WHICH project and WHICH tier, and whether
/// ingest honours that tier. It does not report the attribution MODE
/// (`derived`/`explicit`) or any persisted-force detail, and it is not meant
/// to: `commands::project`'s `status` owns that, via the one function that
/// decides the header (`commands::stream::attribution_mode`) plus
/// `format_force_line`. Reproducing either here would mean a second surface
/// that has to keep agreeing with the wire, and the whole shape of VIS-305's
/// attribution reporting is that exactly one place answers "derived or
/// explicit?" — the bugs this branch fixed were all second answers drifting
/// from the first. The README says the same split rather than promising
/// parity, the way `online_project_outcome`'s unresolvable-name case is
/// documented as a gap instead of claimed as coverage. If the mode ever does
/// belong in the full diagnostic, it must arrive by CALLING
/// `attribution_mode` — never by re-deriving the verdict here.
fn project_binding_check(outcome: &ProjectOutcome) -> Check {
    match outcome {
        Err(e) => Check::warn("Project", e.to_string()),
        Ok(None) => Check::skip(
            "Project",
            "not bound — run `tracevault project switch --user \"<name>\"`, or `tracevault repo switch <path>` inside a checkout",
        ),
        Ok(Some((binding, source))) => {
            // `Env` (`TRACEVAULT_PROJECT`) joined this list once
            // `commands::stream::capture_project` started passing
            // `env_project_binding()` into `effective_project` — it is now
            // one of the tiers capture time actually resolves, same as
            // Subagent/SessionActive/UserDefault, so it must read Ok here
            // too or this Check would warn "not used for attribution at
            // capture time" about a tier that is, in fact, used.
            let honored_tier = matches!(
                source,
                ProjectSource::ProjectFlag
                    | ProjectSource::Subagent
                    | ProjectSource::Env
                    | ProjectSource::SessionActive
                    | ProjectSource::Workspace
                    | ProjectSource::UserDefault
            );
            // ...but only for the form the capture path can actually use. A
            // NAME resolves here (a client is in scope) and nowhere on the
            // wire, so asking `env_project_binding` — the hook's own reader
            // of this same var — is the only test that can't go green on a
            // tier the hook ignores.
            let env_name_form = *source == ProjectSource::Env
                && crate::commands::stream::env_project_binding().is_none();
            let label = project_label(binding);
            if env_name_form {
                Check::warn(
                    "Project",
                    format!(
                        "{label} — {source}, resolved for display only: the capture path honours only the UUID form of TRACEVAULT_PROJECT, so a NAME is ignored there and attribution falls through to the next tier — export TRACEVAULT_PROJECT={} instead, or bind it with `tracevault project switch <name>`",
                        binding.project_id
                    ),
                )
            } else if !honored_tier {
                Check::warn(
                    "Project",
                    format!(
                        "{label} — {source}, not used for attribution at capture time; set one explicitly with `tracevault project switch <name>` or --project"
                    ),
                )
            } else if binding.project_id.parse::<uuid::Uuid>().is_err() {
                Check::warn(
                    "Project",
                    format!(
                        "{label} — {source}, but the saved project_id is not a valid id and will be dropped at capture time; run `{}` to rewrite it",
                        source.rewrite_command()
                    ),
                )
            } else {
                Check::ok("Project", format!("{label} — {source}"))
            }
        }
    }
}

/// Surfaces a `.tracevault/config.toml` that still carries the legacy
/// `default_project` NAME (VIS-1256). Ingest never resolves names, so the
/// name contributes nothing to attribution until `init`/`sync` migrate it to
/// `project_id`; this command therefore does not resolve it either (that
/// would report a project ingest never attributes to — VIS-316) and says so
/// instead. `None` when there is nothing legacy in the config. Shares its
/// wording with `commands::project`'s `status` via
/// [`crate::commands::migrate::legacy_default_project_notice`].
fn legacy_default_project_check(config: Option<&TracevaultConfig>) -> Option<Check> {
    let notice = crate::commands::migrate::legacy_default_project_notice(config?)?;
    Some(Check::warn("Project default", notice))
}

/// The one check that reflects whether anything will record this session at
/// all. Takes the ALREADY-RESOLVED [`crate::commands::stream::Attribution`] —
/// the exact same value `attribution_for(resolve_stream_binding(...),
/// capture_project(...))` the `stream` hook itself computes before deciding
/// to no-op — rather than a hand-built approximation of the two axes. Coupling
/// to the hook's own gate this way is load-bearing: the repo axis has tiers
/// (`repo switch --user`, a config with no `repo_id`) and the project axis has
/// tiers (`project switch --user` with no credential, `Deduced`/`ConfigDefault`
/// display values `capture_project` doesn't honor) that a hand-rolled
/// `repo_bound`/`project_bound` pair would have to re-derive and could get
/// wrong; calling the real functions means the two can't drift apart.
///
/// Only fires for an explicitly named session (`--session-id` /
/// `$TRACEVAULT_SESSION_ID`, i.e. `session_id.is_some()`); without one,
/// [`checkout_recording_check`] answers the session-independent question
/// instead. Pure and
/// network-free: `attribution` is computed by the caller from purely local
/// tiers (mirroring the hook), so this check — and the verdict it drives —
/// can never be swayed by a network hiccup.
fn recording_check(
    session_id: Option<&str>,
    attribution: Option<&crate::commands::stream::Attribution>,
) -> Option<Check> {
    let id = session_id?;
    if attribution.is_some() {
        return None;
    }
    Some(Check::err(
        "Recording",
        format!(
            "nothing will be recorded — session {id} is bound on neither the repo nor the \
             project axis; run `tracevault project switch --user \"<name>\"` on a repo-less \
             machine, or `tracevault repo switch <path>` inside a checkout"
        ),
    ))
}

/// The session-independent half of the recording verdict: will a NEW session
/// started in this checkout record anything, before it runs `repo switch` or
/// `project switch`? Answers the question a plain terminal right after `init`
/// needs, where [`recording_check`] stays silent for lack of a session.
///
/// `attribution` must come from [`recording_attribution`] with NO session —
/// i.e. the hook's own gate fed only the tiers that exist before a session
/// does (bound config, `repo switch --user`, `TRACEVAULT_PROJECT`,
/// `project switch --user`). `config` only picks the wording and severity:
///
/// - a repo resolved → `Ok`;
/// - a `config.toml` is present (bound mode) but did not yield a usable repo
///   (`repo_id` missing or not a UUID) → `Error` when nothing resolved at all,
///   `Warn` when a project still catches the events (they ship, but not to
///   this repo) — the bound-mode user asked for repo attribution;
/// - no config and nothing resolved → `Warn`, not `Error`: in workspace mode
///   each session is bound by its hooks from the checkout's origin remote
///   (`auto_bind`) or by `repo switch`, so this is the expected state of a
///   plain terminal, but the user should still be told.
fn checkout_recording_check(
    attribution: Option<&crate::commands::stream::Attribution>,
    config: Option<&TracevaultConfig>,
) -> Check {
    use crate::commands::stream::Attribution;
    const LABEL: &str = "Recording";
    let repo_id_problem = config.and_then(|c| match c.repo_id.as_deref() {
        None => Some(".tracevault/config.toml has no repo_id".to_string()),
        Some(id) if !crate::commands::stream::binding_repo_id_is_valid(id) => Some(format!(
            ".tracevault/config.toml repo_id '{id}' is not a valid id"
        )),
        Some(_) => None,
    });
    match (attribution, repo_id_problem) {
        (Some(Attribution::Repo { repo_id, .. }), _) => Check::ok(
            LABEL,
            format!("new sessions in this checkout record to repo {repo_id}"),
        ),
        (Some(Attribution::ProjectOnly { project_id }), Some(problem)) => Check::warn(
            LABEL,
            format!(
                "{problem}: new sessions here record to project {project_id} only, not to this repo — run `tracevault sync` while logged in"
            ),
        ),
        (Some(Attribution::ProjectOnly { project_id }), None) => Check::ok(
            LABEL,
            format!("new sessions in this checkout record to project {project_id}"),
        ),
        (None, Some(problem)) => Check::err(
            LABEL,
            format!(
                "nothing will be recorded — {problem} and nothing else binds this checkout; run `tracevault sync` while logged in"
            ),
        ),
        (None, None) => Check::warn(
            LABEL,
            "no session named and nothing binds this checkout locally — a new session here is bound by its hooks to the repo of this checkout's origin remote if the server has it registered (otherwise run `tracevault sync` while logged in), or by `tracevault repo switch <path>`",
        ),
    }
}

/// Compose the "will this session record anything" gate exactly as
/// `run_status` and the `stream` hook do: load the session state, derive the
/// worktree key from `cwd`, extract a bound-config `RepoBinding` (if any),
/// and call `resolve_stream_binding` -> `capture_project` -> `attribution_for`
/// with those inputs. Pure and synchronous — network-free, matching the two
/// functions it calls. Returns the worktree key alongside the attribution so
/// callers that also need it (the project-display resolution in `run_status`)
/// don't re-shell out to git for the same value.
///
/// Deliberately derives its OWN worktree key from `cwd` (via
/// `crate::paths::worktree_toplevel`) rather than taking a pre-computed key as
/// a parameter: `cwd` is the toplevel a `stream` hook invocation actually runs
/// from, which for a LINKED worktree is NOT the same string as `project_root`
/// (the PRIMARY worktree's root, from `resolve_project_root`'s
/// `git rev-parse --git-common-dir`) — subagent overrides are keyed by the
/// former. Keeping the derivation INSIDE this function, with every attribution
/// test calling it directly rather than re-deriving the key by hand, is what
/// makes `recording_attribution_finds_subagent_override_via_linked_worktree_cwd`
/// able to catch a regression back to a primary-root path.
#[cfg(test)]
fn recording_attribution(
    sessions_dir: Option<&Path>,
    session_id: Option<&str>,
    cwd: &Path,
    config: Option<&TracevaultConfig>,
) -> (Option<crate::commands::stream::Attribution>, String) {
    let (recording, worktree) = recording_for(sessions_dir, session_id, cwd, config);
    (recording.attribution, worktree)
}

/// [`recording_attribution`] with whether its repo was inferred from the
/// checkout (VIS-1258) rather than bound — what `run_status` reports.
fn recording_for(
    sessions_dir: Option<&Path>,
    session_id: Option<&str>,
    cwd: &Path,
    config: Option<&TracevaultConfig>,
) -> (crate::commands::stream::Recording, String) {
    let session = match (sessions_dir, session_id) {
        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
        _ => crate::session_state::SessionState::default(),
    };
    let worktree = crate::paths::worktree_toplevel(cwd);
    let bound = config.and_then(crate::resolution::binding_from_config);
    let user_default_repo = crate::user_default::load();
    let recording = crate::commands::stream::recording_attribution_for(
        &session,
        &worktree,
        bound,
        user_default_repo,
        config.and_then(crate::resolution::project_from_config),
    );
    (recording, worktree)
}

/// The `Recording` line for a named session whose repo is inferred from this
/// checkout (VIS-1258), so `status` says it is inferred and not bound.
/// `None` when the repo is not inferred.
fn inferred_recording_check(recording: &crate::commands::stream::Recording) -> Option<Check> {
    use crate::commands::stream::Attribution;
    let (
        Some(Attribution::Repo {
            repo_id,
            project: Some(pid),
        }),
        Some(checkout),
    ) = (&recording.attribution, &recording.inferred_from)
    else {
        return None;
    };
    Some(Check::ok(
        "Recording",
        format!(
            "repo {repo_id} (inferred from the checkout {checkout}) in project {pid} — no repo \
             is bound, so each event is sent to the repo of the checkout it touches when that \
             repo is in the project, else to the project only"
        ),
    ))
}

/// The project axis's client-backed resolution: `TRACEVAULT_PROJECT` (UUID
/// or NAME, mirroring `commands::project`'s `status`) gets to consult
/// `list_projects` here, then the full server-aware precedence chain
/// (`resolve_effective_project`) runs. The workspace config tier is its
/// `project_id` only (`config_project`, read locally exactly as ingest reads
/// it); a legacy `default_project` NAME is never resolved here — the caller
/// reports it via `legacy_default_project_check`. Pulled out analogously to
/// [`offline_project_outcome`] so this branch is unit-testable without
/// driving all of `run_status`.
///
/// An unresolved `TRACEVAULT_PROJECT` NAME still gets no equivalent surfacing
/// here; it is silently dropped. That is now a real (if narrow) gap rather
/// than a matter of parity: `commands::project`'s `status` DOES warn for it
/// (as it already did for an unresolved `--project` and `default_project`).
/// It is survivable because the capture path drops a name too, so nothing
/// this command reports contradicts what the hook does — the operator is
/// simply not told why their variable had no effect. Closing it means a
/// `Check` of its own, deliberately left for a follow-up.
/// One project NAME looked up in the server's project list, as a binding.
///
/// Used for the NAME form of `TRACEVAULT_PROJECT` — a client is in scope
/// here, unlike on the capture path.
async fn resolve_name_via_client(
    client: &ApiClient,
    name: &str,
) -> Option<crate::session_state::ProjectBinding> {
    client.list_projects().await.ok().and_then(|items| {
        items
            .into_iter()
            .find(|p| p.name == name)
            .map(|p| crate::session_state::ProjectBinding {
                project_id: p.id.to_string(),
                project_name: p.name,
                updated_at: chrono::Utc::now().to_rfc3339(),
                forced_until: None,
            })
    })
}

async fn online_project_outcome(
    client: &ApiClient,
    config_project: Option<crate::session_state::ProjectBinding>,
    project_session: &crate::session_state::SessionState,
    worktree: &str,
    user_default_project: Option<crate::session_state::ProjectBinding>,
    project_git_url: Option<&str>,
) -> ProjectOutcome {
    // `TRACEVAULT_PROJECT`: a UUID or a NAME — a client is in scope here, so
    // both forms are honoured (unlike the capture path, which is UUID-only).
    //
    // The UUID form is whatever the HOOK reads, so it comes from
    // `env_project_binding` — the hook's own reader — rather than a fourth
    // hand-rolled copy of the same parse (the reason `offline_project_outcome`
    // already calls it). A non-empty value it declines is a name, which only
    // this command can resolve.
    let env_project = match crate::commands::stream::env_project_binding() {
        Some(binding) => Some(binding),
        None => match std::env::var("TRACEVAULT_PROJECT").ok() {
            Some(raw) if !raw.trim().is_empty() => {
                resolve_name_via_client(client, raw.trim()).await
            }
            _ => None,
        },
    };
    let inputs = ProjectResolveInputs {
        project_flag: None,
        env_project,
        session: project_session,
        worktree_path: Some(worktree),
        config_project,
    };
    resolve_effective_project(&inputs, user_default_project, project_git_url, client).await
}

/// The project axis's offline/no-client display fallback: the pure local
/// tiers (`effective_project`) plus the user-level project default as the
/// lowest tier. `effective_project` alone never consults the user default —
/// only `resolve_effective_project` (the networked chain) does — so without
/// this, a repo-less pod attributed solely via `project switch --user`, with
/// no credential/server URL configured, would show "not bound" on the
/// "Project" line while `recording_attribution` (which reads this same tier
/// independently via `capture_project`) correctly shows the session as
/// recording. Pulled out as its own pure function so this fallback is
/// unit-testable without driving all of `run_status`.
fn offline_project_outcome(
    inputs: &ProjectResolveInputs,
    user_default_project: Option<crate::session_state::ProjectBinding>,
) -> ProjectOutcome {
    Ok(effective_project(inputs)
        .or_else(|| user_default_project.map(|b| (b, ProjectSource::UserDefault))))
}

// --- Server repo ---

/// Which repo id `status` looks up on the server, and where it came from.
/// Always an id — never the checkout's directory name: a name match finds
/// whatever repo of that name someone registered, which says nothing about
/// whether THIS checkout carries an id the stream hook can attribute to.
#[derive(Debug, Clone, PartialEq)]
enum RepoLookup {
    /// The explicitly named session's repo binding for this worktree (a
    /// subagent override or the `repo switch` binding).
    Workspace(String),
    /// The `repo_id` in `.tracevault/config.toml` (bound mode).
    Bound(String),
    /// A `config.toml` exists but has no `repo_id`, and no session binding
    /// supplies one — the state in which the stream hook drops every event
    /// of a repo-only setup.
    MissingRepoId,
}

/// Mirrors the hook's precedence (`effective_binding`: session bindings
/// before bound config): the explicitly named session's binding — from
/// [`session_repo_binding`], so a subagent's worktree override wins exactly as
/// it does in the hook — else the config's `repo_id`. `None` when there is
/// neither a binding nor a config. Pure, so the precedence is unit-testable
/// without a server.
fn server_repo_lookup(
    config: Option<&TracevaultConfig>,
    binding: Option<&crate::session_state::RepoBinding>,
) -> Option<RepoLookup> {
    if let Some(b) = binding {
        return Some(RepoLookup::Workspace(b.repo_id.clone()));
    }
    let config = config?;
    Some(match &config.repo_id {
        Some(id) => RepoLookup::Bound(id.clone()),
        None => RepoLookup::MissingRepoId,
    })
}

/// The session-scoped tiers of the hook's repo chain for `worktree`: a
/// subagent's worktree override, else the session's active binding. Calls
/// `resolve_stream_binding` with the config and user-default tiers left out —
/// [`server_repo_lookup`] handles the config tier itself, and reports a
/// missing `repo_id` there rather than letting a lower tier mask it.
fn session_repo_binding(
    session: &crate::session_state::SessionState,
    worktree: &str,
) -> Option<crate::session_state::RepoBinding> {
    crate::commands::stream::resolve_stream_binding(session, worktree, None, None)
}

/// The server repo whose id is `id`. Compared as UUIDs, so case or
/// formatting differences in a hand-edited id don't produce a false miss; an
/// id that is not a UUID matches nothing (the hook would drop it too).
fn find_repo_by_id<'a>(
    repos: &'a [crate::api_client::RepoListItem],
    id: &str,
) -> Option<&'a crate::api_client::RepoListItem> {
    let id: uuid::Uuid = id.trim().parse().ok()?;
    repos.iter().find(|r| r.id == id)
}

async fn server_repo_checks(
    project_root: &Path,
    auth: &AuthContext,
    config: Option<&TracevaultConfig>,
    binding: Option<&crate::session_state::RepoBinding>,
) -> Vec<Check> {
    let mut out = Vec::new();

    // The local half first: a missing `repo_id` is an error whether or not
    // the user is logged in (init-before-login is exactly that state).
    // `bound_mode`: the id came from config.toml, so the checkout's own
    // `origin` is expected to match the server record (checked below).
    let (id, source, bound_mode) = match server_repo_lookup(config, binding) {
        None => {
            out.push(Check::skip(
                "Repo registered on server",
                "not bound (need a project config.toml or a --session-id workspace binding)",
            ));
            return out;
        }
        Some(RepoLookup::MissingRepoId) => {
            out.push(Check::err(
                "Repo registered on server",
                ".tracevault/config.toml has no repo_id, so sessions here are not attributed to this repo — run `tracevault sync` while logged in to register the repo and write it",
            ));
            return out;
        }
        Some(RepoLookup::Workspace(id)) => (id, "session binding", false),
        Some(RepoLookup::Bound(id)) => (id, ".tracevault/config.toml", true),
    };

    let (Some(credential), Some(server_url)) = (auth.credential.clone(), auth.server_url.as_ref())
    else {
        out.push(Check::skip(
            "Repo registered on server",
            format!("not authenticated (would look up repo id {id} from {source})"),
        ));
        return out;
    };

    let client = ApiClient::with_credential(server_url, Some(credential));
    let repos = match client.list_repos().await {
        Ok(r) => r,
        Err(e) => {
            out.push(Check::warn(
                "Repo registered on server",
                format!("failed to list repos: {e}"),
            ));
            return out;
        }
    };

    match find_repo_by_id(&repos, &id) {
        None => {
            out.push(Check::err(
                "Repo registered on server",
                format!("repo id {id} (from {source}) not found on the server. Run `tracevault sync` while logged in."),
            ));
            return out;
        }
        Some(r) => {
            out.push(Check::ok(
                "Repo registered on server",
                format!("id={} (from {source})", r.id),
            ));
            match r.clone_status.as_deref() {
                Some("ready") => out.push(Check::ok("Server-side clone", "ready")),
                Some(other @ ("cloning" | "pending")) => out.push(Check::warn(
                    "Server-side clone",
                    format!("{other} — analytics and code browser unavailable until it finishes"),
                )),
                Some("error") => out.push(Check::err(
                    "Server-side clone",
                    "error — check the repo settings page on the dashboard",
                )),
                Some(other) => out.push(Check::warn(
                    "Server-side clone",
                    format!("unknown status '{other}'"),
                )),
                None => out.push(Check::skip(
                    "Server-side clone",
                    "server did not report clone status",
                )),
            }

            if bound_mode {
                let local_remote = git_remote_url(project_root);
                match (local_remote.as_deref(), r.github_url.as_deref()) {
                    (Some(local), Some(remote))
                        if normalize_remote(local) == normalize_remote(remote) =>
                    {
                        out.push(Check::ok("Remote URL matches", remote.to_string()));
                    }
                    (Some(local), Some(remote)) => out.push(Check::warn(
                        "Remote URL matches",
                        format!("local={local} vs server={remote} — run `tracevault sync`"),
                    )),
                    (Some(local), None) => out.push(Check::warn(
                        "Remote URL matches",
                        format!("server has no github_url; local={local}"),
                    )),
                    (None, _) => out.push(Check::warn(
                        "Remote URL matches",
                        "no local `origin` remote configured",
                    )),
                }
            } else {
                out.push(Check::skip(
                    "Remote URL matches",
                    "n/a in workspace mode (bound by id)",
                ));
            }
        }
    }

    out
}

// --- Sessions ---

/// True for a per-repo `pending-<id>.jsonl` (nonempty id) queue file —
/// tighter than a bare `starts_with("pending") && ends_with(".jsonl")`
/// check, which would also match e.g. `pendingfoo.jsonl` or `pending-.jsonl`.
/// The legacy `pending.jsonl` name is handled separately by callers, since
/// whether it counts depends on whether there's a bound `repo_id` to
/// attribute it to (see `count_pending_events`).
fn is_pending_queue_filename(name: &str) -> bool {
    crate::commands::flush::repo_id_from_pending_filename(name).is_some()
}

/// Sum the non-empty lines across every per-repo (and, if `include_legacy`,
/// legacy) pending queue file in a session directory: `pending.jsonl` and
/// `pending-<repo_id>.jsonl`.
///
/// `include_legacy` should be true only when the project has a bound
/// `repo_id` (config.toml), since `flush` only drains the legacy
/// `pending.jsonl` in that case (best-effort attribution). Otherwise a
/// stray `pending.jsonl` would be counted here but never cleared by
/// `flush`, leaving `status` permanently reporting stuck events.
fn count_pending_events(session_dir: &Path, include_legacy: bool) -> usize {
    let Ok(read) = fs::read_dir(session_dir) else {
        return 0;
    };

    read.flatten()
        .filter(|entry| {
            entry
                .file_name()
                .to_str()
                .map(|name| {
                    is_pending_queue_filename(name) || (include_legacy && name == "pending.jsonl")
                })
                .unwrap_or(false)
        })
        .map(|entry| {
            fs::read_to_string(entry.path())
                .unwrap_or_default()
                .lines()
                .filter(|l| !l.trim().is_empty())
                .count()
        })
        .sum()
}

fn session_checks(project_root: &Path) -> Vec<Check> {
    let sessions_dir = project_root.join(".tracevault/sessions");
    if !sessions_dir.exists() {
        return vec![Check::skip(
            "Pending events",
            "no .tracevault/sessions/ here (project-local check; a detached worker's queue may live under its own working dir)",
        )];
    }

    // The legacy `pending.jsonl` is only drainable by `flush` when there's a
    // bound `repo_id` to attribute it to (best-effort attribution). Counting
    // it here otherwise would report events that `flush` can never clear.
    let include_legacy = TracevaultConfig::load(project_root)
        .and_then(|c| c.repo_id)
        .is_some();

    let mut total_sessions = 0usize;
    let mut sessions_with_pending = 0usize;
    let mut pending_event_count = 0usize;

    if let Ok(read) = fs::read_dir(&sessions_dir) {
        for entry in read.flatten() {
            if !entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
                continue;
            }
            total_sessions += 1;
            let count = count_pending_events(&entry.path(), include_legacy);
            if count > 0 {
                sessions_with_pending += 1;
                pending_event_count += count;
            }
        }
    }

    vec![if sessions_with_pending == 0 {
        Check::ok(
            "Pending events",
            format!("{total_sessions} session(s), all synced (project-local)"),
        )
    } else {
        Check::warn(
            "Pending events",
            format!(
                "{pending_event_count} event(s) in {sessions_with_pending}/{total_sessions} session(s) — run `tracevault flush`"
            ),
        )
    }]
}

// --- Git helpers ---

/// Make two remote URLs comparable by dropping `.git`, trailing slash, and
/// collapsing SSH ↔ HTTPS differences for github.com specifically.
fn normalize_remote(url: &str) -> String {
    let trimmed = url
        .trim()
        .trim_end_matches('/')
        .trim_end_matches(".git")
        .to_string();

    // git@github.com:org/repo  ->  github.com/org/repo
    if let Some(rest) = trimmed.strip_prefix("git@github.com:") {
        return format!("github.com/{rest}");
    }
    // https://github.com/org/repo -> github.com/org/repo
    for p in ["https://", "http://"] {
        if let Some(rest) = trimmed.strip_prefix(p) {
            return rest.to_string();
        }
    }
    trimmed
}

// --- Entry point ---

/// Resolve the session id for `status`: an explicit `--session-id` wins, else
/// the environment's ([`crate::session_state::env_session_id`]); empty strings
/// are ignored (fall through).
pub fn effective_session_id(arg: Option<String>, env: Option<String>) -> Option<String> {
    arg.filter(|s| !s.is_empty())
        .or_else(|| env.filter(|s| !s.is_empty()))
}

pub async fn run_status(project_root: &Path, cwd: &Path, session_id: Option<&str>) -> i32 {
    // Loaded here rather than reused from `project_checks` below, which runs
    // later and owns its own load. `try_load`, not `load`: `load` prints its own
    // stderr line on malformed TOML, which would pre-empt (and duplicate) the
    // structured parse error `project_checks` reports. A config that will not
    // parse simply contributes nothing here.
    let auth_config = TracevaultConfig::try_load(project_root).ok().flatten();
    let config_server_url = auth_config.as_ref().and_then(|c| c.server_url.as_deref());
    let auth = resolve_auth(
        config_server_url,
        auth_config.as_ref().and_then(|c| c.api_key.as_deref()),
    );

    // ~/.claude/settings.json — None when the home dir can't be resolved. Do
    // NOT fall back to a relative `.claude/settings.json`: that would read the
    // repo's own settings and could report a false "Global install".
    let global_settings: Option<PathBuf> =
        dirs::home_dir().map(|h| h.join(".claude").join("settings.json"));
    let sessions_dir = crate::session_state::sessions_dir();

    let global_check = match global_settings.as_deref() {
        Some(p) => global_hook_check_in(p),
        None => Check::skip("Global install", "cannot determine home directory"),
    };
    let has_global = global_check.level == Level::Ok;

    // Resolve the workspace binding ONCE: it drives both the section and the
    // `has_binding` mode signal used by project_checks.
    let (binding_check, binding) = match sessions_dir.as_deref() {
        Some(dir) => workspace_binding_check_in(dir, session_id),
        None => (
            Check::skip("Workspace repo", "cannot determine session state dir"),
            None,
        ),
    };
    // A binding only counts as a mode signal when the session was named
    // explicitly (--session-id / $TRACEVAULT_SESSION_ID). A *scanned* binding
    // (no session id) is cwd-agnostic and may belong to another repo, so it is
    // shown for information but must NOT downgrade "not set up" severity nor
    // drive the server-repo check.
    let explicit_session = session_id.is_some();
    let has_binding = binding.is_some() && explicit_session;

    let auth_checks_v = auth_checks(&auth, config_server_url).await;
    let telemetry_check = match global_settings.as_deref() {
        Some(p) => with_telemetry_choice(
            claude_telemetry_check_in(
                p,
                auth.server_url.as_deref(),
                &crate::commands::claude_telemetry::Environment::current(p.parent().unwrap_or(p)),
            ),
            &crate::install_state::load_in(&crate::config::tv_config_root()),
        ),
        None => Check::skip("Claude Code telemetry", "cannot determine home directory"),
    };
    let install_v = vec![global_check, telemetry_check];
    let (proj_checks_v, config) = project_checks(
        project_root,
        global_settings.as_deref(),
        has_global,
        has_binding,
    );

    // The recording verdict: call the hook's own gate (stream.rs) via
    // `recording_attribution` — see that function's doc comment for why its
    // composition, including the worktree-key derivation, lives there rather
    // than inline here. Its worktree key is reused below for the project
    // display resolution, which needs the same value.
    let (recording, worktree) =
        recording_for(sessions_dir.as_deref(), session_id, cwd, config.as_ref());
    let attribution = recording.attribution.clone();

    // The project axis for DISPLAY needs its own full `SessionState` (more
    // than `workspace_binding_check_in`'s bare `RepoBinding`, e.g.
    // `active_project`/`subagent_projects`) — unlike the verdict above, which
    // lives entirely inside `recording_attribution`. Loaded separately
    // (rather than sharing `recording_attribution`'s internal session load)
    // so that function's session load stays self-contained.
    let project_session = match (sessions_dir.as_deref(), session_id) {
        (Some(dir), Some(id)) => crate::session_state::load_from(dir, id),
        _ => crate::session_state::SessionState::default(),
    };

    // --- The project axis for DISPLAY only, mirroring `commands::project`'s
    // `status` path (project.rs:228-334): read the worktree-relative
    // default_project + the user-level default, and run the full precedence
    // chain (including server-side deduction) if a client can be built from
    // the existing `auth`. Best-effort like that path: no credential/client
    // degrades to the pure local tiers via `effective_project`, which need no
    // network. Whatever this resolves to (including a deduction failure) is
    // shown to the user but — unlike the verdict above — can never affect the
    // exit code beyond a Warn; see `project_binding_check`.
    // The workspace tier, read exactly as ingest reads it: the config's
    // `project_id`, never the legacy `default_project` name (VIS-1256).
    let config_project = config
        .as_ref()
        .and_then(crate::resolution::project_from_config);
    let user_default_project = crate::user_project_default::load();
    let project_git_url = git_remote_url(cwd);
    let project_outcome: ProjectOutcome = match (auth.credential.clone(), auth.server_url.as_ref())
    {
        (Some(credential), Some(server_url)) => {
            let client = ApiClient::with_credential(server_url, Some(credential));
            online_project_outcome(
                &client,
                config_project,
                &project_session,
                &worktree,
                user_default_project,
                project_git_url.as_deref(),
            )
            .await
        }
        _ => {
            // Offline (no client): only the UUID form of
            // `TRACEVAULT_PROJECT` can be honoured — a name would need
            // `list_projects`, which needs a client this arm doesn't
            // have. Reuses `commands::stream`'s capture-time helper
            // rather than duplicating the same UUID-only parse a third
            // time (the `project.rs` inline version stays separate: it
            // must distinguish "not a UUID" from "absent" so it can fall
            // through to name resolution, which this `Option`-returning
            // helper can't express).
            let inputs = ProjectResolveInputs {
                project_flag: None,
                env_project: crate::commands::stream::env_project_binding(),
                session: &project_session,
                worktree_path: Some(&worktree),
                config_project,
            };
            offline_project_outcome(&inputs, user_default_project)
        }
    };

    let mut attribution_v = Vec::new();
    match session_id {
        Some(_) => attribution_v.extend(
            recording_check(session_id, attribution.as_ref())
                .or_else(|| inferred_recording_check(&recording)),
        ),
        // No session named: `attribution` was resolved with an empty session,
        // i.e. exactly what the hook sees for a new session in this checkout.
        None => attribution_v.push(checkout_recording_check(
            attribution.as_ref(),
            config.as_ref(),
        )),
    }
    attribution_v.push(binding_check);
    attribution_v.push(project_binding_check(&project_outcome));
    attribution_v.extend(legacy_default_project_check(config.as_ref()));

    // The server target is the repo the hook would attribute this worktree's
    // events to — including a subagent override — not just the session's
    // `active` binding shown in "Workspace repo".
    let server_binding = if explicit_session {
        session_repo_binding(&project_session, &worktree)
    } else {
        None
    };
    let server_checks_v = server_repo_checks(
        project_root,
        &auth,
        config.as_ref(),
        server_binding.as_ref(),
    )
    .await;
    let session_checks_v = session_checks(project_root);

    let sections: Vec<(&str, Vec<Check>)> = vec![
        ("Authentication", auth_checks_v),
        ("Installation", install_v),
        ("Project", proj_checks_v),
        ("Attribution", attribution_v),
        ("Server repo", server_checks_v),
        ("Sessions", session_checks_v),
    ];
    for (title, checks) in &sections {
        print_section(title, checks);
    }
    let all: Vec<&Check> = sections.iter().flat_map(|(_, v)| v.iter()).collect();

    let errors = all.iter().filter(|c| c.level == Level::Error).count();
    let warns = all.iter().filter(|c| c.level == Level::Warn).count();

    match (errors, warns) {
        (0, 0) => println!("{ANSI_GREEN}All good.{ANSI_RESET}"),
        (0, w) => println!(
            "{ANSI_YELLOW}{w} warning{} — no blocking issues.{ANSI_RESET}",
            if w == 1 { "" } else { "s" }
        ),
        (e, 0) => println!(
            "{ANSI_RED}{e} problem{} found.{ANSI_RESET}",
            if e == 1 { "" } else { "s" }
        ),
        (e, w) => println!(
            "{ANSI_RED}{e} problem{}, {w} warning{}.{ANSI_RESET}",
            if e == 1 { "" } else { "s" },
            if w == 1 { "" } else { "s" }
        ),
    }

    exit_code_for(&all)
}

/// Only `Level::Error` checks force a non-zero exit; `Warn` and `Skip` are
/// surfaced to the user but don't fail the command. Pulled out as a pure
/// function so the severity→exit-code mapping is unit-testable independent
/// of the network-calling `run_status`.
fn exit_code_for(checks: &[&Check]) -> i32 {
    if checks.iter().any(|c| c.level == Level::Error) {
        1
    } else {
        0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn normalize_remote_ssh_https_equal() {
        assert_eq!(
            normalize_remote("git@github.com:VirtusLab/visdom-ai-tracing.git"),
            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing")
        );
        assert_eq!(
            normalize_remote("https://github.com/VirtusLab/visdom-ai-tracing.git/"),
            "github.com/VirtusLab/visdom-ai-tracing"
        );
    }

    #[test]
    fn normalize_remote_preserves_non_github() {
        assert_eq!(
            normalize_remote("git@gitlab.com:foo/bar.git"),
            "git@gitlab.com:foo/bar"
        );
    }

    #[test]
    fn git_hook_check_missing_file_is_warning() {
        let dir = tempfile::tempdir().unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Warn);
    }

    #[test]
    fn git_hook_check_with_marker_is_ok() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join(".git/hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(
            hooks.join("pre-push"),
            "#!/bin/sh\n# tracevault:enforce\ntracevault check\n",
        )
        .unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Ok);
    }

    #[test]
    fn git_hook_check_without_marker_is_warning() {
        let dir = tempfile::tempdir().unwrap();
        let hooks = dir.path().join(".git/hooks");
        std::fs::create_dir_all(&hooks).unwrap();
        std::fs::write(hooks.join("pre-push"), "#!/bin/sh\necho hi\n").unwrap();
        let check = git_hook_check(dir.path(), "pre-push", "# tracevault:enforce");
        assert_eq!(check.level, Level::Warn);
    }

    #[test]
    fn project_checks_errors_without_tracevault_dir_and_no_global_or_binding() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        let missing_global = dir.path().join("no-global.json");
        let (checks, cfg) =
            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
        assert!(cfg.is_none());
        assert!(checks
            .iter()
            .any(|c| c.level == Level::Error && c.label == "TraceVault initialized"));
        // The Git-hooks Skip must NOT claim "global/workspace mode" when the
        // user is truly unconfigured (no global install, no binding).
        let git_hooks = checks
            .iter()
            .find(|c| c.label == "Git hooks")
            .expect("Git hooks check present");
        assert_eq!(git_hooks.level, Level::Skip);
        assert!(
            !git_hooks.detail.contains("global/workspace mode"),
            "unconfigured git-hooks detail must not claim global/workspace mode: {}",
            git_hooks.detail
        );
    }

    #[test]
    fn project_checks_no_tracevault_dir_is_not_error_in_global_mode() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        let missing_global = dir.path().join("no-global.json");
        let (checks, _) = project_checks(dir.path(), Some(missing_global.as_path()), true, false);
        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(
            exit_code_for(&refs),
            0,
            "global mode must not force exit 1 on missing .tracevault/"
        );
        assert!(checks
            .iter()
            .any(|c| c.label == "TraceVault initialized" && c.level == Level::Skip));
    }

    #[test]
    fn project_checks_warns_when_config_toml_missing() {
        // Pure workspace/detached-mode user: .tracevault/ exists (or not,
        // doesn't matter for this check) but there's no config.toml because
        // `tracevault init` was never run. This must be a Warn, not an
        // Error, and therefore must not force the process exit code to 1.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
        let missing_global = dir.path().join("no-global.json");
        let (checks, cfg) =
            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
        assert!(cfg.is_none());
        let project_config_check = checks
            .iter()
            .find(|c| c.label == "Project config")
            .expect("Project config check present");
        assert_eq!(project_config_check.level, Level::Warn);

        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(
            exit_code_for(&refs),
            0,
            "a missing config.toml alone must not force a non-zero exit code"
        );
    }

    #[test]
    fn project_checks_errors_on_malformed_config_toml() {
        // A config.toml that exists but fails to parse is a genuine error,
        // distinct from "no config.toml at all" — it should stay Check::err
        // and keep forcing a non-zero exit code.
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join(".git")).unwrap();
        std::fs::create_dir_all(dir.path().join(".tracevault")).unwrap();
        std::fs::write(
            dir.path().join(".tracevault/config.toml"),
            "not valid toml {{{",
        )
        .unwrap();
        let missing_global = dir.path().join("no-global.json");
        let (checks, cfg) =
            project_checks(dir.path(), Some(missing_global.as_path()), false, false);
        assert!(cfg.is_none());
        let project_config_check = checks
            .iter()
            .find(|c| c.label == "Project config")
            .expect("Project config check present");
        assert_eq!(project_config_check.level, Level::Error);

        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 1);
    }

    #[test]
    fn exit_code_for_warn_only_is_zero() {
        let checks = [
            Check::warn("a", ""),
            Check::ok("b", ""),
            Check::skip("c", ""),
        ];
        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 0);
    }

    #[test]
    fn exit_code_for_any_error_is_one() {
        let checks = [
            Check::ok("a", ""),
            Check::err("b", ""),
            Check::warn("c", ""),
        ];
        let refs: Vec<&Check> = checks.iter().collect();
        assert_eq!(exit_code_for(&refs), 1);
    }

    #[test]
    fn count_pending_events_sums_across_per_repo_queues() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
        std::fs::write(dir.path().join("pending-b.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-c.jsonl"), "").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 3);
        assert_eq!(count_pending_events(dir.path(), true), 3);
    }

    #[test]
    fn count_pending_events_ignores_unrelated_files() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("notes.txt"), "line1\nline2\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 1);
    }

    #[test]
    fn count_pending_events_zero_for_empty_dir() {
        let dir = tempfile::tempdir().unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 0);
        assert_eq!(count_pending_events(dir.path(), true), 0);
    }

    #[test]
    fn is_pending_queue_filename_matches_per_repo_only() {
        assert!(!is_pending_queue_filename("pending.jsonl"));
        // Repo-less queues must be counted too. This holds today only
        // because `repo_id_from_pending_filename` matches the shared
        // `pending-` prefix and `status` never validates the id — i.e. by
        // accident. Pin it, so tightening that helper to reject the project
        // shape (which its name invites) cannot silently make `status` report
        // "0 pending" over a non-empty queue that `flush` still drains.
        assert!(is_pending_queue_filename(
            "pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"
        ));
        assert!(is_pending_queue_filename("pending-a.jsonl"));
    }

    #[test]
    fn is_pending_queue_filename_rejects_lookalikes() {
        assert!(!is_pending_queue_filename("pendingfoo.jsonl"));
        assert!(!is_pending_queue_filename("pending-.jsonl"));
    }

    #[test]
    fn count_pending_events_legacy_pending_jsonl_requires_include_legacy() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending.jsonl"), "line1\nline2\n").unwrap();
        assert_eq!(
            count_pending_events(dir.path(), false),
            0,
            "legacy pending.jsonl must not be counted when there's no bound repo_id"
        );
        assert_eq!(
            count_pending_events(dir.path(), true),
            2,
            "legacy pending.jsonl counts once a repo_id is bound"
        );
    }

    #[test]
    fn count_pending_events_legacy_and_per_repo_both_count_when_included() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pending.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-a.jsonl"), "line1\nline2\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 2);
        assert_eq!(count_pending_events(dir.path(), true), 3);
    }

    #[test]
    fn count_pending_events_ignores_lookalike_filenames() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("pendingfoo.jsonl"), "line1\n").unwrap();
        std::fs::write(dir.path().join("pending-.jsonl"), "line1\n").unwrap();
        assert_eq!(count_pending_events(dir.path(), false), 0);
        assert_eq!(count_pending_events(dir.path(), true), 0);
    }

    #[test]
    fn settings_has_tracevault_hooks_detects_commands() {
        assert!(settings_has_tracevault_hooks(
            r#"{"hooks":{"PreToolUse":[{"hooks":[{"command":"tracevault stream --event pre"}]}]}}"#
        ));
        assert!(settings_has_tracevault_hooks(
            r#"{"command":"tracevault session-start"}"#
        ));
        assert!(settings_has_tracevault_hooks(
            r#"{"command":"tracevault user-prompt"}"#
        ));
        assert!(!settings_has_tracevault_hooks(
            r#"{"hooks":{"PreToolUse":[]}}"#
        ));
        assert!(!settings_has_tracevault_hooks("{}"));
    }

    #[test]
    fn claude_telemetry_check_levels() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("settings.json");
        let server = Some("https://tv.example.com");

        // No settings file: off.
        let c = claude_telemetry_check_in(
            &p,
            server,
            &crate::commands::claude_telemetry::Environment::default(),
        );
        assert_eq!(c.level, Level::Skip, "{c:?}");

        crate::commands::claude_telemetry::install(
            dir.path(),
            "https://tv.example.com",
            &crate::commands::claude_telemetry::Environment::default(),
        )
        .unwrap();
        let c = claude_telemetry_check_in(
            &p,
            server,
            &crate::commands::claude_telemetry::Environment::default(),
        );
        assert_eq!(c.level, Level::Ok, "{c:?}");
        assert!(
            c.detail.contains("https://tv.example.com/otlp/v1/logs"),
            "{c:?}"
        );

        // Logged in to another server than the one telemetry goes to.
        let c = claude_telemetry_check_in(
            &p,
            Some("https://other.example.com"),
            &crate::commands::claude_telemetry::Environment::default(),
        );
        assert_eq!(c.level, Level::Warn, "{c:?}");

        // Our helper plus someone else's exporter: our token leaks there.
        let env = crate::commands::claude_telemetry::tests::shell("OTEL_METRICS_EXPORTER", "otlp");
        let c = claude_telemetry_check_in(&p, server, &env);
        assert_eq!(c.level, Level::Warn, "{c:?}");

        // Only someone else's exporter: legitimate, just not ours.
        std::fs::write(&p, r#"{"env":{"OTEL_LOGS_EXPORTER":"console"}}"#).unwrap();
        let c = claude_telemetry_check_in(
            &p,
            server,
            &crate::commands::claude_telemetry::Environment::default(),
        );
        assert_eq!(c.level, Level::Skip, "{c:?}");
        assert!(c.detail.contains("exported elsewhere"), "{c:?}");

        std::fs::write(&p, "{not json").unwrap();
        assert_eq!(
            claude_telemetry_check_in(
                &p,
                server,
                &crate::commands::claude_telemetry::Environment::default()
            )
            .level,
            Level::Warn
        );
    }

    #[test]
    fn global_hook_check_ok_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("settings.json");
        std::fs::write(
            &p,
            r#"{"hooks":{"SessionStart":[{"hooks":[{"command":"tracevault session-start"}]}]}}"#,
        )
        .unwrap();
        assert_eq!(global_hook_check_in(&p).level, Level::Ok);
    }

    #[test]
    fn global_hook_check_skip_when_absent_or_no_hooks() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("settings.json");
        assert_eq!(global_hook_check_in(&missing).level, Level::Skip);
        let empty = dir.path().join("empty.json");
        std::fs::write(&empty, "{}").unwrap();
        assert_eq!(global_hook_check_in(&empty).level, Level::Skip);
    }

    #[test]
    fn global_hook_check_warns_when_unreadable() {
        // A path that exists but isn't a readable file (a directory) yields a
        // non-NotFound read error → Warn, not a false "no settings.json" Skip.
        let dir = tempfile::tempdir().unwrap();
        let as_dir = dir.path().join("settings.json");
        std::fs::create_dir(&as_dir).unwrap();
        let check = global_hook_check_in(&as_dir);
        assert_eq!(check.level, Level::Warn);
        assert!(
            check.detail.contains("cannot read"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn claude_hook_check_ok_from_global_only() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude"); // does not exist
        let global = dir.path().join("global-settings.json");
        std::fs::write(&global, r#"{"command":"tracevault stream"}"#).unwrap();
        let c = claude_hook_check_in(&repo, Some(global.as_path()));
        assert_eq!(c.level, Level::Ok);
        assert!(
            c.detail.to_lowercase().contains("global") || c.detail.contains("~/.claude"),
            "detail: {}",
            c.detail
        );
    }

    #[test]
    fn claude_hook_check_ok_from_repo() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(
            repo.join("settings.json"),
            r#"{"command":"tracevault stream"}"#,
        )
        .unwrap();
        let global = dir.path().join("global-settings.json"); // does not exist
        let c = claude_hook_check_in(&repo, Some(global.as_path()));
        assert_eq!(c.level, Level::Ok);
        assert!(
            c.detail.contains(".claude/settings.json"),
            "detail: {}",
            c.detail
        );
    }

    #[test]
    fn claude_hook_check_ok_from_repo_local_settings() {
        // `init --claude-settings local` writes only settings.local.json; the
        // check must not warn "not registered" for it (VIS-1047).
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(
            repo.join("settings.local.json"),
            r#"{"command":"tracevault stream"}"#,
        )
        .unwrap();
        let global = dir.path().join("global-settings.json"); // does not exist
        let c = claude_hook_check_in(&repo, Some(global.as_path()));
        assert_eq!(c.level, Level::Ok);
        assert!(
            c.detail.contains(".claude/settings.local.json"),
            "detail: {}",
            c.detail
        );
    }

    #[test]
    fn claude_hook_check_local_settings_win_over_hookless_shared() {
        // A shared settings.json without our hooks (team settings) next to a
        // local file that has them is the usual `--claude-settings local` shape.
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(repo.join("settings.json"), r#"{"permissions":{}}"#).unwrap();
        std::fs::write(
            repo.join("settings.local.json"),
            r#"{"command":"tracevault session-start"}"#,
        )
        .unwrap();
        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);
    }

    #[test]
    fn claude_hook_check_no_global_path_uses_repo_only() {
        // When the home dir can't be resolved (global_settings = None), only the
        // repo settings are consulted — never a relative fallback.
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude");
        std::fs::create_dir(&repo).unwrap();
        std::fs::write(
            repo.join("settings.json"),
            r#"{"command":"tracevault stream"}"#,
        )
        .unwrap();
        assert_eq!(claude_hook_check_in(&repo, None).level, Level::Ok);

        let missing = dir.path().join("nope");
        assert_eq!(claude_hook_check_in(&missing, None).level, Level::Warn);
    }

    #[test]
    fn claude_hook_check_warn_when_neither() {
        let dir = tempfile::tempdir().unwrap();
        let c = claude_hook_check_in(
            &dir.path().join(".claude"),
            Some(dir.path().join("b.json").as_path()),
        );
        assert_eq!(c.level, Level::Warn);
        assert!(
            c.detail.contains("settings.local.json"),
            "detail: {}",
            c.detail
        );
    }

    #[test]
    fn claude_hook_check_warns_when_repo_settings_unreadable() {
        let dir = tempfile::tempdir().unwrap();
        let repo = dir.path().join(".claude");
        // directory-as-file → non-NotFound read error
        std::fs::create_dir_all(repo.join("settings.local.json")).unwrap();
        let global = dir.path().join("global.json"); // missing
        let c = claude_hook_check_in(&repo, Some(global.as_path()));
        assert_eq!(c.level, Level::Warn);
        assert!(c.detail.contains("cannot read"), "detail: {}", c.detail);
        assert!(
            c.detail.contains("settings.local.json"),
            "detail: {}",
            c.detail
        );
    }

    #[test]
    fn tracevault_init_check_severity_matrix() {
        assert_eq!(tracevault_init_check(true, false, false).level, Level::Ok); // present → Ok
        assert_eq!(tracevault_init_check(false, true, false).level, Level::Skip); // absent + global → Skip
        assert_eq!(tracevault_init_check(false, false, true).level, Level::Skip); // absent + binding → Skip
        assert_eq!(tracevault_init_check(false, true, true).level, Level::Skip);
        assert_eq!(
            tracevault_init_check(false, false, false).level,
            Level::Error
        ); // nothing → Error
    }

    #[test]
    fn workspace_binding_explicit_id_with_binding_is_ok() {
        let dir = tempfile::tempdir().unwrap();
        let st = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "11111111-1111-4111-8111-111111111111".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("sess-9.toml"),
            toml::to_string(&st).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-9"));
        assert_eq!(check.level, Level::Ok);
        assert!(
            check
                .detail
                .contains("11111111-1111-4111-8111-111111111111"),
            "detail: {}",
            check.detail
        );
        assert_eq!(
            binding.unwrap().repo_id,
            "11111111-1111-4111-8111-111111111111"
        );
    }

    #[test]
    fn workspace_binding_explicit_id_without_binding_is_skip() {
        // Severity moved to `recording_check`, which is the only place that
        // sees both attribution axes — this check alone can't tell a
        // genuinely unbound machine from one attributed via the project axis.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("sess-empty.toml"),
            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-empty"));
        assert_eq!(check.level, Level::Skip);
        assert!(binding.is_none());
    }

    #[test]
    fn workspace_binding_no_id_empty_dir_is_skip() {
        let dir = tempfile::tempdir().unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), None);
        assert_eq!(check.level, Level::Skip);
        assert!(binding.is_none());
    }

    #[test]
    fn workspace_binding_no_id_scans_latest() {
        let dir = tempfile::tempdir().unwrap();
        // Two sessions; the one written LAST should be picked by the mtime scan.
        let older = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("old.toml"),
            toml::to_string(&older).unwrap(),
        )
        .unwrap();
        // Ensure a distinct, later mtime for the second file.
        std::thread::sleep(std::time::Duration::from_millis(20));
        let newer = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "bbbbbbbb-2222-4222-8222-222222222222".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("new.toml"),
            toml::to_string(&newer).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), None);
        assert_eq!(check.level, Level::Ok);
        assert_eq!(
            binding.unwrap().repo_id,
            "bbbbbbbb-2222-4222-8222-222222222222",
            "must pick the most-recently-modified session"
        );
    }

    #[test]
    fn workspace_binding_scan_skips_newest_without_binding() {
        // The most-recently-touched session has NO active binding, but an older
        // one does — the scan must find the older binding, not stop at the newest.
        let dir = tempfile::tempdir().unwrap();
        let with_binding = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "aaaaaaaa-1111-4111-8111-111111111111".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("older.toml"),
            toml::to_string(&with_binding).unwrap(),
        )
        .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(20));
        // Newest file: no active binding.
        std::fs::write(
            dir.path().join("newest.toml"),
            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), None);
        assert_eq!(check.level, Level::Ok);
        assert_eq!(
            binding.unwrap().repo_id,
            "aaaaaaaa-1111-4111-8111-111111111111"
        );
    }

    #[test]
    fn workspace_binding_scan_no_active_binding_is_skip_not_warn() {
        // A session file exists but has no active binding (e.g. a bound-mode
        // user with a stray session). Scan mode must Skip, not Warn.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("stray.toml"),
            toml::to_string(&crate::session_state::SessionState::default()).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), None);
        assert_eq!(check.level, Level::Skip);
        assert!(binding.is_none());
    }

    #[test]
    fn workspace_binding_explicit_id_malformed_repo_id_is_warn_not_ok() {
        // `attribution_for` filters a resolved binding through
        // `binding_repo_id_is_valid` and drops it if the check fails; a
        // corrupted session-state file with a non-UUID `repo_id` must not
        // read Ok here either.
        let dir = tempfile::tempdir().unwrap();
        let st = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "not-a-uuid".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("sess-bad.toml"),
            toml::to_string(&st).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), Some("sess-bad"));
        assert_eq!(check.level, Level::Warn);
        assert!(
            check.detail.contains("not a valid id"),
            "detail: {}",
            check.detail
        );
        // The raw binding is still returned (unchanged mode signal for
        // callers) — only this check's OWN severity changes.
        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
    }

    #[test]
    fn workspace_binding_scan_malformed_repo_id_is_warn_not_ok() {
        // Same rule, scan arm: `latest_active_binding_in` doesn't validate
        // either, so the same corrupted binding could surface via a scan.
        let dir = tempfile::tempdir().unwrap();
        let st = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "not-a-uuid".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        std::fs::write(
            dir.path().join("sess-bad.toml"),
            toml::to_string(&st).unwrap(),
        )
        .unwrap();
        let (check, binding) = workspace_binding_check_in(dir.path(), None);
        assert_eq!(check.level, Level::Warn);
        assert!(
            check.detail.contains("not a valid id"),
            "detail: {}",
            check.detail
        );
        assert_eq!(binding.unwrap().repo_id, "not-a-uuid");
    }

    fn repo_item(id: &str, name: &str) -> crate::api_client::RepoListItem {
        crate::api_client::RepoListItem {
            id: id.parse().unwrap(),
            name: name.to_string(),
            github_url: None,
            clone_status: None,
        }
    }

    fn workspace_binding(id: &str) -> crate::session_state::RepoBinding {
        crate::session_state::RepoBinding {
            repo_id: id.into(),
            git_url: None,
            remote_id: None,
            codebase_name: None,
            updated_at: "t".into(),
        }
    }

    #[test]
    fn find_repo_by_id_hits_by_id_not_name() {
        let id = "11111111-1111-4111-8111-111111111111";
        let repos = vec![repo_item(id, "myrepo")];
        assert_eq!(find_repo_by_id(&repos, id).unwrap().name, "myrepo");
        // Compared as UUIDs: an upper-cased, hand-edited id still matches.
        assert!(find_repo_by_id(&repos, &id.to_uppercase()).is_some());
    }

    #[test]
    fn find_repo_by_id_ignores_same_named_repo() {
        // VIS-1047: someone else registered a repo with this checkout's
        // directory name. A name match used to show ✓ here; the id must not.
        let repos = vec![repo_item("11111111-1111-4111-8111-111111111111", "myrepo")];
        assert!(find_repo_by_id(&repos, "22222222-2222-4222-8222-222222222222").is_none());
        assert!(find_repo_by_id(&repos, "myrepo").is_none());
    }

    #[test]
    fn server_repo_lookup_uses_config_repo_id() {
        let config = TracevaultConfig {
            repo_id: Some("rid-config".into()),
            ..Default::default()
        };
        assert_eq!(
            server_repo_lookup(Some(&config), None),
            Some(RepoLookup::Bound("rid-config".into()))
        );
    }

    #[test]
    fn server_repo_lookup_config_without_repo_id_is_missing() {
        // VIS-1047: the state in which the hook drops every event must not be
        // looked up by directory name and reported as registered.
        let config = TracevaultConfig::default();
        assert_eq!(
            server_repo_lookup(Some(&config), None),
            Some(RepoLookup::MissingRepoId)
        );
    }

    #[test]
    fn server_repo_lookup_session_binding_wins_over_config() {
        // Same precedence as `effective_binding`: a session's active binding
        // outranks the bound config, so it is the repo the hook attributes to.
        let config = TracevaultConfig::default();
        let b = workspace_binding("rid-session");
        assert_eq!(
            server_repo_lookup(Some(&config), Some(&b)),
            Some(RepoLookup::Workspace("rid-session".into()))
        );
        assert_eq!(
            server_repo_lookup(None, Some(&b)),
            Some(RepoLookup::Workspace("rid-session".into()))
        );
    }

    #[test]
    fn server_repo_lookup_none_when_neither() {
        assert!(server_repo_lookup(None, None).is_none());
    }

    fn unauthenticated() -> AuthContext {
        AuthContext {
            server_url: None,
            credential: None,
            source: "none",
            email_from_creds: None,
            url_override_mismatch: None,
        }
    }

    #[tokio::test]
    async fn server_repo_checks_missing_repo_id_is_error_before_login() {
        // Init-before-login: the missing repo_id is a local fact and must be
        // reported even though the server cannot be asked.
        let dir = tempfile::tempdir().unwrap();
        let config = TracevaultConfig::default();
        let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].level, Level::Error);
        assert!(
            checks[0].detail.contains("no repo_id"),
            "detail: {}",
            checks[0].detail
        );
    }

    #[tokio::test]
    async fn server_repo_checks_with_repo_id_but_no_login_is_skip() {
        let dir = tempfile::tempdir().unwrap();
        let config = TracevaultConfig {
            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
            ..Default::default()
        };
        let checks = server_repo_checks(dir.path(), &unauthenticated(), Some(&config), None).await;
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].level, Level::Skip);
        assert!(
            checks[0]
                .detail
                .contains("22222222-2222-4222-8222-222222222222"),
            "detail: {}",
            checks[0].detail
        );
    }

    #[test]
    fn session_repo_binding_prefers_subagent_override_like_the_hook() {
        // Codex R1: the server target must be the repo the hook attributes
        // this worktree to — a subagent override beats the active binding.
        let mut session = crate::session_state::SessionState {
            active: Some(workspace_binding("11111111-1111-4111-8111-111111111111")),
            ..Default::default()
        };
        session.subagents.insert(
            "/wt/sub".into(),
            workspace_binding("33333333-3333-4333-8333-333333333333"),
        );
        assert_eq!(
            session_repo_binding(&session, "/wt/sub").unwrap().repo_id,
            "33333333-3333-4333-8333-333333333333"
        );
        assert_eq!(
            session_repo_binding(&session, "/wt/other").unwrap().repo_id,
            "11111111-1111-4111-8111-111111111111"
        );
        assert!(session_repo_binding(&Default::default(), "/wt/sub").is_none());
    }

    /// Runs `recording_attribution` the way `run_status` does without a named
    /// session, then `checkout_recording_check` on the result — in an isolated
    /// config home so no real user-level default leaks in.
    fn checkout_verdict(config: Option<&TracevaultConfig>) -> Check {
        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), config);
        checkout_recording_check(attribution.as_ref(), config)
    }

    #[test]
    fn checkout_recording_config_without_repo_id_is_error() {
        // VIS-1047 case 3: right after an init-before-login, a plain terminal
        // must say capture is off.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let check = checkout_verdict(Some(&TracevaultConfig::default()));
        assert_eq!(check.level, Level::Error);
        assert!(
            check.detail.contains("no repo_id"),
            "detail: {}",
            check.detail
        );
        assert!(
            check.detail.contains("tracevault sync"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn checkout_recording_config_with_invalid_repo_id_is_error() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let config = TracevaultConfig {
            repo_id: Some("not-a-uuid".into()),
            ..Default::default()
        };
        let check = checkout_verdict(Some(&config));
        assert_eq!(check.level, Level::Error);
        assert!(
            check.detail.contains("not a valid id"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn checkout_recording_config_with_repo_id_is_ok() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let config = TracevaultConfig {
            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
            ..Default::default()
        };
        let check = checkout_verdict(Some(&config));
        assert_eq!(check.level, Level::Ok);
        assert!(
            check
                .detail
                .contains("22222222-2222-4222-8222-222222222222"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn checkout_recording_config_without_repo_id_but_user_project_is_warn() {
        // Events still ship (project-only), but not to this repo, which is
        // what a bound-mode checkout asked for.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");
        crate::user_project_default::save(&project_binding(
            &uuid::Uuid::from_u128(7).to_string(),
            "p",
        ))
        .unwrap();

        let check = checkout_verdict(Some(&TracevaultConfig::default()));
        assert_eq!(check.level, Level::Warn);
        assert!(check.detail.contains("project"), "detail: {}", check.detail);
    }

    #[test]
    fn checkout_recording_user_default_repo_without_config_is_ok() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");
        crate::user_default::save(&workspace_binding("11111111-1111-4111-8111-111111111111"))
            .unwrap();

        assert_eq!(checkout_verdict(None).level, Level::Ok);
    }

    #[test]
    fn checkout_recording_nothing_bound_without_config_is_warn() {
        // Workspace mode binds per session, so an unbound plain terminal is
        // expected — but it is said out loud, not left green.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let check = checkout_verdict(None);
        assert_eq!(check.level, Level::Warn);
        // Says what will bind a new session: its checkout's remote (VIS-1048).
        assert!(
            check.detail.contains("origin remote") && check.detail.contains("tracevault sync"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn effective_session_id_arg_wins_and_filters_empty() {
        assert_eq!(
            effective_session_id(Some("a".into()), Some("b".into())),
            Some("a".into())
        );
        assert_eq!(
            effective_session_id(Some("".into()), Some("b".into())),
            Some("b".into())
        );
        assert_eq!(
            effective_session_id(Some("   ".into()), None).as_deref(),
            Some("   ")
        ); // non-empty whitespace is a real (if odd) id — NOT filtered
        assert_eq!(effective_session_id(None, Some("".into())), None);
        assert_eq!(effective_session_id(None, None), None);
    }

    fn project_binding(id: &str, name: &str) -> crate::session_state::ProjectBinding {
        crate::session_state::ProjectBinding {
            project_id: id.into(),
            project_name: name.into(),
            updated_at: "t".into(),
            forced_until: None,
        }
    }

    /// `id` must be a real UUID string — `attribution_for` only accepts a
    /// repo binding whose `repo_id` parses as one (`binding_repo_id_is_valid`
    /// in stream.rs); a non-UUID id degrades to `ProjectOnly`/`None` instead.
    fn repo_binding_for_attribution(id: &str) -> crate::session_state::RepoBinding {
        crate::session_state::RepoBinding {
            repo_id: id.into(),
            git_url: None,
            remote_id: None,
            codebase_name: None,
            updated_at: "t".into(),
        }
    }

    #[test]
    fn recording_check_truth_table() {
        // Literal expected outcomes, NOT a restatement of `recording_check`'s
        // own condition (a computed `expect_error` formula could pass even if
        // the implementation's condition drifted, since both would drift
        // together).
        let repo_attr = crate::commands::stream::Attribution::Repo {
            repo_id: "11111111-1111-4111-8111-111111111111".into(),
            project: None,
        };
        let project_attr = crate::commands::stream::Attribution::ProjectOnly {
            project_id: uuid::Uuid::from_u128(1),
        };

        // session_id: None (no explicit session — a bare scan): never fires,
        // no matter what attribution is.
        assert!(recording_check(None, None).is_none());
        assert!(recording_check(None, Some(&repo_attr)).is_none());
        assert!(recording_check(None, Some(&project_attr)).is_none());

        // session_id: Some, something resolved (either shape): no check.
        assert!(recording_check(Some("s"), Some(&repo_attr)).is_none());
        assert!(recording_check(Some("s"), Some(&project_attr)).is_none());

        // session_id: Some, nothing resolved: the ONLY firing cell.
        assert_eq!(
            recording_check(Some("s"), None).map(|c| c.level),
            Some(Level::Error)
        );
    }

    #[test]
    fn recording_check_error_names_project_switch_and_session() {
        // Defect (2): the stale `repo switch <name>` hint has to be gone and
        // the repo-less remediation (`project switch --user`) has to be
        // present, or a regression to the old text wouldn't be caught by a
        // plain level assertion.
        let check = recording_check(Some("3f27a336-abcd"), None).expect("expected an Error check");
        assert_eq!(check.level, Level::Error);
        assert!(
            check.detail.contains("project switch"),
            "detail: {}",
            check.detail
        );
        assert!(
            check.detail.contains("3f27a336-abcd"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn project_binding_check_tiers_capture_project_honors_are_ok() {
        // Only the tiers `capture_project` itself resolves at capture time
        // read Ok: a `--project`-equivalent flag, the subagent/session-active
        // overrides, `TRACEVAULT_PROJECT` (`Env`, since A2 wired
        // `env_project_binding()` into `capture_project`'s inputs), and the
        // user-level default. `ConfigDefault` and `Deduced` are covered
        // separately — they must NOT appear here. Uses a well-formed UUID
        // id: an honored tier still needs a parseable `project_id` to read
        // Ok (see the malformed-id tests below).
        //
        // `TRACEVAULT_PROJECT` is pinned to that same UUID for the duration:
        // an `Env`-sourced binding can only ever exist when that var is set,
        // and the check now asks `env_project_binding()` whether the RAW
        // value is the UUID form the capture path honours (see
        // `project_binding_check_env_name_form_is_warn_not_ok`). Leaving the
        // var unset here would assert on a state that cannot occur.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");

        use crate::resolution::ProjectSource::*;
        for source in [ProjectFlag, Subagent, Env, SessionActive, UserDefault] {
            let outcome: ProjectOutcome = Ok(Some((
                project_binding("33333333-3333-4333-8333-333333333333", "My Project"),
                source,
            )));
            let check = project_binding_check(&outcome);
            assert_eq!(check.level, Level::Ok, "source={source} should read Ok");
            assert!(
                check.detail.contains("My Project"),
                "source={source} detail: {}",
                check.detail
            );
        }
    }

    /// VIS-305 whole-branch review, Important finding 2: the false green.
    /// `env_project_binding` is UUID-only, but `project status` and
    /// `run_status` both resolve a project NAME in `TRACEVAULT_PROJECT` via
    /// `list_projects` and report the tier as `Env`. The resolved binding's
    /// id then IS a valid UUID, so an id-only check reads `Ok` — whose
    /// documented contract is "this tier IS honoured at capture time" —
    /// while the hook ignores the name entirely and attributes elsewhere.
    ///
    /// The condition `capture_project` actually applies is to the RAW env
    /// value, so this pins that: same well-formed resolved binding, same
    /// `Env` tier, but `TRACEVAULT_PROJECT` holding a NAME must render
    /// `Warn`, worded like `unresolved_config_default_check` — resolves for
    /// display, not honoured on the wire.
    #[test]
    fn project_binding_check_env_name_form_is_warn_not_ok() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("TRACEVAULT_PROJECT", "payments");

        // Exactly what `online_project_outcome`/`resolve_status_effective`
        // hand back for `TRACEVAULT_PROJECT=payments`: the NAME resolved
        // against `list_projects`, so the id is a perfectly valid UUID.
        let outcome: ProjectOutcome = Ok(Some((
            project_binding("33333333-3333-4333-8333-333333333333", "payments"),
            crate::resolution::ProjectSource::Env,
        )));
        let check = project_binding_check(&outcome);
        assert_eq!(
            check.level,
            Level::Warn,
            "a NAME in TRACEVAULT_PROJECT is ignored by the capture path, so it must never read Ok: {}",
            check.detail
        );
        assert!(
            check.detail.contains("UUID form"),
            "the warning must say WHICH form is honoured: {}",
            check.detail
        );
        assert!(
            check.detail.contains("display only"),
            "worded like unresolved_config_default_check's precedent: {}",
            check.detail
        );

        // Discrimination: the SAME binding under the UUID form still reads
        // Ok, so this pins the raw-value rule and not merely "Env warns".
        _guard.set("TRACEVAULT_PROJECT", "33333333-3333-4333-8333-333333333333");
        let outcome: ProjectOutcome = Ok(Some((
            project_binding("33333333-3333-4333-8333-333333333333", "payments"),
            crate::resolution::ProjectSource::Env,
        )));
        assert_eq!(project_binding_check(&outcome).level, Level::Ok);
    }

    #[test]
    fn project_binding_check_workspace_config_is_ok() {
        // VIS-1256: the workspace config's `project_id` IS a capture tier,
        // so a valid one reads Ok, labelled with its source.
        let outcome: ProjectOutcome = Ok(Some((
            project_binding("00000000-0000-4000-8000-0000000000aa", "visdom"),
            crate::resolution::ProjectSource::Workspace,
        )));
        let check = project_binding_check(&outcome);
        assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
        assert_eq!(check.detail, "visdom — workspace .tracevault/config.toml");
    }

    /// A legacy `default_project` is reported as unmigrated, never resolved
    /// (status must match ingest, which ignores it).
    #[test]
    fn legacy_default_project_check_says_unmigrated() {
        let cfg = TracevaultConfig {
            default_project: Some("payments".into()),
            ..Default::default()
        };
        let check = legacy_default_project_check(Some(&cfg)).unwrap();
        assert_eq!(check.level, Level::Warn);
        assert_eq!(
            check.detail,
            "default_project \"payments\" is not used for capture until migrated; run `tracevault sync`"
        );
        assert!(legacy_default_project_check(Some(&TracevaultConfig::default())).is_none());
        assert!(legacy_default_project_check(None).is_none());
    }

    #[test]
    fn project_binding_check_deduced_is_warn() {
        // `capture_project` never deduces server-side, so this tier can't
        // read Ok either — same reasoning as `ConfigDefault` above.
        let outcome: ProjectOutcome = Ok(Some((
            project_binding("pid-2", ""),
            crate::resolution::ProjectSource::Deduced,
        )));
        let check = project_binding_check(&outcome);
        assert_eq!(check.level, Level::Warn);
        assert!(
            check
                .detail
                .contains("not used for attribution at capture time"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn project_binding_check_malformed_project_id_is_warn_not_ok() {
        // Aikido's finding: `capture_project` ends with
        // `.parse::<uuid::Uuid>().ok()?`, so a saved binding with a
        // non-UUID `project_id` (a hand-edited or corrupted
        // `user_project.toml`, or a corrupted session-state file) is
        // silently dropped at capture time. An honored tier with such an id
        // must not read Ok. Covers SessionActive and UserDefault.
        use crate::resolution::ProjectSource::{SessionActive, UserDefault};
        for source in [SessionActive, UserDefault] {
            let outcome: ProjectOutcome =
                Ok(Some((project_binding("not-a-uuid", "My Project"), source)));
            let check = project_binding_check(&outcome);
            assert_eq!(check.level, Level::Warn, "source={source}");
            assert!(
                check.detail.contains("not a valid id"),
                "source={source} detail: {}",
                check.detail
            );
        }
    }

    #[test]
    fn project_binding_check_ambiguous_err_is_warn_not_error() {
        // This axis is display-only — the verdict comes from
        // `recording_check`'s real gate, which never deduces — so ANY failure
        // of the deduction call (genuinely ambiguous, or a transport/5xx
        // error propagated the same way) must read as Warn, never Error: a
        // network blip on this axis must not be able to redden the exit code.
        let outcome: ProjectOutcome =
            Err("this repo belongs to multiple projects; select one with `tracevault project switch <name>`".into());
        let check = project_binding_check(&outcome);
        assert_eq!(check.level, Level::Warn);
        assert!(
            check.detail.contains("multiple projects"),
            "detail: {}",
            check.detail
        );
    }

    #[test]
    fn project_binding_check_none_is_skip() {
        let outcome: ProjectOutcome = Ok(None);
        let check = project_binding_check(&outcome);
        assert_eq!(check.level, Level::Skip);
    }

    // --- Verdict composition: every test below drives `recording_attribution`
    // directly (rather than re-deriving its session-load/worktree-key/bound-
    // config composition by hand), so a regression in that composition —
    // e.g. the worktree key coming from the wrong path — fails a test instead
    // of only a full end-to-end run (see `recording_attribution_finds_
    // subagent_override_via_linked_worktree_cwd` below).
    //
    // ISOLATION: `recording_attribution` -> `capture_project` always
    // consults `user_project_default::load()` once its local tiers miss, and
    // `recording_attribution` itself calls `user_default::load()`
    // unconditionally — both are backed by `dirs::config_dir()`/
    // `dirs::home_dir()`, which read the REAL developer config on the machine
    // running the test unless overridden. EVERY test below therefore
    // redirects both `XDG_CONFIG_HOME` (the path on Linux) and `HOME` (the
    // path `dirs` actually uses on macOS, and `home_dir()`'s own first
    // choice) to the same empty temp dir — even tests that don't care about
    // either default, since a developer machine that has ever run
    // `project switch --user` or `repo switch --user` would otherwise inject
    // a real, non-deterministic tier and flip the test's outcome. Three of
    // these tests call the public `save()` (not just `load()`), so getting
    // this isolation wrong doesn't just make a test flaky — it overwrites
    // that developer's real config file.
    //
    // Every test below ALSO pins `TRACEVAULT_PROJECT` unset. Since the A2
    // fix, `capture_project` reads it at a rung ABOVE `session.active_
    // project`, so a developer who has exported it in their shell — or a
    // concurrently-running test in this same binary that sets it — would
    // otherwise silently change which project these verdicts resolve. The
    // crate lock serializes mutators against each other, but only holding
    // the lock AND declaring the var's value makes a reader safe.

    // ---- resolve_auth: `.tracevault/config.toml` is the lowest credential
    // ---- rung in `resolve_credentials`, so the inspector must know it too.

    /// Isolate the env and the credentials file so nothing on the developer's
    /// machine can supply a credential these tests are asserting the absence of.
    fn auth_fixture() -> (
        tempfile::TempDir,
        tokio::sync::MutexGuard<'static, ()>,
        crate::test_helpers::EnvVarGuard,
    ) {
        let env_lock = crate::test_helpers::lock_env_mutation_sync();
        let dir = tempfile::tempdir().unwrap();
        let mut guard = crate::test_helpers::EnvVarGuard::new();
        guard.set("XDG_CONFIG_HOME", dir.path());
        guard.set("HOME", dir.path());
        guard.remove("TRACEVAULT_API_KEY");
        guard.remove("TRACEVAULT_SERVER_URL");
        (dir, env_lock, guard)
    }

    /// The reported bug: a repo authenticated purely through `config.toml`
    /// works for every command, but `status` called it "no credentials found"
    /// and exited non-zero.
    #[test]
    fn a_config_only_setup_reads_as_logged_in() {
        let (_dir, _lock, _guard) = auth_fixture();

        let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));

        assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
        assert!(
            matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_config"),
            "the config's key is the credential every command resolves"
        );
        assert_eq!(auth.source, "project config (.tracevault/config.toml)");
    }

    /// `resolve_credentials` resolves the URL and the credential independently,
    /// so an env key with the URL pinned only in the config is a working setup
    /// — it used to report "token found but no server URL".
    #[test]
    fn an_env_key_takes_its_url_from_the_config_when_the_env_has_none() {
        let (_dir, _lock, mut guard) = auth_fixture();
        guard.set("TRACEVAULT_API_KEY", "tvk_from_env");

        let auth = resolve_auth(Some("http://localhost:8080"), None);

        assert_eq!(auth.server_url.as_deref(), Some("http://localhost:8080"));
        assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_env"));
        assert_eq!(auth.source, "env (TRACEVAULT_API_KEY)");
    }

    /// The config is the LOWEST rung: a credentials file still outranks it, and
    /// its URL still wins, which is what the conflict warning then reports on.
    #[test]
    fn the_credentials_file_still_outranks_the_config() {
        let (dir, _lock, _guard) = auth_fixture();
        let creds_dir = dir.path().join("tracevault");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            r#"{"server_url":"https://dev.example.com","token":"tvk_from_file","email":"a@b.com"}"#,
        )
        .unwrap();

        let auth = resolve_auth(Some("http://localhost:8080"), Some("tvk_from_config"));

        assert_eq!(auth.server_url.as_deref(), Some("https://dev.example.com"));
        assert!(matches!(auth.credential, Some(Credential::ApiKey(ref k)) if k == "tvk_from_file"));
        assert_eq!(auth.source, "credentials file (API key)");
    }

    /// Nothing anywhere is still "none" — the fallback must not start claiming
    /// a credential just because a config exists without one.
    #[test]
    fn a_config_without_a_key_is_still_not_logged_in() {
        let (_dir, _lock, _guard) = auth_fixture();

        let auth = resolve_auth(Some("http://localhost:8080"), None);

        assert!(auth.credential.is_none());
        assert_eq!(auth.source, "none");
        assert_eq!(
            auth.server_url.as_deref(),
            Some("http://localhost:8080"),
            "the pin is still worth reporting"
        );
    }

    #[test]
    fn verdict_repo_user_default_alone_is_not_an_error() {
        // `repo switch --user` is `resolve_stream_binding`'s lowest tier.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        crate::user_default::save(&repo_binding_for_attribution(
            "11111111-1111-4111-8111-111111111111",
        ))
        .unwrap();

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
        assert_eq!(
            attribution,
            Some(crate::commands::stream::Attribution::Repo {
                repo_id: "11111111-1111-4111-8111-111111111111".into(),
                project: None,
            })
        );
        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
    }

    #[test]
    fn verdict_project_user_default_alone_is_not_an_error() {
        // `project switch --user` with no credential configured: the display
        // half of this same fallback is pinned separately by
        // `offline_project_outcome_falls_back_to_saved_user_default`.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let pb = crate::session_state::ProjectBinding {
            project_id: uuid::Uuid::from_u128(7).to_string(),
            project_name: "p".into(),
            updated_at: "".into(),
            forced_until: None,
        };
        crate::user_project_default::save(&pb).unwrap();

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
        assert_eq!(
            attribution,
            Some(crate::commands::stream::Attribution::ProjectOnly {
                project_id: uuid::Uuid::from_u128(7)
            })
        );
        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
    }

    #[test]
    fn verdict_config_without_repo_id_and_nothing_else_is_error() {
        // A loaded `config.toml` with no `repo_id` must not count as bound —
        // `binding_from_config` returns `None` for it.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let config = crate::config::TracevaultConfig::default();
        assert!(
            crate::resolution::binding_from_config(&config).is_none(),
            "a repo_id-less config must not bind"
        );

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
        assert_eq!(
            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
            Some(Level::Error)
        );
    }

    #[test]
    fn verdict_nothing_anywhere_is_error() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
        assert_eq!(
            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
            Some(Level::Error)
        );
    }

    #[test]
    fn verdict_deduced_project_display_does_not_suppress_recording_error() {
        // A `Deduced` DISPLAY value must not make the project axis count as
        // bound for the verdict — `capture_project` never deduces.
        let outcome: ProjectOutcome = Ok(Some((
            project_binding("pid", ""),
            crate::resolution::ProjectSource::Deduced,
        )));
        assert_eq!(project_binding_check(&outcome).level, Level::Warn);

        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), None);
        assert_eq!(
            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
            Some(Level::Error),
            "a Deduced display value must not suppress the Recording error"
        );
    }

    #[test]
    fn verdict_deduction_failure_is_warn_and_does_not_affect_recording() {
        // A deduction failure (network blip, 5xx, or genuinely Ambiguous)
        // must render at most Warn, and — since `recording_check` never even
        // sees `project_outcome` — cannot suppress or trigger the Recording
        // verdict either way.
        let outcome: ProjectOutcome = Err("this repo belongs to multiple projects".into());
        assert_eq!(project_binding_check(&outcome).level, Level::Warn);

        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let config = crate::config::TracevaultConfig {
            repo_id: Some("22222222-2222-4222-8222-222222222222".into()),
            ..Default::default()
        };
        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(None, None, cwd.path(), Some(&config));
        // Repo bound (via config) independently of the deduction failure
        // above -> no error, and nothing about the `Err` outcome forced one.
        assert!(recording_check(Some("s"), attribution.as_ref()).is_none());
    }

    #[test]
    fn offline_project_outcome_falls_back_to_saved_user_default() {
        // A saved `project switch --user` default must surface as Ok, not
        // Skip, in the credential-less path — not just the pure local tiers,
        // which `effective_project` alone covers.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above

        let pb = crate::session_state::ProjectBinding {
            project_id: uuid::Uuid::from_u128(9).to_string(),
            project_name: "My Project".into(),
            updated_at: "".into(),
            forced_until: None,
        };
        crate::user_project_default::save(&pb).unwrap();

        let session = crate::session_state::SessionState::default();
        let inputs = ProjectResolveInputs {
            project_flag: None,
            env_project: None,
            session: &session,
            worktree_path: None,
            config_project: None,
        };
        // Same call `run_status`'s credential-less arm makes.
        let user_default_project = crate::user_project_default::load();
        let outcome = offline_project_outcome(&inputs, user_default_project);
        let check = project_binding_check(&outcome);
        assert_eq!(check.level, Level::Ok, "detail: {}", check.detail);
        assert!(
            check.detail.contains("My Project"),
            "detail: {}",
            check.detail
        );
    }

    /// VIS-305 Part A fix: `run_status`'s client-backed arm must resolve
    /// `TRACEVAULT_PROJECT`'s UUID form at the `Env` rung, and the resulting
    /// `Check` must read Ok (not the "not used for attribution at capture
    /// time" Warn) — `capture_project` genuinely honours this tier as of the
    /// A2 fix, so the diagnostic disagreeing with real behaviour would be
    /// exactly the bug this batch closes.
    #[tokio::test]
    async fn online_project_outcome_resolves_env_uuid_and_reads_ok() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        let uuid = "55555555-5555-4555-8555-555555555555";
        _guard.set("TRACEVAULT_PROJECT", uuid);

        // No `list_projects` mock: the UUID form must resolve without one.
        let client = ApiClient::new("http://127.0.0.1:0", Some("tok"));
        let session = crate::session_state::SessionState::default();
        let outcome = online_project_outcome(&client, None, &session, "/wt", None, None).await;
        let (b, source) = outcome
            .unwrap()
            .expect("TRACEVAULT_PROJECT must resolve to a binding");
        assert_eq!(source, ProjectSource::Env);
        assert_eq!(b.project_id, uuid);

        let check = project_binding_check(&Ok(Some((b, source))));
        assert_eq!(
            check.level,
            Level::Ok,
            "an Env-sourced binding is honoured by capture_project and must read Ok: {}",
            check.detail
        );
    }

    /// VIS-305 Part A fix, name form: with a client in scope,
    /// `TRACEVAULT_PROJECT` set to a NAME must resolve via `list_projects`,
    /// mirroring `commands::project`'s `status`.
    #[tokio::test]
    async fn online_project_outcome_resolves_env_name_via_the_client() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("TRACEVAULT_PROJECT", "payments");

        let list =
            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
        let (base, _rx) =
            crate::test_helpers::spawn_seq(vec![crate::test_helpers::http_json("200 OK", &list)]);
        let client = ApiClient::new(&base, Some("tok"));
        let session = crate::session_state::SessionState::default();
        let outcome = online_project_outcome(&client, None, &session, "/wt", None, None).await;
        let (b, source) = outcome
            .unwrap()
            .expect("a name should resolve via list_projects");
        assert_eq!(source, ProjectSource::Env);
        assert_eq!(b.project_name, "payments");
        assert_eq!(b.project_id, "11111111-1111-4111-8111-111111111111");
    }

    #[test]
    fn recording_attribution_finds_subagent_override_via_linked_worktree_cwd() {
        // The subagent override is keyed by the LINKED worktree's own
        // toplevel, not the primary repo's — resolving from the wrong one
        // must miss it.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let base = tempfile::tempdir().unwrap();
        let repo_dir = base.path().join("repo");
        let wt_dir = base.path().join("wt");
        std::fs::create_dir_all(&repo_dir).unwrap();
        crate::test_helpers::init_git_repo(&repo_dir);
        crate::test_helpers::add_worktree(&repo_dir, &wt_dir);

        let wt_key = crate::paths::worktree_toplevel(&wt_dir);
        let project_id = uuid::Uuid::from_u128(42);
        let mut subagent_projects = std::collections::HashMap::new();
        subagent_projects.insert(
            wt_key,
            crate::session_state::ProjectBinding {
                project_id: project_id.to_string(),
                project_name: "linked".into(),
                updated_at: "t".into(),
                forced_until: None,
            },
        );
        let state = crate::session_state::SessionState {
            subagent_projects,
            ..Default::default()
        };
        let sessions_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            sessions_dir.path().join("sess-linked.toml"),
            toml::to_string(&state).unwrap(),
        )
        .unwrap();

        // From the LINKED worktree cwd, the subagent override resolves.
        let (found, _worktree) = recording_attribution(
            Some(sessions_dir.path()),
            Some("sess-linked"),
            &wt_dir,
            None,
        );
        assert_eq!(
            found,
            Some(crate::commands::stream::Attribution::ProjectOnly { project_id })
        );

        // From the PRIMARY worktree root instead, the key doesn't match, so
        // nothing resolves.
        let (missed, _worktree) = recording_attribution(
            Some(sessions_dir.path()),
            Some("sess-linked"),
            &repo_dir,
            None,
        );
        assert_eq!(missed, None);
    }

    #[test]
    fn verdict_malformed_project_id_leaves_project_axis_unbound() {
        // Pins that the display fix (`project_binding_check`) and the real
        // verdict (`recording_attribution` -> `capture_project`) cannot
        // diverge: a malformed `project_id` must be dropped by both.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let state = crate::session_state::SessionState {
            active_project: Some(project_binding("not-a-uuid", "My Project")),
            ..Default::default()
        };
        let sessions_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            sessions_dir.path().join("sess-bad-project.toml"),
            toml::to_string(&state).unwrap(),
        )
        .unwrap();

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(
            Some(sessions_dir.path()),
            Some("sess-bad-project"),
            cwd.path(),
            None,
        );
        assert_eq!(
            attribution, None,
            "a malformed project_id must not resolve an attribution"
        );
        assert_eq!(
            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
            Some(Level::Error)
        );
    }

    #[test]
    fn verdict_malformed_repo_id_with_nothing_else_bound_is_error() {
        // Same principle, repo axis: `attribution_for` drops a binding whose
        // `repo_id` fails `binding_repo_id_is_valid`, so nothing else bound
        // must still error, matching `workspace_binding_*_malformed_repo_id_*`.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let cfg_tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", cfg_tmp.path());
        _guard.set("HOME", cfg_tmp.path()); // see isolation note above
        _guard.remove("TRACEVAULT_PROJECT"); // see isolation note above

        let state = crate::session_state::SessionState {
            active: Some(crate::session_state::RepoBinding {
                repo_id: "not-a-uuid".into(),
                git_url: None,
                remote_id: None,
                codebase_name: None,
                updated_at: "t".into(),
            }),
            ..Default::default()
        };
        let sessions_dir = tempfile::tempdir().unwrap();
        std::fs::write(
            sessions_dir.path().join("sess-bad-repo.toml"),
            toml::to_string(&state).unwrap(),
        )
        .unwrap();

        let cwd = tempfile::tempdir().unwrap();
        let (attribution, _worktree) = recording_attribution(
            Some(sessions_dir.path()),
            Some("sess-bad-repo"),
            cwd.path(),
            None,
        );
        assert_eq!(
            attribution, None,
            "a malformed repo_id must not resolve an attribution"
        );
        assert_eq!(
            recording_check(Some("s"), attribution.as_ref()).map(|c| c.level),
            Some(Level::Error)
        );
    }
}