tracevault-cli 0.29.8

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
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
use crate::program::{CLI, TOP};
use std::collections::HashMap;
use std::fs::{self, OpenOptions};
use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
use std::path::Path;

use tracevault_protocol::hooks::{parse_hook_event, HookResponse};
use tracevault_protocol::streaming::{
    extract_is_error_from_transcript, StreamEventRequest, StreamEventType, MAX_REQUEST_BYTES,
};

/// Convert a resolved [`crate::context::EffectiveContext`] into the three
/// optional fields that are stamped onto a [`StreamEventRequest`].
///
/// - `flow_id`  — taken directly from `ctx.flow_id`
/// - `labels`   — `None` when the vec is empty, `Some(vec)` otherwise
/// - `params`   — `None` when the map is empty, `Some(HashMap)` otherwise
///   (BTreeMap → HashMap conversion)
///
/// This is a pure function so it can be unit-tested without I/O.
#[allow(clippy::type_complexity)]
pub fn apply_context(
    ctx: crate::context::EffectiveContext,
) -> (
    Option<String>,
    Option<Vec<String>>,
    Option<HashMap<String, String>>,
) {
    let flow_id = ctx.flow_id;
    let labels = if ctx.labels.is_empty() {
        None
    } else {
        Some(ctx.labels)
    };
    let params = if ctx.params.is_empty() {
        None
    } else {
        Some(ctx.params.into_iter().collect())
    };
    (flow_id, labels, params)
}

/// Returns `(lines, start_offset, end_offset)`: `start_offset` is the seek
/// position read from `offset_path` (0 if absent), and `end_offset` is the
/// byte offset after the last line read (the old `bytes_read`).
///
/// Callers should send `start_offset` as `StreamEventRequest::transcript_offset`
/// (so the server's `chunk_index = transcript_offset + line_index` is stable
/// per physical line across overlapping/retried reads) and persist
/// `end_offset` to `.stream_offset` as the next read's seek position.
pub fn read_new_transcript_lines(
    transcript_path: &Path,
    offset_path: &Path,
) -> Result<(Vec<serde_json::Value>, i64, i64), io::Error> {
    let batch = read_transcript_batch(transcript_path, offset_path, i64::MAX)?;
    Ok((batch.lines, batch.start, batch.end))
}

/// How much of a transcript one hook reads. A hook has a few seconds to send
/// in, and what it holds it holds parsed; a backlog larger than this (a
/// resumed session's transcript, a server that was away) is caught up on over
/// the next hooks instead, each advancing the read offset by what it sent.
pub const MAX_BATCH_BYTES: i64 = 4 * 1024 * 1024;

/// What a hook read of a transcript: the lines, where each ends in the file
/// (`ends[i]` is the byte offset after `lines[i]`), and the byte range read.
#[derive(Debug, Default)]
pub struct TranscriptBatch {
    pub lines: Vec<serde_json::Value>,
    pub ends: Vec<i64>,
    pub start: i64,
    pub end: i64,
}

impl TranscriptBatch {
    /// Where the next read starts after `delivered`: the end of the batch
    /// when every line was accepted or queued, else the end of the last line
    /// that was, and `None` when none was. Lines read from there on get new
    /// chunk_indexes, all past those of the lines before them: an index is
    /// the batch's byte offset plus the line's position, and a line is longer
    /// than one byte.
    pub fn next_offset(&self, delivered: &Delivered) -> Option<i64> {
        if delivered.lines >= self.ends.len() {
            return Some(self.end);
        }
        delivered
            .lines
            .checked_sub(1)
            .and_then(|last| self.ends.get(last))
            .copied()
    }
}

/// [`read_new_transcript_lines`], reading no further than the line that
/// reaches `max_bytes`.
pub fn read_transcript_batch(
    transcript_path: &Path,
    offset_path: &Path,
    max_bytes: i64,
) -> Result<TranscriptBatch, io::Error> {
    // An empty path means "no transcript yet" — Codex documents `transcript_path`
    // as nullable (e.g. on SessionStart before a rollout exists), and the hook
    // payload deserializes null/absent to "". Guard explicitly so we never hand
    // `Path::new("")` to `exists()`/`File::open` (whose behavior on an empty path
    // is platform-dependent); treat it as a clean no-op.
    if transcript_path.as_os_str().is_empty() || !transcript_path.exists() {
        return Ok(TranscriptBatch::default());
    }

    let offset: i64 = if offset_path.exists() {
        let content = fs::read_to_string(offset_path)?;
        content
            .trim()
            .parse::<i64>()
            .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
    } else {
        0
    };

    let mut file = fs::File::open(transcript_path)?;
    file.seek(SeekFrom::Start(offset as u64))?;

    let reader = io::BufReader::new(file);
    let mut lines = Vec::new();
    let mut ends = Vec::new();
    let mut bytes_read = offset;

    for line_result in reader.lines() {
        let line = line_result?;
        // +1 for the newline character
        bytes_read += line.len() as i64 + 1;
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&line) {
            lines.push(value);
            ends.push(bytes_read);
        }
        if bytes_read - offset >= max_bytes {
            break;
        }
    }

    Ok(TranscriptBatch {
        lines,
        ends,
        start: offset,
        end: bytes_read,
    })
}

/// Move the read offset `offset_path` holds forward to `to`, never back: two
/// hooks of a session can read from one offset at the same time, and the one
/// that got less through must not undo the other's progress, or the lines
/// between are sent again under new chunk_indexes and stored twice.
fn advance_offset(offset_path: &Path, to: i64) -> io::Result<()> {
    // Read, compare and replace as one step: without the lock the hook with
    // the smaller offset can still write last.
    let _lock = crate::pending_queue::lock(&offset_path.with_extension("advance.lock"))?;
    let current = fs::read_to_string(offset_path)
        .ok()
        .and_then(|c| c.trim().parse::<i64>().ok());
    if current.is_some_and(|c| c >= to) {
        return Ok(());
    }
    crate::subagents::write_offset(offset_path, to)
}

/// Store `transcript_path` in the session's `metadata.json`, which is where
/// `tracevault check` looks for the transcript it counts tool calls from.
/// Without it every session reports no tool calls, and a "must call X" policy
/// can never pass. Other keys in the file are kept. An empty path (Codex
/// before its first record) writes nothing, and an unchanged path skips the
/// write. The file is replaced atomically: parallel tool hooks of one session
/// run concurrently, and `check` must never read a half-written file.
pub fn record_transcript_path(session_dir: &Path, transcript_path: &str) -> Result<(), io::Error> {
    if transcript_path.is_empty() {
        return Ok(());
    }
    record_metadata(
        session_dir,
        "transcript_path",
        serde_json::Value::String(transcript_path.to_string()),
    )
}

/// The session's `metadata.json`; `{}` when it is missing or unreadable.
pub(crate) fn session_metadata(session_dir: &Path) -> serde_json::Value {
    fs::read_to_string(session_dir.join("metadata.json"))
        .ok()
        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
        .filter(serde_json::Value::is_object)
        .unwrap_or_else(|| serde_json::json!({}))
}

/// Set `key` in the session's `metadata.json`, keeping its other keys. An
/// unchanged value skips the write; the file is replaced atomically (see
/// [`record_transcript_path`]).
fn record_metadata(
    session_dir: &Path,
    key: &str,
    value: serde_json::Value,
) -> Result<(), io::Error> {
    let mut meta = session_metadata(session_dir);
    if meta.get(key) == Some(&value) {
        return Ok(());
    }
    meta[key] = value;
    let tmp = session_dir.join(format!(".metadata.json.{}", uuid::Uuid::now_v7()));
    fs::write(&tmp, meta.to_string())?;
    fs::rename(&tmp, session_dir.join("metadata.json")).inspect_err(|_| {
        let _ = fs::remove_file(&tmp);
    })
}

/// `attribution` as the session's hooks record it in `metadata.json`.
fn attribution_record(attribution: &Attribution) -> serde_json::Value {
    match attribution {
        Attribution::Repo { repo_id, project } => {
            serde_json::json!({"repo_id": repo_id, "project_id": project})
        }
        Attribution::ProjectOnly { project_id } => {
            serde_json::json!({"repo_id": null, "project_id": project_id})
        }
    }
}

/// Whether the catch-up sweep may send an earlier session's lines under
/// `now`, the attribution that resolves today. Bindings can change after a
/// session ended (a new default project, say), so it must be the one the
/// session's own hooks recorded. A session recorded by an older CLI has
/// none: it is sent when repo-attributed, since the server keys its row by
/// the repo and never moves a project once stamped, and left alone when
/// project-only, since there the project picks the row.
pub(crate) fn catch_up_may_send(recorded: Option<&serde_json::Value>, now: &Attribution) -> bool {
    match recorded {
        Some(recorded) => *recorded == attribution_record(now),
        None => matches!(now, Attribution::Repo { .. }),
    }
}

/// Fileless agents (OpenCode) have no transcript for `tracevault check` to
/// count tool calls from: their records ride inline on each hook event. Append
/// one slim `toolCall` record per tool called in `records` to the session's
/// `tool_calls.jsonl` and record that file as the session's transcript. Only
/// the tool name is kept — arguments and outputs (file contents, bash stdout)
/// would grow the file for nothing. Records with no tool call write nothing.
pub fn record_inline_tool_calls(
    session_dir: &Path,
    records: &[serde_json::Value],
) -> Result<(), io::Error> {
    let lines: String = records
        .iter()
        .flat_map(crate::transcript::tool_call_names)
        .map(|name| {
            let record = serde_json::json!({
                "type": "message",
                "message": {"role": "assistant", "content": [{"type": "toolCall", "name": name}]},
            });
            format!("{record}\n")
        })
        .collect();
    if lines.is_empty() {
        return Ok(());
    }
    let log_path = session_dir.join("tool_calls.jsonl");
    OpenOptions::new()
        .create(true)
        .append(true)
        .open(&log_path)?
        .write_all(lines.as_bytes())?;
    record_transcript_path(session_dir, &log_path.to_string_lossy())
}

pub fn append_pending(pending_path: &Path, json: &str) -> Result<(), io::Error> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(pending_path)?;
    writeln!(file, "{json}")?;
    Ok(())
}

pub fn drain_pending(pending_path: &Path) -> Result<Vec<String>, io::Error> {
    if !pending_path.exists() {
        return Ok(vec![]);
    }
    let content = fs::read_to_string(pending_path)?;
    let lines: Vec<String> = content
        .lines()
        .filter(|l| !l.trim().is_empty())
        .map(String::from)
        .collect();
    fs::remove_file(pending_path)?;
    Ok(lines)
}

/// How a stream event is attributed on the wire, resolved from the local repo
/// and project bindings before anything is sent.
///
/// The rule this type encodes: an event ships when EITHER a repo or a project
/// resolves. Before this existed the hook required a repo binding and dropped
/// the event otherwise, which silently discarded every event of a repo-less
/// session even when its project was bound — despite the server supporting
/// exactly that shape (`ProjectStreamQuery::repo_id` is `Option<Uuid>`:
/// "repo-less (0-repo) projects are supported").
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum Attribution {
    /// A usable repo binding resolved. `project` is the capture-time project
    /// overlay; when `None` the server deduces the project from the repo.
    Repo {
        repo_id: String,
        project: Option<uuid::Uuid>,
    },
    /// No usable repo binding, but a project did — repo-less project-scoped
    /// ingest.
    ProjectOnly { project_id: uuid::Uuid },
}

impl Attribution {
    /// Offline-queue filename for this attribution. Keyed by whatever
    /// identifies the target so a mid-session rebind (workspace mode) can
    /// never flush one target's queued events to another.
    ///
    /// The `project-` infix is load-bearing for back-compat: an older CLI's
    /// `repo_id_from_pending_filename` extracts `project-<uuid>` from this
    /// name, fails its UUID check, and skips the file — so a downgrade leaves
    /// these queues alone instead of trying to POST them at a repo endpoint.
    pub(crate) fn pending_file_name(&self) -> String {
        use crate::commands::flush::{PROJECT_QUEUE_PREFIX, QUEUE_PREFIX, QUEUE_SUFFIX};
        match self {
            Self::Repo { repo_id, .. } => format!("{QUEUE_PREFIX}{repo_id}{QUEUE_SUFFIX}"),
            Self::ProjectOnly { project_id } => {
                format!("{PROJECT_QUEUE_PREFIX}{project_id}{QUEUE_SUFFIX}")
            }
        }
    }
}

/// Pure attribution resolver: fold the repo binding and the capture-time
/// project into the target this event will be sent to. `None` means neither
/// resolved and the hook must no-op.
///
/// A binding whose `repo_id` is not a UUID degrades to `ProjectOnly` rather
/// than dropping the event — a corrupted session-state file should cost the
/// repo attribution, not the whole trace, when a project is available.
///
/// `project` here is whatever `capture_project` resolved, and its lowest tier
/// is the MACHINE-GLOBAL `project switch --user` default — not just
/// session-scoped bindings. That tier is therefore now a sufficient condition
/// for an event to ship, where previously it could only redirect an event that
/// was already shipping because a repo bound. This is deliberate: it is the
/// only binding a container can establish before the agent session exists and
/// before the repo is cloned, which is the case this whole path serves.
/// `resolve_stream_binding` has the same machine-global tier for repos, so the
/// two sides stay symmetric. Consequence worth knowing: a session started in an
/// unrelated directory, with no repo and no `.visdom/`, will attribute to
/// that default project.
pub(crate) fn attribution_for(
    binding: Option<&crate::session_state::RepoBinding>,
    project: Option<uuid::Uuid>,
) -> Option<Attribution> {
    match binding.filter(|b| binding_repo_id_is_valid(&b.repo_id)) {
        Some(b) => Some(Attribution::Repo {
            repo_id: b.repo_id.clone(),
            project,
        }),
        None => project.map(|project_id| Attribution::ProjectOnly { project_id }),
    }
}

/// The project a session's event may infer its repo within (VIS-1258): the
/// capture-time `project`, but only when no repo binding resolved from any
/// tier. A binding — even one [`attribution_for`] cannot use — is the
/// session's explicit choice, which inference never overrides.
pub(crate) fn inference_project(
    binding: Option<&crate::session_state::RepoBinding>,
    project: Option<uuid::Uuid>,
) -> Option<uuid::Uuid> {
    match binding {
        Some(_) => None,
        None => project,
    }
}

/// [`attribution_for`] with the repo inferred for the event's checkout
/// (`crate::inferred_repo`), which applies only where [`inference_project`]
/// allows it. Ingest and `status` both go through this, so `status` reports
/// what the hook sends.
pub(crate) fn attribution_with_inference(
    binding: Option<&crate::session_state::RepoBinding>,
    project: Option<uuid::Uuid>,
    inferred: Option<&crate::session_state::RepoBinding>,
) -> Option<Attribution> {
    match (inference_project(binding, project), inferred) {
        (Some(pid), Some(repo)) if binding_repo_id_is_valid(&repo.repo_id) => {
            Some(Attribution::Repo {
                repo_id: repo.repo_id.clone(),
                project: Some(pid),
            })
        }
        _ => attribution_for(binding, project),
    }
}

/// What a session's events are sent under, as `status` reports it: the
/// [`Attribution`], and the checkout its repo was inferred from when it was
/// (VIS-1258) rather than bound.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Recording {
    pub attribution: Option<Attribution>,
    pub inferred_from: Option<String>,
}

/// Offline-queue path for an attribution target.
fn pending_path_for(session_dir: &Path, attribution: &Attribution) -> std::path::PathBuf {
    session_dir.join(attribution.pending_file_name())
}

/// The project-only queue a repo-scoped target takes over (VIS-1255), if any.
///
/// A session that started repo-less (umbrella dir, project bound) and then
/// gained a repo (`repo switch` mid-session) moves from `ProjectOnly { pid }`
/// to `Repo { project: Some(pid) }`. Events queued before the switch sit in
/// `pending-project-<pid>.jsonl`, which the repo target never reads. Left
/// there, they are either stranded or — via `tracevault flush` — delivered to
/// the server's repo-less session row, while the same transcript lines (the
/// offset did not advance for them) are re-read and sent to the repo row:
/// the same lines stored twice. The server keys a session by
/// `(repo_id, session_id)` when a repo is present and by
/// `(project_id, session_id) WHERE repo_id IS NULL` otherwise, and dedupes
/// lines per row, so the client must not split them. Draining the queue
/// under the current target puts them on the row the re-read lines go to,
/// where `chunk_index` dedupes them.
///
/// Only the SAME project is adopted: the repo send still declares that
/// project, so this refines where the events land within it instead of
/// re-attributing them. A `Repo` with a different or no project keeps the
/// per-target isolation [`Attribution::pending_file_name`] exists for.
///
/// What this cannot prevent (server-side, needs a row merge there): lines
/// the repo-less row ALREADY stored before the switch while `.stream_offset`
/// did not advance — a multi-part batch whose first parts were accepted and
/// a later one failed, or an accepted request whose response was lost. The
/// re-read after the switch sends those to the repo row too. The client
/// cannot tell which of them the other row holds, and advancing the offset
/// per accepted part would move every later line's `chunk_index` (it is
/// based on the read's start offset) and break dedupe within one row.
fn adopted_project_queue(
    session_dir: &Path,
    attribution: &Attribution,
) -> Option<std::path::PathBuf> {
    match attribution {
        Attribution::Repo {
            project: Some(project_id),
            ..
        } => Some(pending_path_for(
            session_dir,
            &Attribution::ProjectOnly {
                project_id: *project_id,
            },
        )),
        _ => None,
    }
}

/// Resolve the project root and session directory for a stream hook invocation.
///
/// This is the pure, testable core of `run_stream`'s path resolution. It uses
/// [`crate::paths::resolve_project_root`] which queries `git rev-parse
/// --git-common-dir` first, so it correctly resolves to the **primary**
/// `.visdom/` directory from any worktree — including sibling linked
/// worktrees where the primary `.visdom/` is not an ancestor of `hook_cwd`.
///
/// Returns `(resolved, session_dir)` — the resolved
/// [`crate::paths::ProjectRoot`] (so callers can inspect `.source`, e.g. to warn
/// on a Fallback that would create a stray `.visdom/`) and `session_dir`
/// under `<resolved.root>/.visdom/sessions/<session_id>/`.
pub fn resolve_session_paths(
    hook_cwd: &Path,
    session_id: &str,
) -> (crate::paths::ProjectRoot, std::path::PathBuf) {
    let resolved = crate::paths::resolve_project_root(hook_cwd);
    let session_dir = crate::layout::session_dir(&resolved.root, session_id);
    (resolved, session_dir)
}

/// A resolved binding is usable for hook attribution only if its repo_id is a
/// real UUID — guards against a corrupted/edited session-state file injecting
/// path separators into the pending-<repo_id>.jsonl filename.
///
/// `pub(crate)`: also called by `commands::status`, so a binding with a
/// malformed `repo_id` is never displayed as bound (`Check::ok`) when this
/// same check means the hook will not actually honor it.
pub(crate) fn binding_repo_id_is_valid(repo_id: &str) -> bool {
    uuid::Uuid::parse_str(repo_id).is_ok()
}

/// The effective repo binding for a stream event, given the loaded session
/// state, the event's worktree, and the bound-config fallback. Pure — the
/// hook path has no repo-override flag, so `repo_flag` is always `None` here.
pub(crate) fn resolve_stream_binding(
    session: &crate::session_state::SessionState,
    worktree: &str,
    bound: Option<crate::session_state::RepoBinding>,
    user_default: Option<crate::session_state::RepoBinding>,
) -> Option<crate::session_state::RepoBinding> {
    crate::resolution::effective_binding(crate::resolution::ResolveInputs {
        repo_flag: None,
        session,
        worktree_path: Some(worktree),
        bound,
        user_default,
    })
    .map(|(b, _)| b)
}

/// `TRACEVAULT_PROJECT` as a binding, UUID form only.
///
/// A project NAME would require a `list_projects` round trip, and the capture
/// path fires per event in a short-lived process — the same reason
/// `capture_project` already ignores the repo config's `default_project`. The
/// name form is honoured by the interactive commands, which already have a
/// client in hand.
pub(crate) fn env_project_binding() -> Option<crate::session_state::ProjectBinding> {
    let raw = std::env::var("TRACEVAULT_PROJECT").ok()?;
    let raw = raw.trim();
    let parsed = raw.parse::<uuid::Uuid>().ok()?;
    Some(crate::session_state::ProjectBinding {
        project_id: parsed.to_string(),
        project_name: String::new(),
        updated_at: String::new(),
        forced_until: None,
    })
}

/// WHICH of the two force sources put a send into `explicit` attribution —
/// the reason behind [`attribution_mode`]'s verdict, not a second opinion on
/// it.
///
/// The two sources are not interchangeable and, crucially, are not undone
/// the same way: the env var is process-wide and cleared by unsetting it,
/// while a persisted force lives on the binding and is cleared by switching
/// again without the flag. Any message that tells an operator how to STOP
/// forcing therefore has to know which one is actually in effect — telling
/// someone whose force came from `TRACEVAULT_PROJECT_ATTRIBUTION` to drop a
/// CLI flag is advice that silently changes nothing (Copilot on PR #54).
///
/// This carries the reason alongside the verdict instead of letting the
/// message-building code re-derive it, because re-deriving it would mean a
/// second copy of the env-var read and the `forced_until` parse — exactly
/// the two-codepaths-for-one-fact shape whose removal is the whole point of
/// [`attribution_mode`] taking the winning binding as a parameter.
///
/// `Default` is "neither source is forcing", i.e. plain derived attribution
/// — the ordinary case, and what a test that cares about routing rather
/// than attribution wants to pass.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) struct AttributionForce {
    /// `TRACEVAULT_PROJECT_ATTRIBUTION=explicit` is set in this process's
    /// environment. Never expires; only unsetting it stops the forcing.
    pub(crate) env: bool,
    /// The winning binding carries a LIVE `forced_until`. Lapses on its own
    /// (~12h); `project switch` without `--project-attribution explicit`
    /// clears it immediately.
    pub(crate) binding: bool,
}

impl AttributionForce {
    /// The verdict these sources add up to. Either source alone forces;
    /// neither does not.
    pub(crate) fn mode(self) -> crate::api_client::AttributionMode {
        if self.env || self.binding {
            crate::api_client::AttributionMode::Explicit
        } else {
            crate::api_client::AttributionMode::Derived
        }
    }
}

/// Which attribution mode THIS PARTICULAR winning binding declares.
///
/// `explicit` comes either from `TRACEVAULT_PROJECT_ATTRIBUTION` (per-process,
/// re-asserted at every launch, no expiry — genuinely global, by design) OR
/// from a LIVE `forced_until` carried by `effective` — the exact
/// [`crate::session_state::ProjectBinding`] that [`capture_project`] resolved
/// as the one this event is being attributed to.
///
/// `forced_until` is stored PER-BINDING (see that field's own doc comment:
/// "the FORCE lapses (the binding itself survives)"), so this must read the
/// force off THAT binding and no other. An earlier version of this function
/// instead did a process-global disk read
/// (`user_project_default::load_with_force()`), which had it backwards two
/// ways at once: a session-scoped force (`project switch` without `--user`,
/// which is the ordinary case whenever a session id is set) is written into
/// session state and was never read there at all, so it silently never took
/// effect while still telling the user membership was not being checked; and
/// a live force sitting on the user-level default leaked onto ANY
/// higher-precedence project that happened to resolve instead (subagent
/// override, `TRACEVAULT_PROJECT`, session active), stamping `explicit` for a
/// project nobody forced. Taking `effective` as a parameter — the actual
/// winning binding — makes both mistakes impossible: a force can only apply
/// when it is attached to the binding actually being used.
///
/// Whether that force is live is [`crate::session_state::force_status`]'s
/// answer, not this function's: `commands::project`'s status line reads the
/// same field and must never disagree with the header this fills, so there is
/// exactly one parse and one `Utc::now()` comparison. A lapsed persisted
/// force reads as `derived` — not sending an `explicit` header IS the
/// fallback, so ingest never starts failing because a force was forgotten —
/// and so does an unparseable one, for the same fail-safe reason.
///
/// An unrecognised (or absent) `TRACEVAULT_PROJECT_ATTRIBUTION` also reads as
/// `derived`, deliberately asymmetric with the server, which 400s an unknown
/// value: that strictness is for callers that bypass the CLI entirely, and
/// failing a hook over a typo'd env var helps nobody — silently falling back
/// to the always-checked default is the safe direction to fail in.
///
/// This always returns one of the two variants and the caller always sends
/// it as the header — including the
/// [`crate::api_client::AttributionMode::Derived`] case. The
/// server treats an absent header and an explicit `derived` value
/// identically, but nothing here omits the header; "always emits one of two
/// values" is simpler to reason about than "sometimes sends a header,
/// sometimes doesn't."
///
/// A verdict only. Callers that must also explain THE REASON — the refusal
/// remediation, which has to name the force source it is telling the
/// operator to remove — take [`attribution_force`] instead and call
/// [`AttributionForce::mode`] on it; both spellings run the one evaluation
/// below.
pub(crate) fn attribution_mode(
    effective: Option<&crate::session_state::ProjectBinding>,
) -> crate::api_client::AttributionMode {
    attribution_force(effective).mode()
}

/// The single evaluation behind [`attribution_mode`]: reads both force
/// sources ONCE and reports each separately, so the verdict and any
/// explanation of it are the same fact viewed twice rather than two facts
/// that can drift. See [`AttributionForce`] for why the distinction is
/// load-bearing, and [`attribution_mode`]'s doc comment for why each source
/// is read the way it is.
pub(crate) fn attribution_force(
    effective: Option<&crate::session_state::ProjectBinding>,
) -> AttributionForce {
    AttributionForce {
        env: std::env::var("TRACEVAULT_PROJECT_ATTRIBUTION")
            .map(|v| v.trim().eq_ignore_ascii_case("explicit"))
            .unwrap_or(false),
        binding: effective
            .and_then(|b| b.forced_until.as_deref())
            .is_some_and(|s| {
                matches!(
                    crate::session_state::force_status(s),
                    crate::session_state::ForceStatus::Live(_)
                )
            }),
    }
}

/// The capture-time project BINDING for a stream event: a thin wrapper over
/// the shared chain [`crate::resolution::capture_project_binding`] (subagent
/// worktree override -> `TRACEVAULT_PROJECT` -> session `active_project` ->
/// workspace `.visdom/tracing.toml` `project_id` -> user-level default; no
/// `--project` flag on the hook path), with a binding whose stored id is not a
/// UUID dropped exactly as [`crate::resolution::capture_project_id`] drops it.
/// Local only — no network (the hook fires per event in a short-lived
/// process), which is why the config tier is its `project_id` (a UUID, via
/// [`crate::resolution::project_from_config`]) and never the legacy
/// `default_project` name, and why `TRACEVAULT_PROJECT` is honoured in its
/// UUID form only. `config_project` is that config tier, read by the caller
/// from the config it already loaded. `commands::project::status` calls the
/// same shared chain, so it reports exactly what this returns.
///
/// Returns the full [`crate::session_state::ProjectBinding`], not just its
/// id: `forced_until` travels with whichever binding actually wins this
/// precedence chain, so a caller can ask THAT binding — via
/// [`attribution_mode`] — whether it is currently forced, rather than
/// consulting some other, unrelated binding (see `attribution_mode`'s doc
/// comment for why that distinction matters). Callers that only need the id
/// use [`capture_project`].
pub(crate) fn capture_binding(
    session: &crate::session_state::SessionState,
    worktree_path: Option<&str>,
    config_project: Option<crate::session_state::ProjectBinding>,
) -> Option<crate::session_state::ProjectBinding> {
    use crate::resolution::{capture_project_binding, capture_project_id, CaptureProjectInputs};
    let (binding, _) = capture_project_binding(&CaptureProjectInputs {
        project_flag: None,
        env_project: env_project_binding(),
        session,
        worktree_path,
        config_project,
        user_default: crate::user_project_default::load(),
    })?;
    // Defensive: a corrupted/hand-edited binding whose id isn't a real UUID
    // must not be usable for attribution at all (mirrors
    // `binding_repo_id_is_valid` for the repo side) — checked here, once, so
    // every caller gets the same guarantee rather than re-deriving it.
    capture_project_id(&binding)?;
    Some(binding)
}

/// The capture-time project ID for a stream event: [`capture_binding`]
/// projected down to its id. `None` -> fall back to the repo-scoped stream
/// (server deduces).
///
/// `pub(crate)`: also called by `commands::status`, which reuses this
/// function (plus `resolve_stream_binding`/`attribution_for`) as the
/// authoritative "will this session record anything" gate, so the status
/// verdict can never drift from what this hook actually does. `commands::flush`
/// and `commands::project::status` call it for the same reason.
pub(crate) fn capture_project(
    session: &crate::session_state::SessionState,
    worktree_path: Option<&str>,
    config_project: Option<crate::session_state::ProjectBinding>,
) -> Option<uuid::Uuid> {
    capture_binding(session, worktree_path, config_project)
        .as_ref()
        .and_then(crate::resolution::capture_project_id)
}

/// The hook's attribution gate for an already-loaded session: the same
/// `resolve_stream_binding` -> `capture_project` -> `attribution_for` chain
/// `stream_event` runs, minus the network auto-bind. Shared by `status`,
/// `repo status` and `project status` so all three report what ingest does
/// (VIS-158, VIS-316) — in particular a repo-less, project-only session
/// (VIS-1255), which `repo status` alone would show as "not bound" and
/// `project status` alone as merely "bound to project X".
///
/// A project-only session's repo inferred for `worktree` (VIS-1258) is read
/// from the session's cache — what the hook sends under there — and is
/// labelled as inferred. A checkout the hook has not looked up yet reads as
/// project-only until the session's first event there.
pub(crate) fn recording_attribution_for(
    session: &crate::session_state::SessionState,
    worktree: &str,
    bound: Option<crate::session_state::RepoBinding>,
    user_default_repo: Option<crate::session_state::RepoBinding>,
    config_project: Option<crate::session_state::ProjectBinding>,
) -> Recording {
    let stream_binding = resolve_stream_binding(session, worktree, bound, user_default_repo);
    let project = capture_project(session, Some(worktree), config_project);
    let inferred = inference_project(stream_binding.as_ref(), project)
        .and_then(|pid| crate::inferred_repo::cached_repo(session, worktree, pid));
    let attribution =
        attribution_with_inference(stream_binding.as_ref(), project, inferred.as_ref());
    let inferred_from = match (&attribution, &inferred) {
        (Some(Attribution::Repo { repo_id, .. }), Some(repo)) if *repo_id == repo.repo_id => {
            Some(worktree.to_string())
        }
        _ => None,
    };
    Recording {
        attribution,
        inferred_from,
    }
}

/// One `recording:` line describing a [`Recording`] for `repo status` and
/// `project status`. Pure, so the wording is asserted directly.
pub(crate) fn recording_line_for(recording: &Recording) -> String {
    if let (
        Some(Attribution::Repo {
            repo_id,
            project: Some(pid),
        }),
        Some(checkout),
    ) = (&recording.attribution, &recording.inferred_from)
    {
        return format!(
            "recording: repo {repo_id} in project {pid} — inferred from the checkout {checkout} \
             (no repo is bound; events in other checkouts go to their own repo in the project, \
             or to the project only)"
        );
    }
    recording_line(recording.attribution.as_ref())
}

/// The `recording:` line for an [`Attribution`] that was not inferred. Pure.
pub(crate) fn recording_line(attribution: Option<&Attribution>) -> String {
    match attribution {
        Some(Attribution::Repo {
            repo_id,
            project: None,
        }) => format!("recording: repo {repo_id} (the server deduces the project from the repo)"),
        Some(Attribution::Repo {
            repo_id,
            project: Some(pid),
        }) => format!("recording: repo {repo_id} in project {pid}"),
        Some(Attribution::ProjectOnly { project_id }) => format!(
            "recording: project {project_id} only — no repo is bound, so events are sent \
             without one (`{CLI} repo switch <path>` adds the repo)"
        ),
        None => "recording: nothing — neither a repo nor a project is bound, so this \
                 session's events are not sent"
            .to_string(),
    }
}

/// The one-line error printed when the server refuses a REPO-LESS
/// (project-only) send. The repo-scoped [`refused_error`] says the project
/// "does not apply to this repo", which is wrong when there is no repo, and
/// its remedy names only `project switch` — while for a repo-less session
/// `repo switch` is the other way out. Pure, so the wording is asserted
/// directly. The `explicit`-force clause is shared with [`refused_error`]:
/// the force gate refuses with the same 403 on either route.
///
/// VIS-1255: the event is QUEUED, not dropped (VIS-316: a deterministic 4xx
/// on a project-scoped send is an error that goes through the normal buffer
/// path). Dropping advanced `.stream_offset`, so the session's transcript
/// was lost with only a stderr line nobody reads in a hook.
pub(crate) fn refused_project_only_error(
    pid: uuid::Uuid,
    kind: &ClientErrorKind,
    force: AttributionForce,
) -> String {
    let base = match kind {
        ClientErrorKind::Forbidden => format!(
            "{TOP}: error: the server refused this repo-less session's event for project \
             {pid} (403). Either this account has no access to that project (no `Operator` \
             role on it) — run `{CLI} project switch <name>` (add `--user` if the binding \
             is the machine-wide default in `user_project.toml`) — or it has no `tracevault` \
             grant in Control Plane at all, which an administrator must grant. The session has \
             no repo binding, so the event was not sent anywhere else; it has been queued and \
             will be retried with the next event."
        ),
        ClientErrorKind::Scoping => format!(
            "{TOP}: error: project {pid} does not resolve on the server (400/404/409: it \
             does not exist, or this account cannot see it). The session has no repo binding, \
             so the event was not sent anywhere else; it has been queued and will be retried \
             with the next event. Run `{CLI} project switch <name>` (add `--user` if the \
             binding is the machine-wide default in `user_project.toml`) to bind a project that \
             exists, or `{CLI} repo switch <path>` to record this session to a repo."
        ),
    };
    with_force_clause(base, kind, force)
}

/// True when a stream-send error's rendered message carries a `(4xx ...)`
/// status marker — i.e. the server deterministically rejected the request in
/// a way that will never succeed on blind retry (bad binding, missing
/// permission, ambiguous repo, ...). Deliberately excludes 5xx and
/// transport/network/timeout failures (which have no `(NNN ` marker at all,
/// or a 5xx one) — those remain transient and must keep propagating so the
/// existing buffer/retry logic in `run_stream` still applies to them.
///
/// Takes `&dyn Error` rather than `&Box<dyn Error>` to avoid the clippy
/// `borrowed_box` lint at call sites that already hold a `Box<dyn Error>`.
///
/// COUPLING: the `"(NNN "` markers below must byte-for-byte match what
/// `ApiClient::authed_send_json`'s `err_prefix` closures render (e.g.
/// `stream_event`'s `"Stream failed ({status})"`, where `{status}` Displays
/// as `"404 Not Found"`, yielding `"Stream failed (404 Not Found): ..."` —
/// hence the `"(404 "` marker below matching on the open-paren + code + the
/// space before the reason phrase). If that error-formatting ever changes,
/// update this list (and its tests) to match.
/// Which deterministic client error this is, so the refusal error can name a
/// cause that is actually possible instead of assuming one.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum ClientErrorKind {
    /// 403, which now has TWO plausible causes — see [`send_stream_event`].
    Forbidden,
    /// 400/404/409: a binding/scoping problem, and only that.
    Scoping,
}

/// The one-line error printed when the server refuses a project-scoped send.
/// Pure, so the wording is asserted directly rather than by capturing stderr.
///
/// `force` is the force situation this send actually declared — the exact
/// [`AttributionForce`] whose [`AttributionForce::mode`] filled the
/// `x-tracevault-project-attribution` header, so the message and the wire
/// can never disagree. It matters because the force gate also refuses with a
/// 403: "not Operator on the project", or "`explicit` from a `tvk_` key".
/// Without naming it, an operator who asked for `explicit` got an error about
/// membership and realm roles and was never told the force itself was what
/// got refused. Failing closed on trust is right; failing closed silently is
/// the defect.
///
/// The force clause takes the whole `AttributionForce`, not just the mode,
/// because its remediation has to name the source ACTUALLY in effect. The
/// two are undone differently and only one of them by a CLI flag: an earlier
/// wording told everyone to switch again without `--project-attribution
/// explicit`, which for an env-sourced force clears a persisted
/// `forced_until` that may not even exist while [`attribution_force`] goes
/// on reading `TRACEVAULT_PROJECT_ATTRIBUTION` and every subsequent send
/// keeps declaring `explicit` — advice that silently does nothing, handed
/// out on the one code path a confused operator reaches (Copilot on PR #54).
/// [`force_remediation`] derives the fix from the same struct the header
/// came from, so it cannot name a source that is not set, or miss one that
/// is.
///
/// The extra clause is attached to `Forbidden` ONLY. A `Scoping` 4xx
/// (400/404/409) means the project id itself does not resolve — the force
/// gate never ran — so blaming the force there would be a new wrong
/// explanation of exactly the kind this fixes.
pub(crate) fn refused_error(
    pid: uuid::Uuid,
    kind: &ClientErrorKind,
    force: AttributionForce,
) -> String {
    let base = match kind {
        // Since Keycloak, a 403 has a SECOND and now more common cause: the
        // account has no `tracevault` grant in Control Plane, in which case nothing this
        // hook does will work and `project switch` is confidently wrong advice —
        // on the code path users hit most. The server's 403 envelope is not
        // distinguishable from here (see `ClientErrorKind`), so name both.
        ClientErrorKind::Forbidden => format!(
            "{TOP}: error: the server refused to attribute this event to active project \
             {pid} (403). Either that project does not apply to this repo (not a member, or \
             no `Operator` role on it) — run `{CLI} project switch <name>` (add `--user` if the \
             binding is the machine-wide default in `user_project.toml`) — or this account has \
             no `tracevault` grant in Control Plane at all, which an administrator must grant. \
             The event was NOT re-attributed elsewhere; it has been queued and will be retried \
             once the binding or the grant is fixed."
        ),
        ClientErrorKind::Scoping => format!(
            "{TOP}: error: active project {pid} does not apply to this repo (not a member, \
             missing permission, or the project no longer exists). The event was NOT \
             re-attributed elsewhere; it has been queued and will be retried once the binding is \
             fixed. Run `{CLI} project switch <name>` (add `--user` if the binding is the \
             machine-wide default in `user_project.toml`) to update it."
        ),
    };
    with_force_clause(base, kind, force)
}

/// Append the "the refusal may be of the FORCE itself" clause to a refusal
/// line when the send declared `explicit` and the refusal is a 403. Shared by
/// [`refused_error`] and [`refused_project_only_error`].
fn with_force_clause(base: String, kind: &ClientErrorKind, force: AttributionForce) -> String {
    if force.mode() == crate::api_client::AttributionMode::Explicit
        && matches!(kind, ClientErrorKind::Forbidden)
    {
        return format!(
            "{base} This send declared `explicit` attribution, so the refusal may be of the \
             FORCE itself: forcing needs `Operator` on that project AND a Control Plane \
             identity (a `tvk_` API key can never force). If membership attribution is what \
             you want, {}",
            force_remediation(force)
        );
    }
    base
}

/// How to STOP forcing, given which source(s) are doing it.
///
/// A sentence fragment completing "If membership attribution is what you
/// want, ...", so the caller keeps the framing and this keeps the facts.
///
/// Only ever reached with at least one source set (see [`refused_error`]'s
/// guard, which is `force.mode() == Explicit` — i.e. `env || binding`), so
/// the all-false arm is unreachable in practice. It still has to say
/// something rather than panic: this runs while printing an error on the
/// capture path, and a hook that panics mid-diagnostic is strictly worse
/// than one that prints a slightly vague line. The fallback names both ways,
/// which is wrong about emphasis but never wrong about the fix.
///
/// When BOTH are set the message says so explicitly: removing one alone
/// leaves the other still forcing, which would look exactly like the fix not
/// working.
fn force_remediation(force: AttributionForce) -> String {
    let env_fix = crate::program::say(
        "unset `TRACEVAULT_PROJECT_ATTRIBUTION` in this environment (it is \
                   process-wide and never expires, so no switch clears it)",
    );
    let binding_fix = crate::program::say(
        "run `tracevault project switch <name>` WITHOUT \
                       `--project-attribution explicit` (add `--user` if the forced binding \
                       is the machine-wide default in `user_project.toml`)",
    );
    match (force.env, force.binding) {
        (true, false) => format!("{env_fix}."),
        (false, true) => format!("{binding_fix}."),
        // Both: neither fix is sufficient alone.
        (true, true) => {
            format!("BOTH forces are in effect and both must go — {env_fix}, and {binding_fix}.")
        }
        (false, false) => format!("{env_fix}, or {binding_fix}."),
    }
}

pub(crate) fn deterministic_client_error_kind(
    e: &dyn std::error::Error,
) -> Option<ClientErrorKind> {
    let s = e.to_string();
    // 401 is deliberately excluded: it's an authentication failure (bad/expired
    // token), not a project-scoping problem, and the buffer/retry path already
    // handles it correctly without a misleading project-scoping message. 403
    // stays in: it can mean the token is valid but lacks `Operator` on the bound
    // project (or the account has no `tracevault` grant at all), and the refusal
    // line can name both possible causes.
    if s.contains("(403 ") {
        return Some(ClientErrorKind::Forbidden);
    }
    if ["(400 ", "(404 ", "(409 "]
        .iter()
        .any(|marker| s.contains(marker))
    {
        return Some(ClientErrorKind::Scoping);
    }
    None
}

/// Send a single stream event, routing to the project-scoped endpoint when a
/// local project binding resolved (`capture_pid = Some(_)`), else the
/// repo-scoped endpoint (server-side deduction/refusal). Factored out so both
/// the pending-flush loop and the live send share one branch.
///
/// Routing is decided by the [`Attribution`] resolved before the send:
/// `Repo` with no project goes to the repo-scoped endpoint (the server
/// deduces the project); `Repo` with a project goes to the project-scoped
/// endpoint carrying `repo_id`; `ProjectOnly` goes to the project-scoped
/// endpoint with no `repo_id` at all. A deterministic refusal there (VIS-1255,
/// per VIS-316) prints [`refused_project_only_error`] once and propagates as
/// `Err`, exactly like the repo+project refusal below: the caller buffers it
/// in `pending-project-<pid>.jsonl`. It used to be dropped as "undeliverable",
/// which advanced `.stream_offset` and so lost the session's transcript on a
/// refusal that a later `project switch`/`repo switch` or role grant could
/// have fixed.
///
/// When the attribution carries BOTH a repo and a project, the project was
/// explicitly declared (by binding or by `project switch`), so the server's
/// refusal of it is an error, never re-derived elsewhere: a deterministic
/// client error (the bound project doesn't apply to this repo: not a member,
/// or the caller lacks `Operator` on it) prints the refusal line to stderr
/// and returns `Err(e)` with the original error, unchanged, so the caller's
/// existing buffer/retry logic queues it in the REPO's pending file
/// (`pending-<repo_id>.jsonl`, see [`Attribution::pending_file_name`]); the
/// next drain (the hook's or `tracevault flush`'s) re-applies whatever capture
/// project is in force at that time (mirrors the server-side rule from VIS-305: a declared project the server
/// refuses is not silently re-attributed). A transient error (5xx,
/// network/transport, timeout) also propagates as `Err`, and is handled
/// identically by that same buffer/retry path.
///
/// `warned` is shared across every call made for a single hook
/// invocation (both the pending-flush loop and the live send). The
/// pending-flush loop only `break`s on `Err`, so without this flag a stale,
/// refused binding would print the refusal line once per buffered event
/// before the loop breaks. Gating on `*warned` caps stderr at one line per
/// invocation. The repo-less refusal shares the flag for the same reason.
///
/// `force` is the invocation's attribution force — [`attribution_force`]
/// applied to the capture binding. Its [`AttributionForce::mode`] goes on
/// every project-scoped send as the `x-tracevault-project-attribution`
/// header, and the same value is handed to [`refused_error`], which needs
/// the SOURCES and not only the verdict to tell the operator how to stop
/// forcing. Taken as a parameter rather than derived here because the
/// binding is invariant across a whole hook invocation while this function
/// runs once per buffered event, and the evaluation costs an env read plus
/// an RFC3339 parse. `commands::flush` resolves it once per queue for the
/// same reason.
async fn send_stream_event(
    client: &crate::api_client::ApiClient,
    attribution: &Attribution,
    force: AttributionForce,
    req: &StreamEventRequest,
    warned: &mut bool,
) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn std::error::Error>> {
    let (repo_id, capture_pid) = match attribution {
        // Repo-less: there is no repo-scoped endpoint to fall back TO. A
        // deterministic refusal is an error (VIS-316) that goes through the
        // normal buffer path like any other — printed once, then `Err` so the
        // caller queues it in `pending-project-<pid>.jsonl` and leaves
        // `.stream_offset` where it is. Nothing is ever dropped here: a
        // refused project can be fixed by `project switch`, by `repo switch`
        // (whose repo-scoped send adopts this queue when the project is the
        // same, see `adopted_project_queue`), or by a role grant.
        Attribution::ProjectOnly { project_id } => {
            let attempt = client
                .stream_event_for_project(*project_id, None, force.mode(), req)
                .await;
            if let Err(e) = &attempt {
                if let Some(kind) = deterministic_client_error_kind(e.as_ref()) {
                    if !*warned {
                        eprintln!("{}", refused_project_only_error(*project_id, &kind, force));
                        *warned = true;
                    }
                }
            }
            return attempt;
        }
        Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
    };
    match capture_pid {
        None => client.stream_event(repo_id, req).await,
        Some(pid) => {
            let attempt = client
                .stream_event_for_project(pid, Some(repo_id), force.mode(), req)
                .await;
            let kind = match &attempt {
                Ok(_) => None,
                Err(e) => deterministic_client_error_kind(e.as_ref()),
            };
            match (attempt, kind) {
                (Ok(r), _) => Ok(r),
                (Err(e), Some(kind)) => {
                    if !*warned {
                        // Since Keycloak, a 403 has a SECOND and now more common
                        // cause: the account has no `tracevault` grant at all,
                        // in which case nothing this hook does will work and
                        // `project switch` is confidently wrong advice — on the
                        // code path users hit most. The server's 403 envelope
                        // isn't distinguishable from here (see
                        // `ClientErrorKind`), so the wording names both.
                        eprintln!("{}", refused_error(pid, &kind, force));
                        *warned = true;
                    }
                    // The caller declared this project; the server refused it.
                    // Do NOT re-attribute to another project by falling back to
                    // the repo-scoped endpoint — propagate so the caller queues
                    // this event for retry under the same (or a corrected)
                    // binding.
                    Err(e)
                }
                // transient — propagate for buffer/retry
                (Err(e), None) => Err(e),
            }
        }
    }
}

/// Record-count offset arithmetic for the inline (fileless) path, mirroring the
/// byte-offset semantics of `read_new_transcript_lines`: returns
/// `(send_offset, next_offset)` where `send_offset` is stamped on the request as
/// `transcript_offset` (base for the server's per-line `chunk_index`) and
/// `next_offset` is persisted to `.stream_offset`.
pub fn inline_offset_bump(start_offset: i64, records_len: i64) -> (i64, i64) {
    (start_offset, start_offset + records_len)
}

/// Split a hook event whose transcript batch does not fit in one request
/// ([`MAX_REQUEST_BYTES`]) into several requests, so no line is dropped. A
/// request that fits is returned unchanged as the only part.
///
/// Otherwise the event itself (its type, tool payload and `event_uuid`) goes
/// in the LAST part, with as many trailing lines as fit beside it; the lines
/// before those go, in order, in `Transcript` parts, which the server handles
/// as lines only. A single line larger than the cap is sent alone; it cannot
/// be split.
///
/// Every line keeps the chunk_index it would have had unsplit: a part's
/// `transcript_offset` is the batch's plus the index of the part's first line
/// in the batch. Where the batch is cut therefore never matters — not between
/// two hooks of one session that read from the same offset concurrently and
/// split different lengths, and not between a delivery and its retry.
pub fn split_into_parts(mut req: StreamEventRequest) -> Vec<StreamEventRequest> {
    if req.serialized_len() <= MAX_REQUEST_BYTES {
        return vec![req];
    }
    let lines = req.transcript_lines.take().unwrap_or_default();
    let batch_offset = req.transcript_offset.unwrap_or(0);
    // The event part without lines: shed its tool payload if even that does
    // not fit, as before.
    req.truncate_large_fields();

    // Each line costs its JSON plus a separating comma in the array.
    let sizes: Vec<usize> = lines
        .iter()
        .map(|l| serde_json::to_string(l).map(|s| s.len()).unwrap_or(0) + 1)
        .collect();
    let envelope = |r: &StreamEventRequest| {
        let mut r = r.clone();
        r.transcript_lines = Some(vec![]);
        r.serialized_len()
    };

    // Trailing lines that fit beside the event.
    let mut tail_start = lines.len();
    let mut used = envelope(&req);
    while tail_start > 0 && used + sizes[tail_start - 1] <= MAX_REQUEST_BYTES {
        tail_start -= 1;
        used += sizes[tail_start];
    }

    let transcript_template = transcript_template(&req);
    let transcript_envelope = envelope(&transcript_template);

    // Group the leading lines into `Transcript` parts, then the tail.
    let mut groups: Vec<std::ops::Range<usize>> = Vec::new();
    let mut start = 0;
    while start < tail_start {
        let mut end = start + 1;
        let mut used = transcript_envelope + sizes[start];
        while end < tail_start && used + sizes[end] <= MAX_REQUEST_BYTES {
            used += sizes[end];
            end += 1;
        }
        groups.push(start..end);
        start = end;
    }
    groups.push(tail_start..lines.len());

    let last = groups.len() - 1;
    let mut lines = lines.into_iter();
    groups
        .into_iter()
        .enumerate()
        .map(|(n, range)| {
            let mut part = if n == last {
                req.clone()
            } else {
                transcript_template.clone()
            };
            let part_lines: Vec<_> = lines.by_ref().take(range.len()).collect();
            part.transcript_lines = (!part_lines.is_empty()).then_some(part_lines);
            part.transcript_offset = Some(batch_offset + range.start as i64);
            part
        })
        .collect()
}

/// A lines-only `Transcript` request with `req`'s session, agent and context
/// fields but none of its event (type, tool payload, `event_uuid`), which the
/// server handles as transcript lines only. `req`'s lines are not copied.
/// Every field is listed, so a new one has to be decided on here.
pub fn transcript_template(req: &StreamEventRequest) -> StreamEventRequest {
    StreamEventRequest {
        protocol_version: req.protocol_version,
        tool: req.tool.clone(),
        event_type: StreamEventType::Transcript,
        session_id: req.session_id.clone(),
        timestamp: req.timestamp,
        hook_event_name: req.hook_event_name.clone(),
        tool_name: None,
        tool_use_id: None,
        tool_input: None,
        tool_response: None,
        tool_is_error: None,
        event_index: None,
        event_uuid: None,
        transcript_lines: None,
        transcript_offset: req.transcript_offset,
        model: req.model.clone(),
        cwd: req.cwd.clone(),
        final_stats: None,
        flow_id: req.flow_id.clone(),
        labels: req.labels.clone(),
        params: req.params.clone(),
        billing_mode: req.billing_mode,
    }
}

/// Send what the session's subagents (Claude Code: see [`crate::subagents`])
/// appended to their transcripts since the last hook. Each file goes in its
/// own `Transcript` request(s) under the parent session, never mixed with
/// another file's lines or the main transcript's, with `transcript_offset`
/// counted within that file and split like any batch, so every line keeps one
/// chunk_index per file.
///
/// Delivery is the event's: same budget, same queue, and once a send fails
/// the remaining files are queued behind it. A file's offset advances only
/// when all its parts were accepted, as with the main transcript, so a queued
/// or failed batch is read again (same offsets, same chunk_indexes) next time.
/// A file whose offset cannot be read is skipped with a warning; it must not
/// cost the other files their delivery.
///
/// A file another hook of the session is sending right now (it holds the
/// file's lock) is skipped, unless `wait_for_lock` is set: then the lock is
/// awaited until that instant, and only a holder still busy by then makes the
/// file skipped, with a warning. Final hooks wait: the holder may have read
/// before the subagent wrote its last lines, and no hook may come after a
/// final one to send them.
#[allow(clippy::too_many_arguments)]
async fn deliver_subagent_transcripts(
    client: &crate::api_client::ApiClient,
    attribution: &Attribution,
    force: AttributionForce,
    template: &StreamEventRequest,
    transcript_path: &Path,
    session_dir: &Path,
    pending_path: &Path,
    mut send_failed: bool,
    deadline: std::time::Instant,
    wait_for_lock: Option<std::time::Instant>,
    warned: &mut bool,
) -> Result<bool, Box<dyn std::error::Error>> {
    // Whether every file was read to its end and all of it accepted.
    let mut complete = true;
    for file in crate::subagents::transcripts(transcript_path) {
        let offset_path = crate::subagents::offset_path(session_dir, &file);
        // Held until the offset is written (see `subagents::try_lock`).
        let lock = loop {
            match crate::subagents::try_lock(&offset_path) {
                Ok(None) if wait_for_lock.is_some_and(|t| std::time::Instant::now() < t) => {
                    tokio::time::sleep(std::time::Duration::from_millis(25)).await;
                }
                other => break other,
            }
        };
        let _lock = match lock {
            Ok(Some(lock)) => lock,
            Ok(None) => {
                complete = false;
                if wait_for_lock.is_some() {
                    eprintln!(
                        "{TOP}: warning: skipping subagent transcript {}: \
                         another hook is still sending it",
                        file.display()
                    );
                }
                continue;
            }
            Err(e) => {
                eprintln!(
                    "{TOP}: warning: skipping subagent transcript {}: cannot lock: {e}",
                    file.display()
                );
                complete = false;
                continue;
            }
        };
        // One batch per hook; a final hook reads on to the file's end, batch
        // by batch, since no hook may come after it. Past the deadline the
        // batches are queued, not sent, and once the queue is full the rest
        // stays in the file (the offset stops there).
        loop {
            let mut batch = match crate::subagents::read_batch(&file, &offset_path, MAX_BATCH_BYTES)
            {
                Ok(read) => read,
                Err(e) => {
                    eprintln!(
                        "{TOP}: warning: skipping subagent transcript {}: {e}",
                        file.display()
                    );
                    complete = false;
                    break;
                }
            };
            if batch.end == batch.start {
                break;
            }
            // Only blank or malformed lines: nothing to send, but move past them.
            let mut delivered = Delivered {
                all: true,
                lines: 0,
            };
            if !batch.lines.is_empty() {
                let mut req = template.clone();
                req.transcript_lines = Some(std::mem::take(&mut batch.lines));
                req.transcript_offset = Some(batch.start);
                delivered = deliver_parts(
                    client,
                    attribution,
                    force,
                    split_into_parts(req),
                    pending_path,
                    send_failed,
                    deadline,
                    Unsent::Queued,
                    warned,
                )
                .await?;
                send_failed |= !delivered.all;
            }
            // Past what was accepted or queued. Under the file's lock, so the
            // offset only ever moves forward here.
            let next = batch.next_offset(&delivered);
            if let Some(next) = next {
                crate::subagents::write_offset(&offset_path, next)?;
            }
            let stopped_short = next != Some(batch.end);
            if wait_for_lock.is_none() || stopped_short {
                let unread = fs::metadata(&file).is_ok_and(|m| m.len() as i64 > batch.end);
                complete &= delivered.all && !stopped_short && !unread;
                break;
            }
            complete &= delivered.all;
        }
    }
    Ok(complete)
}

/// Choose the transcript source for a stream event. Inline records (from a
/// plugin-based agent like OpenCode) win over the file-read result whenever the
/// hook event carries them — INCLUDING an empty vec, so an event with no new
/// records (e.g. OpenCode `stop`) preserves the prior record-count offset
/// instead of resetting it to the file-path's 0.
pub fn resolve_transcript_source(
    inline_records: Option<Vec<serde_json::Value>>,
    prior_offset: i64,
    file_result: (Vec<serde_json::Value>, i64, i64),
) -> (Vec<serde_json::Value>, i64, i64) {
    match inline_records {
        Some(records) => {
            let (send, next) = inline_offset_bump(prior_offset, records.len() as i64);
            (records, send, next)
        }
        None => file_result,
    }
}

/// Derive the event-level tool-error flag from inline transcript records.
/// OpenCode tool events carry no `tool_use_id`, so `extract_is_error_from_transcript`
/// can't run; instead the plugin forwards a `toolResult` record whose `isError`
/// signals the outcome. Amp's records (`type: "amp_message"`) carry Amp's own
/// `tool_result` block instead, whose `status` is `"error"` only for a tool
/// that failed: a permission rejection and a non-zero `exitCode` are both
/// `"done"`, as Amp reports them. Returns `Some(true|false)` for the first
/// tool result found, or `None` when there is none (non-tool events).
pub fn inline_tool_is_error(lines: &[serde_json::Value]) -> Option<bool> {
    lines.iter().find_map(|line| {
        let msg = line.get("message")?;
        if line.get("type").and_then(|v| v.as_str()) == Some("amp_message") {
            return msg
                .get("content")?
                .as_array()?
                .iter()
                .find(|b| b.get("type").and_then(|v| v.as_str()) == Some("tool_result"))
                .map(|b| b.get("status").and_then(|v| v.as_str()) == Some("error"));
        }
        if msg.get("role").and_then(|v| v.as_str()) == Some("toolResult") {
            Some(
                msg.get("isError")
                    .and_then(|v| v.as_bool())
                    .unwrap_or(false),
            )
        } else {
            None
        }
    })
}

/// Stamp the agent identity onto a request's `tool` + `protocol_version`.
/// Factored out so the mapping is testable without the network/FS-bound
/// `run_stream`.
pub fn stamp_agent(req: &mut StreamEventRequest, agent: crate::agent::Agent) {
    req.tool = Some(agent.tool_name().to_string());
    req.protocol_version = agent.protocol_version() as u32;
}

/// How long a hook may keep starting requests. `init` installs the hooks
/// with a 10 s timeout and the agent kills a hook that overruns it, so a
/// split batch (or a long pending queue) still unsent after this is queued
/// instead: a killed hook would lose whatever it held only in memory. Half
/// the timeout leaves room for the request already in flight.
const DELIVERY_BUDGET: std::time::Duration = std::time::Duration::from_secs(5);

/// How long past the delivery budget a request already in flight may run
/// before it is given up and its part queued (the client's own timeout is
/// 60 s, past the hook's). This bounds how long a hook holds a subagent
/// file's lock: at most its budget plus this.
pub(crate) const IN_FLIGHT_GRACE: std::time::Duration = std::time::Duration::from_secs(2);

/// How long past its own delivery budget a final hook (`Stop`,
/// `SubagentStop`) waits for a subagent file another hook is sending. A
/// holder started no later than the final hook and releases the lock by its
/// budget plus [`IN_FLIGHT_GRACE`], so this outlasts every holder; what is
/// read after the budget is queued, not sent, which takes well under the two
/// seconds left before the 10 s hook timeout.
const FINAL_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(3);

/// Where the transcript lines of a part go when the part cannot be sent.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Unsent {
    /// Lines read from a transcript file: queued with their part while the
    /// queue has room, and then counted in [`Delivered::lines`], so the read
    /// offset moves past them and each is in one place only. Once the queue
    /// is full the lines stay in the file for a later hook (the offset stops
    /// before the first of them) and only the event itself is queued.
    Queued,
    /// Lines read from a transcript file that are left there: nothing of
    /// them is queued and the offset does not move past them. For the
    /// `SessionEnd` lines, which the catch-up sweep of a later session start
    /// finds by that offset (`commands::catch_up`) and sends again.
    StayInFile,
    /// Records an agent handed over inline. They exist nowhere else: a part
    /// is queued whole or, the queue being full, dropped.
    Inline,
}

/// What [`deliver_parts`] did with a batch: whether the server accepted
/// every part, and how many of the batch's transcript lines, from its start,
/// are now accepted or in the queue. Those need not be read again; the read
/// offset moves past them.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Delivered {
    pub all: bool,
    pub lines: usize,
}

/// Send a hook event's parts in order. From the first failure on (or from the
/// start when `send_failed`, i.e. older queued events are still waiting), or
/// once `deadline` has passed, a part goes to the pending queue instead,
/// behind whatever is already there. A request still in flight
/// [`IN_FLIGHT_GRACE`] past `deadline` counts as failed: the server may have
/// stored it, and the queued copy then dedupes on its chunk_indexes and
/// `event_uuid`.
///
/// What happens to the transcript lines of a part that is not sent is
/// `unsent`'s to say (see [`Unsent`]); the caller moves a file's read offset
/// past [`Delivered::lines`].
#[allow(clippy::too_many_arguments)]
async fn deliver_parts(
    client: &crate::api_client::ApiClient,
    attribution: &Attribution,
    force: AttributionForce,
    parts: Vec<StreamEventRequest>,
    pending_path: &Path,
    mut send_failed: bool,
    deadline: std::time::Instant,
    unsent: Unsent,
    warned: &mut bool,
) -> Result<Delivered, Box<dyn std::error::Error>> {
    let mut delivered = Delivered {
        all: true,
        lines: 0,
    };
    let mut queue_full = unsent == Unsent::StayInFile;
    for part in parts {
        send_failed = send_failed || std::time::Instant::now() >= deadline;
        if !send_failed {
            let send = send_stream_event(client, attribution, force, &part, warned);
            let failure =
                match tokio::time::timeout_at((deadline + IN_FLIGHT_GRACE).into(), send).await {
                    Ok(Ok(_)) => {
                        delivered.lines += lines_of(&part);
                        continue;
                    }
                    Ok(Err(e)) => e.to_string(),
                    Err(_) => "no answer in time".to_string(),
                };
            warn_unsent(warned, &failure);
            send_failed = true;
        }
        delivered.all = false;
        let json = serde_json::to_string(&part)?;
        if unsent == Unsent::Inline {
            crate::pending_queue::append(pending_path, &json)?;
            continue;
        }
        if !queue_full && crate::pending_queue::try_append(pending_path, &json)? {
            delivered.lines += lines_of(&part);
            continue;
        }
        // From here on the lines stay in the file: the offset stops before
        // the first one left there, whatever a later, smaller part would fit.
        queue_full = true;
        if let Some(event) = crate::pending_queue::without_lines(part) {
            crate::pending_queue::append(pending_path, &serde_json::to_string(&event)?)?;
        }
    }
    Ok(delivered)
}

fn lines_of(part: &StreamEventRequest) -> usize {
    part.transcript_lines.as_ref().map_or(0, Vec::len)
}

/// Whether `failure` (an error of `ApiClient::stream_event*`, as text) is the
/// server's HTTP 413.
fn too_large(failure: &str) -> bool {
    failure.contains("(413 ")
}

/// Whether the transcript past `from` tells that the tool call `tool_use_id`
/// failed, for a hook whose batch stopped short of the transcript's end: the
/// call's result is among the last lines written, wherever the backlog
/// starts. Reads at most the last [`MAX_BATCH_BYTES`] and parses only the
/// lines that name the call.
fn tool_is_error_past(transcript: &Path, from: i64, tool_use_id: &str) -> Option<bool> {
    let mut file = fs::File::open(transcript).ok()?;
    let len = file.metadata().ok()?.len() as i64;
    if len <= from || tool_use_id.is_empty() {
        return None;
    }
    file.seek(SeekFrom::Start(from.max(len - MAX_BATCH_BYTES) as u64))
        .ok()?;
    let mut tail = Vec::new();
    file.take(MAX_BATCH_BYTES as u64)
        .read_to_end(&mut tail)
        .ok()?;
    let needle = tool_use_id.as_bytes();
    let lines: Vec<serde_json::Value> = tail
        .split(|b| *b == b'\n')
        .filter(|line| line.windows(needle.len()).any(|w| w == needle))
        .filter_map(|line| serde_json::from_slice(line).ok())
        .collect();
    extract_is_error_from_transcript(tool_use_id, &lines)
}

/// Say once per hook why a send failed. A refusal the server explained has
/// been printed already (it sets `warned`); anything else used to fail
/// without a word, hook after hook.
fn warn_unsent(warned: &mut bool, failure: &str) {
    if !*warned {
        eprintln!("{TOP}: warning: could not send to the server ({failure}); it will be retried");
        *warned = true;
    }
}

/// The developer's choice of tracing mode for `visdom` (`hooks` or
/// `gateway`). A preference, not a fact about a running agent: an agent
/// started without `visdom` may well carry `gateway` here and still talk to
/// its provider directly.
pub const TRACING_MODE_ENV: &str = "VISDOM_TRACING_MODE";

/// The variable `visdom` sets on an agent it has routed through the AI
/// Gateway, which then records the session itself: the agent's name
/// (`claude-code`, `codex`). Nobody else sets it.
pub const GATEWAY_SESSION_ENV: &str = "VISDOM_GATEWAY_SESSION";

/// Whether the session this hook of `agent` runs in is recorded by the AI
/// Gateway, given the value of [`GATEWAY_SESSION_ENV`]. Hooks inherit the
/// agent's environment, so this is true for the events of an agent `visdom`
/// routed through the gateway. The capture hook then records nothing: the
/// same session captured twice would be a second, conflicting source.
///
/// The variable names the agent that was routed, and only that agent's hooks
/// go quiet: whatever else is started from its shell — another agent, by
/// hand or by the first one — inherits the variable without being routed
/// anywhere, and is captured.
///
/// `1` is what `visdom` 1.0.0 sets, for whichever agent it started: still
/// taken, for every agent, so that its gateway sessions are not captured a
/// second time by a newer `tracevault`.
pub fn captured_by_gateway(marker: Option<&str>, agent: crate::agent::Agent) -> bool {
    marker
        .map(str::trim)
        .is_some_and(|m| m == "1" || m.eq_ignore_ascii_case(agent.tool_name()))
}

pub async fn run_stream(
    event_type: &str,
    agent: crate::agent::Agent,
) -> Result<(), Box<dyn std::error::Error>> {
    // 1. Read HookEvent from stdin
    let deadline = std::time::Instant::now() + DELIVERY_BUDGET;
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;
    // The event is read (the agent is writing it) and then left alone.
    if captured_by_gateway(std::env::var(GATEWAY_SESSION_ENV).ok().as_deref(), agent) {
        println!("{}", serde_json::to_string(&HookResponse::allow())?);
        return Ok(());
    }
    let hook_event = parse_hook_event(&input)?;

    // Resolve project_root and session_dir via the shared git-aware resolver.
    //
    // `resolve_session_paths` uses `git rev-parse --git-common-dir` to locate
    // the primary worktree root, so it works correctly from a primary checkout,
    // a nested worktree, AND a sibling linked worktree (where the primary
    // `.visdom/` is NOT an ancestor of hook_cwd — the old ancestor-walk
    // would fall back to hook_cwd itself, fail to load config, and silently
    // drop the event).
    //
    // The hook must never hard-fail (a failing hook blocks the Claude Code tool
    // call).  Genuine resolution failure (no git, no `.visdom/`) results in
    // a Fallback root (start dir).  Note: `fs::create_dir_all(&session_dir)?`
    // just below runs BEFORE the config/credentials check and can itself
    // `?`-exit early — that remains graceful because `main.rs` catches all
    // `Err` from `run_stream` and exits 0 without blocking the tool.
    //
    // The session DIR is anchored to where the session started when
    // `session-start` recorded that (VIS-1257): the hook's `cwd` follows the
    // shell's `cd`, and a dir resolved per event would split the session's
    // `.stream_offset` and queues across two `.visdom/`s. Config and
    // credentials still come from the event's `cwd` (`project_root`).
    let hook_cwd = Path::new(&hook_event.cwd);
    let (resolved, cwd_session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
    let storage_root =
        crate::session_state::storage_root(&crate::session_state::load(&hook_event.session_id));
    let session_dir = match &storage_root {
        Some(root) => crate::layout::session_dir(root, &hook_event.session_id),
        None => cwd_session_dir,
    };
    if storage_root.is_none() && resolved.source == crate::paths::ProjectRootSource::Fallback {
        // Neither git nor an ancestor `.visdom/` resolved a project root, so
        // we are about to create a fresh `.visdom/` at the hook's working
        // directory — which is how stray per-subdirectory `.visdom/` dirs
        // appear. Surface it (best-effort; stderr never blocks the hook).
        eprintln!(
            "{TOP}: warning: could not resolve a git project root from {}; \
             creating .visdom/ there. Ensure `git` is on PATH for the hook and \
             that it runs inside the repository to keep sessions under the repo root.",
            hook_cwd.display()
        );
    }
    let project_root = resolved.root;

    // 2. Create session dir
    fs::create_dir_all(&session_dir)?;

    // Ensure runtime artifacts (sessions/, cache/, *.local.toml) are git-ignored
    // inside whatever `.visdom/` we just created — including a per-subproject
    // one. `tracevault init` writes this for the root dir, but runtime-created
    // dirs would otherwise have no .gitignore and leak sessions into commits.
    // Best-effort: never fail the hook on this.
    // (The directory is the session dir's own grandparent: a session an
    // earlier release started keeps its `.tracevault/`.)
    if let Some(dir) = session_dir.parent().and_then(Path::parent) {
        let _ = crate::config::TracevaultConfig::ensure_gitignore(dir);
    }

    // Write origin marker so verify-start can disambiguate sessions by worktree.
    // Best-effort: never fail the hook on marker errors. Uses the shared
    // canonicalizing helper so the value matches what verify-start compares
    // against on the read side.
    let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
    let _ = fs::write(session_dir.join("origin"), &worktree_top);
    // An anchored session also lists every worktree it ran in, so `check` and
    // `verify-start` there find it after it moved on (VIS-1257).
    if storage_root.is_some() {
        let _ = crate::session_state::record_worktree(&session_dir, &worktree_top);
    }

    // Record where the transcript lives: `tracevault check` counts the
    // session's tool calls from it, and finds it only through metadata.json.
    // Best-effort, like the origin marker.
    let _ = record_transcript_path(&session_dir, &hook_event.transcript_path);
    // Inline records (OpenCode) reach no transcript file `check` could read,
    // so keep their tool calls locally for it. Done here, before the
    // `.stream_offset` read below can fail the hook, so a corrupt offset file
    // never costs `check` a tool call.
    if let Some(records) = &hook_event.transcript_records {
        let _ = record_inline_tool_calls(&session_dir, records);
    }

    let target = SessionTarget {
        project_root,
        session_dir,
        worktree_top,
    };
    stream_event(
        hook_event,
        event_type,
        agent,
        &target,
        deadline,
        Sender::Hook,
    )
    .await?;

    // 12. Always print HookResponse::allow() to stdout
    let response = HookResponse::allow();
    println!("{}", serde_json::to_string(&response)?);

    Ok(())
}

/// The server event a hook's `--event` is sent as.
pub fn stream_event_type(event_type: &str) -> StreamEventType {
    match event_type {
        "notification" => StreamEventType::SessionStart,
        // Codex, OpenCode and GSD/pi end their sessions with it.
        "stop" => StreamEventType::SessionEnd,
        // Claude Code's `SessionEnd` comes after `Stop`, which already ended
        // the session on the server: it only carries the last transcript
        // lines, among them the `cost-state` report (VIS-1108).
        "session-end" => StreamEventType::Transcript,
        _ => StreamEventType::ToolUse,
    }
}

/// Where a stream event's session lives, resolved by the caller: the hook
/// from its working directory, the catch-up sweep from the session's
/// directory.
pub(crate) struct SessionTarget {
    pub project_root: std::path::PathBuf,
    /// `<project_root>/.visdom/sessions/<session_id>`; must exist.
    pub session_dir: std::path::PathBuf,
    /// The checkout the session runs in (see [`crate::paths::worktree_toplevel`]).
    pub worktree_top: String,
}

/// Who sends a [`stream_event`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sender {
    /// The session's own hook: it also sends the subagent transcripts, and
    /// stamps the billing mode it detects.
    Hook,
    /// The catch-up sweep (`commands::catch_up`), on behalf of an earlier
    /// session: main transcript only, and no billing mode, since this
    /// process's credentials say nothing about that session's (the server
    /// keeps the one it has).
    CatchUp,
    /// `flush`, on behalf of a session that may have ended: like the
    /// catch-up, but everything the session's transcripts still hold unread
    /// (to their ends, subagent files included), since no hook may come to
    /// send it.
    Flush,
}

/// What a [`stream_event`] did.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Sent {
    /// Every request was accepted, and nothing this event was to send is
    /// left in the queue or unread.
    Accepted,
    /// Something was not sent: a send failed, the deadline came first, or
    /// another hook held a transcript this one was to read.
    Queued,
    /// Nothing was sent: no attribution resolved, or (catch-up) not the one
    /// the session recorded.
    Skipped,
}

/// Send `hook_event` (and, from a hook, what the session's subagents wrote
/// since the last hook) as `event_type`, queueing what is not accepted by
/// `deadline`. Prints nothing: the hook's response is the caller's.
pub(crate) async fn stream_event(
    mut hook_event: tracevault_protocol::hooks::HookEvent,
    event_type: &str,
    agent: crate::agent::Agent,
    target: &SessionTarget,
    deadline: std::time::Instant,
    sender: Sender,
) -> Result<Sent, Box<dyn std::error::Error>> {
    let SessionTarget {
        project_root,
        session_dir,
        worktree_top,
    } = target;
    let hook_cwd = Path::new(&hook_event.cwd);

    // 3. Mint a time-ordered event id. UUIDv7 is stamped at hook-fire time, so
    //    it both orders events and is a stable idempotency key — no shared
    //    `.event_counter` file (which raced between concurrent parallel-tool
    //    hooks and could collide/drop events).
    let event_uuid = uuid::Uuid::now_v7();

    // 4. Read new transcript lines
    let transcript_path = Path::new(&hook_event.transcript_path);
    let offset_path = session_dir.join(".stream_offset");
    // transcript_offset carries the batch START byte offset so the server
    // derives a stable per-line chunk_index across overlapping/retried reads;
    // .stream_offset persists the END (next read position).
    // Claude Code's `SubagentStop` hook only sweeps the subagent transcripts
    // (see `deliver_subagent_transcripts` below): it is not an event of the
    // main conversation, so it neither reads nor advances `.stream_offset`.
    let sends_main = event_type != "subagent-stop";
    // One hook of a session at a time reads the transcript file, sends or
    // queues what it read and moves the offset: two that read the same lines
    // and advance by different amounts leave the later lines to be sent under
    // two chunk_indexes, and stored twice. A hook that finds another at it
    // sends its event without lines, which the other, or a later hook, sends.
    // A final hook waits instead, as for a subagent's file (see
    // `deliver_subagent_transcripts`): no hook may come after it.
    let reads_file = sends_main && hook_event.transcript_records.is_none();
    let main_lock = if reads_file {
        let wait_until =
            matches!(event_type, "stop" | "session-end").then(|| deadline + FINAL_LOCK_WAIT);
        loop {
            match crate::subagents::try_lock(&offset_path) {
                Ok(None) if wait_until.is_some_and(|t| std::time::Instant::now() < t) => {
                    tokio::time::sleep(std::time::Duration::from_millis(25)).await;
                }
                Ok(lock) => break lock,
                Err(e) => {
                    eprintln!("{TOP}: warning: cannot lock the transcript offset: {e}");
                    break None;
                }
            }
        }
    } else {
        None
    };
    let sends_lines = !reads_file || main_lock.is_some();
    let mut batch = if sends_main {
        read_transcript_batch(transcript_path, &offset_path, MAX_BATCH_BYTES)?
    } else {
        TranscriptBatch::default()
    };
    let (transcript_lines, start_offset, new_offset) =
        (std::mem::take(&mut batch.lines), batch.start, batch.end);

    // Fileless inline path (OpenCode): a plugin-based agent with no single
    // tailable transcript supplies records directly on the hook event. When
    // present — INCLUDING an empty vec (OpenCode's `stop`/session.idle event
    // sends `transcript_records: []`) — they take priority over the file-read
    // result. `.stream_offset` is reused as a per-session RECORD counter so
    // the server's chunk_index stays stable/monotonic across retries, exactly
    // as with the byte-offset path. Treating an empty vec as "no new
    // records" rather than "fall back to the file" matters: OpenCode's
    // `transcript_path` is always "", so the file-read result is always
    // `(vec![], 0, 0)` — falling through to it would clobber the accumulated
    // offset back to 0 and collide with earlier turns' chunk_index on the
    // server.
    // Only inline (plugin-based) events override the file-read result, and only
    // they need `.stream_offset` re-read as a record counter. File-based agents
    // (claude/codex/gsd) skip this entirely — no extra hook-path I/O — and keep
    // the byte-offset values from `read_new_transcript_lines` above.
    let is_inline = hook_event.transcript_records.is_some();
    let (transcript_lines, start_offset, new_offset) = if is_inline {
        // Fail CLOSED, mirroring `read_new_transcript_lines`: a corrupt/unreadable
        // `.stream_offset` must NOT silently reset to 0 — that would restart the
        // record counter and collide with earlier turns' chunk_index on the
        // server (the offset-clobber failure mode). Propagate the error instead;
        // `main` treats a hook error as non-fatal (exits 0 without blocking the
        // tool call). Negatives are clamped to 0 defensively.
        let prior_offset: i64 = if offset_path.exists() {
            let content = fs::read_to_string(&offset_path)?;
            content
                .trim()
                .parse::<i64>()
                .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?
                .max(0)
        } else {
            0
        };
        // `take()` moves the records out (nothing below reads
        // `transcript_records` again) — avoids deep-cloning a potentially
        // large payload (full bash stdout / file contents) on the hook path.
        resolve_transcript_source(
            hook_event.transcript_records.take(),
            prior_offset,
            (transcript_lines, start_offset, new_offset),
        )
    } else {
        (transcript_lines, start_offset, new_offset)
    };
    // 5. Build StreamEventRequest
    let stream_event_type = stream_event_type(event_type);

    // Extract is_error from transcript for this tool_use_id. Inline (OpenCode)
    // events have no tool_use_id, so fall back to a forwarded `toolResult`
    // record's `isError` — otherwise a failed OpenCode tool would render as
    // successful (the event-level flag file-based agents populate would be None).
    let tool_is_error = hook_event
        .tool_use_id
        .as_deref()
        .and_then(|uid| {
            extract_is_error_from_transcript(uid, &transcript_lines)
                // The batch may have stopped short of the lines of this call.
                .or_else(|| {
                    reads_file
                        .then(|| tool_is_error_past(transcript_path, new_offset, uid))
                        .flatten()
                })
        })
        .or_else(|| inline_tool_is_error(&transcript_lines));

    // Load config once, up front, so it can back both the user-level context
    // layer resolution below and the repo_id lookup further down — avoids a
    // redundant second read of the same file. `try_load` keeps the
    // missing/malformed distinction so the required-config error further down
    // can report which one it is.
    // Best-effort here: a missing/unconfigured repo config does NOT mean "no
    // user context" — `resolve_user_context` below falls back to the user-level
    // config in that case. A malformed repo config is surfaced as an error
    // later (the required-config check), not silently dropped here.
    let config = crate::config::TracevaultConfig::try_load(project_root);
    // Repo config's user_context wins when the repo configured it; otherwise
    // fall back to the user-level ~/.config/tracevault/config.toml. This is
    // what lets a detached session (no checkout) still carry user context.
    let repo_uc = config
        .as_ref()
        .ok()
        .and_then(|opt| opt.as_ref())
        .and_then(|c| c.user_context.clone());
    let user_layer = crate::config::resolve_user_context(repo_uc).resolve();

    // Load the EFFECTIVE merged context (user layer, if enabled, merged with
    // global and per-worktree) and extract fields before building the
    // request.  Using `effective` means parallel sessions in different linked
    // worktrees each stamp their own per-worktree context without
    // interfering with each other.
    let ctx = crate::context::Context::effective(hook_cwd, user_layer.as_deref());
    let (ctx_flow_id, ctx_labels, ctx_params) = apply_context(ctx);

    let mut req = StreamEventRequest {
        protocol_version: 1,
        tool: Some("claude-code".to_string()),
        event_type: stream_event_type,
        session_id: hook_event.session_id.clone(),
        timestamp: chrono::Utc::now(),
        hook_event_name: Some(hook_event.hook_event_name.clone()),
        tool_name: hook_event.tool_name.clone(),
        tool_use_id: hook_event.tool_use_id.clone(),
        tool_input: hook_event.tool_input.clone(),
        tool_response: hook_event.tool_response.clone(),
        tool_is_error,
        event_index: None,
        event_uuid: Some(event_uuid),
        transcript_lines: None,
        transcript_offset: Some(start_offset),
        model: None,
        cwd: Some(hook_event.cwd.clone()),
        final_stats: None,
        flow_id: ctx_flow_id,
        labels: ctx_labels,
        params: ctx_params,
        billing_mode: (sender == Sender::Hook)
            .then(|| crate::billing::detect_current(agent, hook_cwd, &hook_event.transcript_path)),
    };

    stamp_agent(&mut req, agent);
    // Taken before the lines go in, so they are not copied.
    let subagent_template = transcript_template(&req);
    // Lines read while another hook holds the transcript only told this
    // event's `tool_is_error`.
    if sends_lines && !transcript_lines.is_empty() {
        req.transcript_lines = Some(transcript_lines);
    }

    // 6. Resolve credentials
    let (server_url, credential) = crate::credentials::resolve_credentials_quiet(project_root)?;

    // 7. Config (loaded above, alongside the user-level context layer
    // resolution) no longer directly gates repo_id — a missing config is not
    // fatal on its own, since the repo may instead resolve via the
    // workspace-mode precedence chain (session binding / subagent worktree
    // override) below. A malformed config is still surfaced here — that's
    // easy to miss in hook output otherwise. Only a bound `config.toml`'s
    // repo_id feeds the lowest-precedence tier (via `binding_from_config`
    // below).
    if let Err(e) = &config {
        return Err(format!("malformed .visdom/tracing.toml: {e}").into());
    }

    // Resolve the effective repo binding (workspace/detached mode). Bound
    // mode (a pinned config.toml) still works — it's the lowest-precedence
    // tier, wired below via `binding_from_config`, fed from the `config`
    // already loaded above (no second read of config.toml on this hot path).
    let session = crate::session_state::load(&hook_event.session_id);
    let bound = config
        .as_ref()
        .ok()
        .and_then(|opt| opt.as_ref())
        .and_then(crate::resolution::binding_from_config);
    let user_default = crate::user_default::load();
    let mut binding = resolve_stream_binding(&session, worktree_top, bound, user_default);
    // Explicit local project binding (if any) overrides server-side repo
    // deduction. Computed BEFORE the attribution gate below, reusing the
    // already-loaded session + worktree used just above for the repo-binding
    // resolution: a repo-less session is attributable by project alone, so the
    // project must be known before deciding whether this event can be sent —
    // and, when no repo binds, whether to infer a repo or to auto-bind one.
    // The full binding (not just its id) is resolved: `attribution_mode`
    // reads its `forced_until`, and this is the binding that actually decided
    // the target project, so it's the only one whose force is allowed to
    // apply (see `attribution_mode`'s doc comment).
    // The workspace tier comes from the config already loaded above: a
    // `project_id` (UUID) only, never the legacy `default_project` name, so
    // this costs no network call (VIS-1256).
    let config_project = config
        .as_ref()
        .ok()
        .and_then(|opt| opt.as_ref())
        .and_then(crate::resolution::project_from_config);
    let capture_binding = capture_binding(&session, Some(worktree_top.as_str()), config_project);
    let capture_pid = capture_binding
        .as_ref()
        .and_then(crate::resolution::capture_project_id);
    // The client is built here, not at step 8, because an unbound session may
    // need it first. A project-only session infers this event's repo from the
    // checkout it touches (VIS-1258): per event, within the project, never
    // stored as the session's binding — so a session working across several
    // child checkouts of an umbrella dir is attributed to each in turn. Any
    // other unbound session is bound from its checkout's remote, as the
    // SessionStart hook does — this covers agents without that hook and a
    // SessionStart whose lookup failed (VIS-1048). Either way one lookup per
    // checkout per session.
    let client = server_url
        .as_deref()
        .map(|url| crate::api_client::ApiClient::with_credential(url, credential));
    let mut inferred = None;
    if binding.is_none() {
        if let Some(client) = &client {
            match inference_project(None, capture_pid) {
                Some(pid) => {
                    if let Some(checkout) = crate::inferred_repo::event_checkout(
                        hook_cwd,
                        hook_event.tool_input.as_ref(),
                        worktree_top,
                    ) {
                        inferred = crate::inferred_repo::infer(
                            &hook_event.session_id,
                            &checkout,
                            pid,
                            client,
                            deadline,
                        )
                        .await;
                        // `check` and `verify-start` in a checkout find the
                        // session by the worktrees it ran in; a file tool's
                        // checkout is one even while the shell is elsewhere.
                        if inferred.is_some() && checkout != *worktree_top {
                            let _ = crate::session_state::record_worktree(session_dir, &checkout);
                        }
                    }
                }
                None => {
                    let auto = crate::auto_bind::bind_session(
                        &hook_event.session_id,
                        hook_cwd,
                        client,
                        deadline,
                    )
                    .await;
                    if let Some(notice) = auto.notice {
                        eprintln!("{notice}");
                    }
                    binding = auto.binding;
                }
            }
        }
    }
    // Resolved once per invocation, not per event — the binding is invariant
    // across the pending-flush loop and the live send below, while the
    // evaluation costs an env read and an RFC3339 parse. `commands::flush`
    // resolves it once per queue for the same reason. The whole
    // `AttributionForce` travels, not just its mode: a refusal has to name
    // the force source it is telling the operator to remove.
    let force = attribution_force(capture_binding.as_ref());

    // Ship if EITHER a repo or a project resolved; no-op only when neither
    // did. (`binding_repo_id_is_valid` guards a corrupted/hand-edited
    // session-state file whose repo_id could carry path separators into the
    // pending filename — such a binding degrades to project-only inside
    // `attribution_for` rather than dropping the event.)
    // Graceful no-op, exactly like the hook's normal success path. Do NOT
    // error: a failing hook would block the tool.
    let Some(attribution) =
        attribution_with_inference(binding.as_ref(), capture_pid, inferred.as_ref())
    else {
        return Ok(Sent::Skipped);
    };
    // A hook records what it sends under, for a later catch-up of this
    // session (best-effort, like the transcript path); the catch-up sends
    // only under that.
    match sender {
        Sender::Hook => {
            let _ = record_metadata(session_dir, "attribution", attribution_record(&attribution));
            // For `flush`, which sends what a session left unread and must
            // stamp it as this agent's.
            let _ = record_metadata(session_dir, "agent", agent.tool_name().into());
        }
        Sender::CatchUp | Sender::Flush => {
            let meta = session_metadata(session_dir);
            let recorded = meta.get("attribution");
            // `flush` reads whole transcripts, so it wants more than the
            // catch-up's benefit of the doubt for a session without a record:
            // only what the session's own hooks sent under is sent on.
            if (sender == Sender::Flush && recorded.is_none())
                || !catch_up_may_send(recorded, &attribution)
            {
                return Ok(Sent::Skipped);
            }
        }
    }

    // 8. The ApiClient (built above)
    let client = client.ok_or("server_url not configured")?;

    // 9. Try drain pending queue and send. A project-only queue this target
    // supersedes is first merged into the target's own queue (ahead of it:
    // its events are older), then drained like any queue — whatever is not
    // delivered now is re-queued into `pending_path`.
    // Only a BOUND repo adopts: a `repo switch` moves the whole session to
    // the repo. A repo inferred for this one event (VIS-1258) does not —
    // the queued project-only events touched other checkouts, or none, and
    // keep their own target until a project-only event or `flush` sends them.
    // Their transcript lines, not yet counted as sent, are re-read by this
    // event too, so those lines can reach both server rows; the tool events
    // themselves are never re-attributed.
    let pending_path = pending_path_for(session_dir, &attribution);
    let adopted = if inferred.is_some() && binding.is_none() {
        None
    } else {
        adopted_project_queue(session_dir, &attribution)
    };
    crate::pending_queue::upgrade(session_dir)?;
    // The adopted queue is read first (its events are older), and with it
    // whatever a reader that died left claimed from it: after the switch no
    // hook reads that queue under its own name again.
    // Its files become claims on this target's queue before anything is
    // sent, so a reader that takes them over sends them here as well.
    let claimed = match adopted {
        Some(adopted) => crate::pending_queue::claim(&adopted)?.retarget(&pending_path)?,
        None => crate::pending_queue::Claimed::default(),
    }
    .then(crate::pending_queue::claim(&pending_path)?);

    let mut send_failed = false;
    // Spans the whole invocation (pending-flush loop + live send below) so a
    // refused project binding prints its error at most once per invocation,
    // not once per buffered event.
    let mut warned = false;

    // Send pending events first, one record at a time (the queue is never
    // held whole in memory). At the first one that fails, or past the
    // delivery budget, the hook stops, and that record and the ones never
    // attempted stay queued, in order, ahead of what this hook queues below.
    // They are not copied back: the claim is cut down to them (see
    // `Claimed::finish`), so a hook killed at its timeout leaves every
    // record in one place, and a hook that queues meanwhile writes to a new
    // file.
    let mut rest = None;
    let mut reader = claimed.reader();
    while let Some(record) = reader.next_record()? {
        let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(&record) else {
            continue;
        };
        if std::time::Instant::now() >= deadline {
            send_failed = true;
            rest = Some(reader.before_last());
            break;
        }
        // Capped like `deliver_parts`, so the subagent sweep below is still
        // reached.
        let failure = match tokio::time::timeout_at(
            (deadline + IN_FLIGHT_GRACE).into(),
            send_stream_event(&client, &attribution, force, &pending_req, &mut warned),
        )
        .await
        {
            Ok(Ok(_)) => continue,
            Ok(Err(e)) => e.to_string(),
            Err(_) => "no answer in time".to_string(),
        };
        warn_unsent(&mut warned, &failure);
        if too_large(&failure) {
            // A record the server (or a proxy before it) finds too large
            // will be found so again: it is kept, since its lines are nowhere
            // else, but behind the others, which it must not hold up.
            crate::pending_queue::requeue(&pending_path, &record)?;
            continue;
        }
        send_failed = true;
        rest = Some(reader.before_last());
        break;
    }
    drop(reader);
    claimed.finish(rest, &pending_path)?;

    // Send the current event — several requests when its transcript batch
    // exceeds the request cap (see `split_into_parts`), never dropping lines.
    // A `session-end` without new lines has nothing to send: `Stop` already
    // ended the session on the server.
    let sends_event = sends_main
        && !(req.event_type == StreamEventType::Transcript && req.transcript_lines.is_none());
    // One answer for every batch of this event, the ones a `Stop` or a
    // `flush` reads on to included.
    let unsent = if is_inline {
        Unsent::Inline
    } else if event_type == "session-end" {
        Unsent::StayInFile
    } else {
        Unsent::Queued
    };
    let delivered = if sends_event {
        deliver_parts(
            &client,
            &attribution,
            force,
            split_into_parts(req),
            &pending_path,
            send_failed,
            deadline,
            unsent,
            &mut warned,
        )
        .await?
    } else {
        Delivered {
            all: true,
            lines: 0,
        }
    };
    let all_accepted = delivered.all;
    // 10. Advance .stream_offset once every part is accepted. The inline
    // (OpenCode) path CONSUMES its records from the hook event — they are not
    // re-readable like a transcript file — so its record counter must advance
    // whenever the event is accepted for delivery, INCLUDING when parts were
    // queued after a failure. Otherwise the next inline event reuses these
    // chunk_indexes and the server drops the overlap via ON CONFLICT. The queued
    // parts already carry their `transcript_offset`, so the records keep their
    // indices on drain.
    // Replaced atomically: the catch-up sweep can read it while this runs.
    // A file's offset advances past the lines that were accepted or queued
    // (see `Unsent`), so none is read a second time, and a batch too large
    // for one hook's budget is sent over several hooks.
    let mut all_accepted = all_accepted;
    if sends_main && sends_lines {
        let next = if is_inline {
            Some(new_offset)
        } else {
            batch.next_offset(&delivered)
        };
        if let Some(next) = next {
            advance_offset(&offset_path, next)?;
        }
        // `Stop` ends the session for the agents that have no later hook, so
        // it reads on to the transcript's end, batch by batch, where another
        // event leaves the rest to the next hook. Past the deadline the
        // batches are queued, not sent, and once the queue is full the rest
        // stays in the file.
        let mut read_on = (event_type == "stop" || sender == Sender::Flush)
            && !is_inline
            && next == Some(new_offset);
        while read_on {
            let mut more = read_transcript_batch(transcript_path, &offset_path, MAX_BATCH_BYTES)?;
            if more.end == more.start {
                break;
            }
            let mut delivered = Delivered {
                all: true,
                lines: 0,
            };
            if !more.lines.is_empty() {
                let mut req = subagent_template.clone();
                req.transcript_lines = Some(std::mem::take(&mut more.lines));
                req.transcript_offset = Some(more.start);
                delivered = deliver_parts(
                    &client,
                    &attribution,
                    force,
                    split_into_parts(req),
                    &pending_path,
                    send_failed || !all_accepted,
                    deadline,
                    unsent,
                    &mut warned,
                )
                .await?;
                all_accepted &= delivered.all;
            }
            let next = more.next_offset(&delivered);
            if let Some(next) = next {
                advance_offset(&offset_path, next)?;
            }
            read_on = next == Some(more.end);
        }
    }
    drop(main_lock);

    // 11. Subagent transcripts (Claude Code keeps each subagent's conversation
    // out of the main file). Swept on every hook, not only on `SubagentStop`,
    // so a long-running or background subagent is sent while it runs, and
    // the final hooks read every file to its end.
    let mut complete = !send_failed && all_accepted && sends_lines;
    if sender != Sender::CatchUp && agent == crate::agent::Agent::ClaudeCode {
        complete &= deliver_subagent_transcripts(
            &client,
            &attribution,
            force,
            &subagent_template,
            transcript_path,
            session_dir,
            &pending_path,
            send_failed || !all_accepted,
            deadline,
            matches!(event_type, "stop" | "subagent-stop" | "session-end")
                .then(|| deadline + FINAL_LOCK_WAIT),
            &mut warned,
        )
        .await?;
    }

    Ok(if complete {
        Sent::Accepted
    } else {
        Sent::Queued
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::api_client::AttributionMode;
    use crate::config::UserContext;
    use crate::context::{Context, EffectiveContext};
    use std::collections::BTreeMap;

    #[test]
    fn catch_up_sends_only_under_the_attribution_the_session_recorded() {
        let repo = |project: Option<uuid::Uuid>| Attribution::Repo {
            repo_id: "11111111-1111-1111-1111-111111111111".to_string(),
            project,
        };
        let a = uuid::Uuid::from_u128(0xa);
        let b = uuid::Uuid::from_u128(0xb);
        let only = |project_id| Attribution::ProjectOnly { project_id };

        let recorded = attribution_record(&repo(Some(a)));
        assert!(catch_up_may_send(Some(&recorded), &repo(Some(a))));
        assert!(!catch_up_may_send(Some(&recorded), &repo(Some(b))));
        assert!(!catch_up_may_send(Some(&recorded), &repo(None)));
        let recorded = attribution_record(&only(a));
        assert!(catch_up_may_send(Some(&recorded), &only(a)));
        assert!(!catch_up_may_send(Some(&recorded), &only(b)));
        // Recorded by an older CLI: the repo keys the row, the project does
        // not when there is no repo.
        assert!(catch_up_may_send(None, &repo(Some(b))));
        assert!(!catch_up_may_send(None, &only(a)));
    }

    #[test]
    fn record_metadata_keeps_the_other_keys() {
        let dir = tempfile::tempdir().unwrap();
        record_transcript_path(dir.path(), "/t.jsonl").unwrap();
        record_metadata(
            dir.path(),
            "attribution",
            serde_json::json!({"repo_id": "r"}),
        )
        .unwrap();
        let meta = session_metadata(dir.path());
        assert_eq!(meta["transcript_path"], "/t.jsonl");
        assert_eq!(meta["attribution"]["repo_id"], "r");
    }

    #[test]
    fn hook_events_map_to_server_events() {
        assert_eq!(
            stream_event_type("notification"),
            StreamEventType::SessionStart
        );
        // Every agent's `stop` ends the session; Claude Code's `session-end`
        // comes after it and must not end it again.
        assert_eq!(stream_event_type("stop"), StreamEventType::SessionEnd);
        assert_eq!(
            stream_event_type("session-end"),
            StreamEventType::Transcript
        );
        for event in ["pre-tool-use", "post-tool-use", "subagent-stop", "other"] {
            assert_eq!(
                stream_event_type(event),
                StreamEventType::ToolUse,
                "{event}"
            );
        }
    }

    // ── user layer resolution: disabled config → no user layer ────────────────

    #[test]
    fn disabled_user_context_resolves_to_none() {
        // Default/disabled `user_context` (the `Toggle(false)` variant) must
        // resolve to `None`, matching the pre-existing hook behavior of
        // stamping without a user layer when it isn't configured.
        assert!(UserContext::Toggle(false).resolve().is_none());
    }

    #[test]
    fn effective_with_no_user_layer_on_empty_repo_is_empty() {
        // With no user layer and no global/worktree context files present,
        // `Context::effective` must yield a default (empty) `EffectiveContext`
        // — i.e. passing `None` for `user_layer` is behavior-preserving.
        let dir = tempfile::tempdir().unwrap();
        let effective = Context::effective(dir.path(), None);
        assert_eq!(effective, EffectiveContext::default());
    }

    // ── apply_context: all three fields populated ─────────────────────────────

    #[test]
    fn apply_context_stamps_all_fields() {
        let dir = tempfile::tempdir().unwrap();
        let mut params = BTreeMap::new();
        params.insert("env".to_string(), "prod".to_string());
        params.insert("region".to_string(), "eu-west-1".to_string());

        let ctx = EffectiveContext {
            flow_id: Some("flow-xyz".to_string()),
            labels: vec!["backend".to_string(), "urgent".to_string()],
            params,
        };

        let (flow_id, labels, params_out) = apply_context(ctx);

        assert_eq!(flow_id, Some("flow-xyz".to_string()));
        assert_eq!(
            labels,
            Some(vec!["backend".to_string(), "urgent".to_string()])
        );
        let p = params_out.expect("params should be Some");
        assert_eq!(p.get("env").map(String::as_str), Some("prod"));
        assert_eq!(p.get("region").map(String::as_str), Some("eu-west-1"));

        // Verify the stored context round-trips through save_to → load_from →
        // merge_layers → apply_context (stored params are now `Option<String>`).
        let written = Context {
            flow_id: Some("flow-xyz".to_string()),
            labels: vec!["backend".to_string(), "urgent".to_string()],
            params: {
                let mut m = BTreeMap::new();
                m.insert("env".to_string(), Some("prod".to_string()));
                m.insert("region".to_string(), Some("eu-west-1".to_string()));
                m
            },
        };
        let ctx_path = dir.path().join(".visdom").join("context.json");
        written.save_to(&ctx_path).unwrap();
        let loaded = Context::load_from(&ctx_path);
        let (flow_id2, labels2, params2) = apply_context(Context::merge_layers(&[&loaded]));
        assert_eq!(flow_id2, Some("flow-xyz".to_string()));
        assert!(labels2.is_some());
        assert!(params2.is_some());
    }

    // ── apply_context: missing context file → all None ────────────────────────

    #[test]
    fn apply_context_missing_file_all_none() {
        let dir = tempfile::tempdir().unwrap();
        let missing_path = dir.path().join(".visdom").join("context.json");
        let ctx = Context::load_from(&missing_path); // no context.json → default
        let (flow_id, labels, params) = apply_context(Context::merge_layers(&[&ctx]));
        assert!(flow_id.is_none(), "flow_id should be None");
        assert!(labels.is_none(), "labels should be None");
        assert!(params.is_none(), "params should be None");
    }

    // ── apply_context: empty labels vec / empty params map → None ─────────────

    #[test]
    fn apply_context_empty_collections_are_none() {
        let ctx = EffectiveContext {
            flow_id: None,
            labels: vec![],
            params: BTreeMap::new(),
        };
        let (flow_id, labels, params) = apply_context(ctx);
        assert!(flow_id.is_none());
        assert!(
            labels.is_none(),
            "empty labels should be None, not Some([])"
        );
        assert!(
            params.is_none(),
            "empty params should be None, not Some({{}})"
        );
    }

    // ── apply_context: flow_id only, collections empty ────────────────────────

    #[test]
    fn apply_context_flow_id_only() {
        let ctx = EffectiveContext {
            flow_id: Some("my-flow".to_string()),
            labels: vec![],
            params: BTreeMap::new(),
        };
        let (flow_id, labels, params) = apply_context(ctx);
        assert_eq!(flow_id, Some("my-flow".to_string()));
        assert!(labels.is_none());
        assert!(params.is_none());
    }

    // ── resolve_session_paths tests ───────────────────────────────────────────
    //
    // These tests verify that `resolve_session_paths` routes through the
    // git-aware resolver so that sibling linked worktrees capture events under
    // the PRIMARY `.visdom/sessions/`, not the worktree directory.

    use crate::test_helpers::{add_worktree, init_git_repo};

    /// Primary checkout: project_root resolves to the repo root; session_dir is
    /// under `<repo>/.visdom/sessions/<id>/`.
    #[test]
    fn resolve_session_paths_primary_checkout() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_git_repo(&repo);
        // Create a .visdom/ in the primary root to match a real init.
        std::fs::create_dir_all(repo.join(".visdom")).unwrap();

        let (resolved, session_dir) = resolve_session_paths(&repo, "sess-primary-123");
        let project_root = resolved.root;

        assert_eq!(
            project_root.canonicalize().unwrap(),
            repo.canonicalize().unwrap(),
            "primary checkout: project_root must be repo root"
        );
        assert_eq!(
            session_dir.canonicalize().unwrap_or(session_dir.clone()),
            repo.join(".visdom")
                .join("sessions")
                .join("sess-primary-123"),
            "primary checkout: session_dir must be <repo>/.visdom/sessions/<id>/"
        );
        // session_dir must be INSIDE the primary repo, not elsewhere.
        assert!(
            session_dir.starts_with(&repo),
            "session_dir must be under the primary repo root"
        );
    }

    /// Sibling linked worktree: `hook_cwd` is OUTSIDE the primary repo tree.
    /// The old ancestor-walk would fall back to `hook_cwd` itself; the new
    /// git-aware resolver must return the PRIMARY root.
    #[test]
    fn resolve_session_paths_sibling_worktree_uses_primary_root() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        // Sibling worktree lives outside the primary repo directory.
        let wt = tmp.path().join("sibling-wt");

        std::fs::create_dir_all(&repo).unwrap();
        init_git_repo(&repo);
        // Place .visdom/ ONLY in the primary repo — not in the worktree.
        std::fs::create_dir_all(repo.join(".visdom")).unwrap();
        add_worktree(&repo, &wt);

        let (resolved, session_dir) = resolve_session_paths(&wt, "sess-sibling-456");
        let project_root = resolved.root;

        // Must resolve to the PRIMARY repo root, not the sibling worktree dir.
        assert_eq!(
            project_root.canonicalize().unwrap(),
            repo.canonicalize().unwrap(),
            "sibling worktree: project_root must be primary repo root (not worktree dir)"
        );
        // session_dir must be inside the PRIMARY .visdom/, not the worktree.
        assert!(
            session_dir.starts_with(&repo),
            "sibling worktree: session_dir must be under the PRIMARY repo root"
        );
        assert!(
            !session_dir.starts_with(&wt),
            "sibling worktree: session_dir must NOT be under the sibling worktree dir"
        );
        assert!(
            session_dir.ends_with(
                std::path::Path::new(".visdom")
                    .join("sessions")
                    .join("sess-sibling-456")
            ),
            "session_dir must end with .visdom/sessions/<session_id>"
        );
    }

    /// Non-git directory with no `.visdom/` ancestor: project_root falls
    /// back to `hook_cwd` itself (Fallback source); the function must not panic.
    #[test]
    fn resolve_session_paths_non_git_fallback() {
        let tmp = tempfile::tempdir().unwrap();
        // No git repo, no .visdom/ anywhere.
        let (resolved, session_dir) = resolve_session_paths(tmp.path(), "sess-fallback-789");
        let project_root = resolved.root;

        assert_eq!(
            project_root,
            tmp.path(),
            "non-git: project_root must fall back to hook_cwd"
        );
        assert_eq!(
            session_dir,
            tmp.path()
                .join(".visdom")
                .join("sessions")
                .join("sess-fallback-789"),
            "non-git: session_dir must be relative to the fallback root"
        );
    }

    /// The origin marker written by run_stream contains the worktree toplevel.
    /// This test exercises the same `paths::worktree_toplevel` helper the hook
    /// uses (can't call run_stream end-to-end without a real server) so the
    /// marker content is computed and canonicalized exactly as in production.
    #[test]
    fn origin_marker_written_in_session_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        std::fs::create_dir_all(&repo).unwrap();
        init_git_repo(&repo);

        let session_dir = repo.join(".visdom").join("sessions").join("test-sess-001");
        std::fs::create_dir_all(&session_dir).unwrap();

        let hook_cwd = &repo;
        let worktree_top = crate::paths::worktree_toplevel(hook_cwd);
        let _ = std::fs::write(session_dir.join("origin"), &worktree_top);

        let origin_content = std::fs::read_to_string(session_dir.join("origin")).unwrap();
        let expected = repo.canonicalize().unwrap().to_string_lossy().into_owned();
        assert_eq!(
            origin_content.trim(),
            expected.as_str(),
            "origin marker must contain the canonicalized worktree toplevel"
        );
    }

    fn metadata(session_dir: &Path) -> serde_json::Value {
        serde_json::from_str(&std::fs::read_to_string(session_dir.join("metadata.json")).unwrap())
            .unwrap()
    }

    #[test]
    fn record_transcript_path_writes_metadata_for_check() {
        let tmp = tempfile::tempdir().unwrap();
        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
    }

    #[test]
    fn record_transcript_path_keeps_other_keys_and_follows_a_new_path() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(
            tmp.path().join("metadata.json"),
            r#"{"transcript_path":"/t/old.jsonl","model":"m"}"#,
        )
        .unwrap();
        record_transcript_path(tmp.path(), "/t/new.jsonl").unwrap();
        let m = metadata(tmp.path());
        assert_eq!(m["transcript_path"], "/t/new.jsonl");
        assert_eq!(m["model"], "m");
        let leftovers = std::fs::read_dir(tmp.path())
            .unwrap()
            .filter(|e| e.as_ref().unwrap().file_name() != "metadata.json")
            .count();
        assert_eq!(leftovers, 0, "the temp file is renamed into place");
    }

    #[test]
    fn record_transcript_path_ignores_an_empty_path_and_replaces_garbage() {
        let tmp = tempfile::tempdir().unwrap();
        record_transcript_path(tmp.path(), "").unwrap();
        assert!(!tmp.path().join("metadata.json").exists());

        std::fs::write(tmp.path().join("metadata.json"), "not json").unwrap();
        record_transcript_path(tmp.path(), "/t/a.jsonl").unwrap();
        assert_eq!(metadata(tmp.path())["transcript_path"], "/t/a.jsonl");
    }

    // ── resolve_stream_binding: workspace-mode precedence for the stream hook ──

    use crate::session_state::{RepoBinding, SessionState};

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

    /// Workspace mode: no pinned config, but the session is bound (e.g. via
    /// `tracevault repo switch`) — the stream event attributes to that repo.
    #[test]
    fn resolve_stream_binding_uses_session_active_when_unbound() {
        let session = SessionState {
            active: Some(binding("session-repo")),
            subagents: HashMap::new(),
            ..Default::default()
        };
        let got = resolve_stream_binding(&session, "/wt/top", None, None);
        assert_eq!(got.unwrap().repo_id, "session-repo");
    }

    /// Bound-mode regression: an empty session (no `repo switch` ever run)
    /// with a bound config.toml still resolves via the config.
    #[test]
    fn resolve_stream_binding_falls_back_to_bound_config() {
        let session = SessionState::default();
        let got = resolve_stream_binding(&session, "/wt/top", Some(binding("bound-repo")), None);
        assert_eq!(got.unwrap().repo_id, "bound-repo");
    }

    /// No session binding and no bound config: nothing resolves, which is
    /// exactly what should trigger `run_stream`'s graceful no-op.
    #[test]
    fn resolve_stream_binding_none_when_nothing_resolves() {
        let session = SessionState::default();
        let got = resolve_stream_binding(&session, "/wt/top", None, None);
        assert!(got.is_none());
    }

    /// Subagent override precedence: a per-worktree override for the current
    /// worktree wins over the session's `active` binding.
    #[test]
    fn resolve_stream_binding_prefers_subagent_override_for_worktree() {
        let session = SessionState {
            active: Some(binding("session-repo")),
            subagents: HashMap::from([("/wt/x".to_string(), binding("subagent-repo"))]),
            ..Default::default()
        };
        let got = resolve_stream_binding(&session, "/wt/x", Some(binding("bound-repo")), None);
        assert_eq!(got.unwrap().repo_id, "subagent-repo");
    }

    /// Workspace mode: no bound config, but a user-level default is set (e.g.
    /// via `tracevault repo switch --user`) — the stream event attributes to
    /// that repo when nothing more specific resolves.
    #[test]
    fn resolve_stream_binding_falls_back_to_user_default() {
        let session = SessionState::default();
        let got = resolve_stream_binding(&session, "/wt/x", None, Some(binding("userdef")));
        assert_eq!(got.unwrap().repo_id, "userdef");
    }

    /// The user-level default is the LOWEST-precedence tier: a bound config
    /// still wins over it.
    #[test]
    fn resolve_stream_binding_prefers_bound_over_user_default() {
        let session = SessionState::default();
        let got = resolve_stream_binding(
            &session,
            "/wt/x",
            Some(binding("bound")),
            Some(binding("userdef")),
        );
        assert_eq!(got.unwrap().repo_id, "bound");
    }

    // ── attribution_for: repo-or-project gate ────────────────────────────────

    fn binding_with(repo_id: &str) -> crate::session_state::RepoBinding {
        crate::session_state::RepoBinding {
            repo_id: repo_id.into(),
            git_url: None,
            remote_id: None,
            codebase_name: None,
            updated_at: String::new(),
        }
    }

    /// The regression this whole change exists for: a session with a project
    /// binding and NO repo binding must still ship, repo-less, instead of
    /// being dropped by the hook.
    #[test]
    fn attribution_falls_back_to_project_when_no_repo_binds() {
        let pid = uuid::Uuid::new_v4();
        assert_eq!(
            attribution_for(None, Some(pid)),
            Some(Attribution::ProjectOnly { project_id: pid })
        );
    }

    /// Neither binding resolves — the only case that may still no-op.
    #[test]
    fn attribution_is_none_when_neither_repo_nor_project_binds() {
        assert_eq!(attribution_for(None, None), None);
    }

    /// A repo alone keeps the pre-existing repo-scoped behaviour, with the
    /// server left to deduce the project.
    #[test]
    fn attribution_uses_repo_with_no_project_overlay() {
        let repo = uuid::Uuid::new_v4().to_string();
        let b = binding_with(&repo);
        assert_eq!(
            attribution_for(Some(&b), None),
            Some(Attribution::Repo {
                repo_id: repo,
                project: None
            })
        );
    }

    /// Both bound: the project overlays the repo (project-scoped ingest
    /// carrying repo_id), unchanged from before.
    #[test]
    fn attribution_overlays_project_on_repo() {
        let repo = uuid::Uuid::new_v4().to_string();
        let pid = uuid::Uuid::new_v4();
        let b = binding_with(&repo);
        assert_eq!(
            attribution_for(Some(&b), Some(pid)),
            Some(Attribution::Repo {
                repo_id: repo,
                project: Some(pid)
            })
        );
    }

    /// A corrupted repo_id costs the repo attribution, not the trace: it
    /// degrades to project-only rather than dropping the event.
    #[test]
    fn attribution_degrades_a_corrupt_repo_id_to_project_only() {
        let pid = uuid::Uuid::new_v4();
        let b = binding_with("../../escape");
        assert_eq!(
            attribution_for(Some(&b), Some(pid)),
            Some(Attribution::ProjectOnly { project_id: pid })
        );
    }

    /// ...but with no project to fall back to, a corrupt repo_id still drops,
    /// so it can never reach the pending filename.
    #[test]
    fn attribution_drops_a_corrupt_repo_id_with_no_project() {
        let b = binding_with("../../escape");
        assert_eq!(attribution_for(Some(&b), None), None);
    }

    // ── pending queue filenames ──────────────────────────────────────────────

    /// The repo filename is unchanged, so queues buffered by earlier releases
    /// are still found and drained after this upgrade.
    #[test]
    fn pending_file_name_for_a_repo_is_unchanged() {
        let repo = uuid::Uuid::new_v4().to_string();
        assert_eq!(
            Attribution::Repo {
                repo_id: repo.clone(),
                project: Some(uuid::Uuid::new_v4())
            }
            .pending_file_name(),
            format!("pending-{repo}.jsonl")
        );
    }

    /// Repo-less queues carry the `project-` infix, which an older CLI reads
    /// as a non-UUID repo id and skips (see the doc comment).
    #[test]
    fn pending_file_name_for_a_project_is_distinct() {
        let pid = uuid::Uuid::new_v4();
        assert_eq!(
            Attribution::ProjectOnly { project_id: pid }.pending_file_name(),
            format!("pending-project-{pid}.jsonl")
        );
    }

    // ── binding_repo_id_is_valid: hook-attribution UUID guard ────────────────

    #[test]
    fn binding_repo_id_is_valid_accepts_real_uuid() {
        assert!(binding_repo_id_is_valid(
            "550e8400-e29b-41d4-a716-446655440000"
        ));
    }

    #[test]
    fn binding_repo_id_is_valid_rejects_path_traversal() {
        assert!(!binding_repo_id_is_valid("../evil"));
    }

    #[test]
    fn binding_repo_id_is_valid_rejects_empty() {
        assert!(!binding_repo_id_is_valid(""));
    }

    #[test]
    fn binding_repo_id_is_valid_rejects_non_uuid() {
        assert!(!binding_repo_id_is_valid("not-a-uuid"));
    }

    // ── stamp_agent: agent → tool/protocol_version mapping ───────────────────

    #[test]
    fn stamp_agent_sets_tool_and_version() {
        use crate::agent::Agent;
        let mut req = StreamEventRequest {
            protocol_version: 1,
            tool: Some("claude-code".to_string()),
            event_type: StreamEventType::ToolUse,
            session_id: "s".into(),
            timestamp: chrono::Utc::now(),
            hook_event_name: None,
            tool_name: None,
            tool_use_id: None,
            tool_input: None,
            tool_response: None,
            tool_is_error: None,
            event_index: None,
            event_uuid: None,
            transcript_lines: None,
            transcript_offset: None,
            model: None,
            cwd: None,
            final_stats: None,
            flow_id: None,
            labels: None,
            params: None,
            billing_mode: None,
        };
        stamp_agent(&mut req, Agent::Codex);
        assert_eq!(req.tool.as_deref(), Some("codex"));
        assert_eq!(req.protocol_version, 2);

        stamp_agent(&mut req, Agent::ClaudeCode);
        assert_eq!(req.tool.as_deref(), Some("claude-code"));
        assert_eq!(req.protocol_version, 1);
    }

    // ── pending_path_for: per-target offline queue ───────────────────────────

    fn repo_attr(repo_id: &str) -> Attribution {
        Attribution::Repo {
            repo_id: repo_id.into(),
            project: None,
        }
    }

    #[test]
    fn pending_path_is_repo_scoped() {
        let dir = std::path::Path::new("/tmp/sess");
        assert_eq!(
            pending_path_for(dir, &repo_attr("repo-a")),
            std::path::Path::new("/tmp/sess/pending-repo-a.jsonl")
        );
        assert_ne!(
            pending_path_for(dir, &repo_attr("repo-a")),
            pending_path_for(dir, &repo_attr("repo-b")),
        );
    }

    /// A repo-less session must not share a queue file with any repo, so its
    /// buffered events can never be flushed to a repo endpoint.
    #[test]
    fn pending_path_for_a_project_never_collides_with_a_repo() {
        let dir = std::path::Path::new("/tmp/sess");
        let pid = uuid::Uuid::from_u128(9);
        assert_eq!(
            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
            std::path::Path::new(&format!("/tmp/sess/pending-project-{pid}.jsonl"))
        );
        assert_ne!(
            pending_path_for(dir, &Attribution::ProjectOnly { project_id: pid }),
            pending_path_for(dir, &repo_attr(&pid.to_string())),
        );
    }

    // ── read_new_transcript_lines: empty transcript_path is a clean no-op ──────

    #[test]
    fn read_new_transcript_lines_empty_path_is_noop() {
        // Codex's nullable transcript_path deserializes to "" (see HookEvent).
        // An empty path must yield no lines and offset 0, never an error from
        // handing `Path::new("")` to exists()/File::open.
        let dir = tempfile::tempdir().unwrap();
        let offset_path = dir.path().join(".stream_offset");
        let (lines, start_offset, end_offset) =
            read_new_transcript_lines(std::path::Path::new(""), &offset_path).unwrap();
        assert!(
            lines.is_empty(),
            "empty path must yield no transcript lines"
        );
        assert_eq!(start_offset, 0);
        assert_eq!(end_offset, 0);
    }

    // ── read_new_transcript_lines: start_offset is stable across a persisted
    //    end_offset, and equals the previous read's end_offset ─────────────────

    #[test]
    fn read_new_transcript_lines_second_read_starts_at_previous_end() {
        let dir = tempfile::tempdir().unwrap();
        let transcript_path = dir.path().join("transcript.jsonl");
        let offset_path = dir.path().join(".stream_offset");

        fs::write(
            &transcript_path,
            "{\"type\":\"user\"}\n{\"type\":\"assistant\"}\n",
        )
        .unwrap();

        let (lines, start_offset, end_offset) =
            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
        assert_eq!(lines.len(), 2);
        assert_eq!(start_offset, 0, "first read starts at byte 0");
        assert!(end_offset > 0);

        fs::write(&offset_path, end_offset.to_string()).unwrap();

        let mut f = OpenOptions::new()
            .append(true)
            .open(&transcript_path)
            .unwrap();
        writeln!(f, "{{\"type\":\"user\",\"message\":\"more\"}}").unwrap();
        drop(f);

        let (lines2, start_offset2, end_offset2) =
            read_new_transcript_lines(&transcript_path, &offset_path).unwrap();
        assert_eq!(lines2.len(), 1);
        assert_eq!(
            start_offset2, end_offset,
            "second read's start_offset must equal the first read's persisted end_offset"
        );
        assert!(end_offset2 > start_offset2);
    }

    // ── capture_project: local-only project resolver ──────────────────────────

    /// Holds the env lock and points the config dir (`XDG_CONFIG_HOME` on
    /// Linux, `HOME` for macOS's `dirs::config_dir()`) at a tempdir: the last
    /// tier reads `user_project.toml` from there, so without isolation this
    /// test fails on any machine with a real user default and races tests
    /// that write one.
    ///
    /// `TRACEVAULT_PROJECT` is pinned UNSET for the same reason:
    /// `capture_project` reads it (rung 3, above `session.active_project`),
    /// and other tests in this same binary SET it. The crate lock only
    /// serializes mutators against each other, so a non-locking reader still
    /// races them — and `std::env::set_var` concurrent with `std::env::var`
    /// is exactly the UB the `unsafe` blocks in `EnvVarGuard` are annotated
    /// against. Holding the lock AND declaring the value is what makes the
    /// precedence assertions below describe the tiers they name rather than
    /// whatever the ambient shell happens to export.
    #[tokio::test]
    async fn capture_project_precedence_local_only() {
        use crate::session_state::{ProjectBinding, SessionState};
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.set("HOME", tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let pb = |id: &str| ProjectBinding {
            project_id: id.into(),
            project_name: "n".into(),
            updated_at: "".into(),
            forced_until: None,
        };
        let u = uuid::Uuid::from_u128;
        // session active only
        let s = SessionState {
            active_project: Some(pb(&u(2).to_string())),
            ..Default::default()
        };
        assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(2)));
        // subagent worktree beats session
        let mut s = s;
        s.subagent_projects
            .insert("/wt".into(), pb(&u(1).to_string()));
        assert_eq!(capture_project(&s, Some("/wt"), None), Some(u(1)));
        // no worktree match -> session active
        assert_eq!(capture_project(&s, Some("/other"), None), Some(u(2)));
        // empty session, no user_project.toml in the isolated config dir -> None
        assert_eq!(capture_project(&SessionState::default(), None, None), None);
        // malformed stored id -> None (defensive)
        let bad = SessionState {
            active_project: Some(pb("not-a-uuid")),
            ..Default::default()
        };
        assert_eq!(capture_project(&bad, None, None), None);
        // a valid user_project.toml in the isolated config dir is the last tier
        let path = crate::user_project_default::default_project_path().unwrap();
        assert!(path.starts_with(tmp.path()), "not isolated: {path:?}");
        crate::user_project_default::save(&pb(&u(3).to_string())).unwrap();
        assert_eq!(
            capture_project(&SessionState::default(), None, None),
            Some(u(3))
        );
    }

    /// The full binding — not just its id — survives `capture_binding`: this
    /// is what lets `attribution_mode` see a session-scoped `forced_until`
    /// (Important finding 1 in the VIS-305 Part C review: the old
    /// process-global disk read never saw a force written into SESSION
    /// state, which is where a plain `project switch --project-attribution
    /// explicit` — no `--user` — writes it).
    /// ENV ISOLATION: see `capture_project_precedence_local_only` — this
    /// test also goes through the capture chain, which reads
    /// `TRACEVAULT_PROJECT` at a rung ABOVE the session-active binding it is
    /// asserting on.
    #[test]
    fn capture_binding_preserves_forced_until_from_the_winning_tier() {
        use crate::session_state::{ProjectBinding, SessionState};
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_PROJECT");
        let pid = uuid::Uuid::from_u128(2);
        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
        let s = SessionState {
            active_project: Some(ProjectBinding {
                project_id: pid.to_string(),
                project_name: "n".into(),
                updated_at: "".into(),
                forced_until: Some(future.clone()),
            }),
            ..Default::default()
        };
        let got = capture_binding(&s, Some("/wt"), None).expect("session-active binding resolves");
        assert_eq!(got.forced_until, Some(future));
    }

    /// `_env_lock` serializes this against other tests in the crate that
    /// mutate `TRACEVAULT_PROJECT` (see `test_helpers::lock_env_mutation_sync`),
    /// including any that call `commands::project::status`, which reads the
    /// same var.
    #[test]
    fn env_project_binding_takes_a_uuid_and_ignores_a_name() {
        // A name would need a `list_projects` round trip, and this path runs
        // per-event in a short-lived hook process. Same rule already excludes
        // `config_default` here.
        let uuid = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";

        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();

        _guard.set("TRACEVAULT_PROJECT", uuid);
        let got = env_project_binding().expect("uuid form is honoured");
        assert_eq!(got.project_id, uuid);

        _guard.set("TRACEVAULT_PROJECT", "my-project");
        assert!(
            env_project_binding().is_none(),
            "a name is ignored on the network-free capture path"
        );

        _guard.remove("TRACEVAULT_PROJECT");
        assert!(env_project_binding().is_none());
    }

    // ── attribution_mode ───────────────────────────────────────────────────
    //
    // `attribution_mode` no longer touches disk at all: it takes the WINNING
    // binding (as resolved by `capture_project`) as a parameter, so these
    // tests only need to isolate `TRACEVAULT_PROJECT_ATTRIBUTION` via the
    // crate's env-mutation lock/guard, not `XDG_CONFIG_HOME`.

    fn forced_binding(forced_until: Option<&str>) -> crate::session_state::ProjectBinding {
        crate::session_state::ProjectBinding {
            project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
            project_name: "p".into(),
            updated_at: chrono::Utc::now().to_rfc3339(),
            forced_until: forced_until.map(str::to_string),
        }
    }

    #[test]
    fn env_force_is_explicit_and_needs_no_expiry() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");

        assert_eq!(attribution_mode(None), AttributionMode::Explicit);
    }

    #[test]
    fn absent_or_unrecognised_env_is_derived() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();

        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
        assert_eq!(attribution_mode(None), AttributionMode::Derived);

        // The CLI does not forward a value it does not recognise: the server
        // would 400 it, and failing a hook over a typo'd env var helps
        // nobody. The server's strictness is for callers that bypass the
        // CLI.
        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "yes-please");
        assert_eq!(attribution_mode(None), AttributionMode::Derived);
    }

    /// The binding-persisted half of `attribution_mode`: a LIVE `forced_until`
    /// on the WINNING binding (no env var involved) must also read as
    /// `explicit` — this is what `project switch --project-attribution
    /// explicit` ultimately drives, whether that binding lives in session
    /// state or the user-level default.
    #[test]
    fn live_binding_force_is_explicit_without_env() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
        let binding = forced_binding(Some(&future));

        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
    }

    /// This is the test that would fail if a lapsed persisted force still
    /// made it onto the wire: with no env override, a `forced_until` in the
    /// past on the winning binding must make `attribution_mode` — the exact
    /// function that supplies the header — report `derived`, not `explicit`.
    /// Not sending an `explicit` header IS the fallback to derived
    /// attribution.
    #[test]
    fn lapsed_binding_force_is_derived_without_env() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
        let binding = forced_binding(Some(&past));

        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
    }

    /// A `forced_until` that doesn't even parse as RFC3339 (a hand-edited or
    /// corrupted `user_project.toml`/session-state file) must fail SAFE —
    /// read as `derived`, never panic or, worse, read as `explicit`. Pins the
    /// fail-safe direction against a future refactor to `.expect(...)`.
    #[test]
    fn unparseable_forced_until_is_derived() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let binding = forced_binding(Some("not-a-timestamp"));

        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Derived);
    }

    /// Env-provided force must be exempt from expiry in fact, not just by
    /// coincidence of the OR: pairing it with a binding force that has
    /// ALREADY LAPSED still yields `explicit`. If `attribution_mode` were
    /// refactored to gate the env branch on any timestamp, this is the test
    /// that would catch it — `lapsed_binding_force_is_derived_without_env`
    /// alone couldn't, since it never sets the env var.
    #[test]
    fn env_force_is_explicit_even_with_a_lapsed_binding_force() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");

        let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
        let binding = forced_binding(Some(&past));

        assert_eq!(attribution_mode(Some(&binding)), AttributionMode::Explicit);
    }

    /// VIS-305 Part C review, Important finding 1: a SESSION-scoped force
    /// (`project switch --project-attribution explicit` WITHOUT `--user`,
    /// which is the default whenever a session id is set — i.e. the ordinary
    /// case inside every instrumented agent session) must actually reach the
    /// wire as `explicit`. The old process-global `attribution_mode` only
    /// ever consulted the user-level default store and never saw a force
    /// written into session state at all, so this would have silently sent
    /// `derived` while `project switch`'s own success message claimed
    /// membership was not being checked. Exercised end-to-end through
    /// `send_stream_event` and a real captured request header, not just the
    /// pure `attribution_mode` function, so a regression anywhere in the
    /// plumbing between `capture_project` and the wire is caught.
    #[tokio::test]
    async fn session_scoped_force_is_honoured_on_the_wire() {
        use crate::session_state::{ProjectBinding, SessionState};

        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        // No user-level default at all: the force under test lives ONLY in
        // session state, so a pass here can't be explained by an ambient or
        // accidentally-written user_project.toml.
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
        // `capture_project` reads `TRACEVAULT_PROJECT` ABOVE the
        // session-active tier this test pins the force on; unset it so an
        // ambient export can't redirect the capture at another project.
        _guard.remove("TRACEVAULT_PROJECT");

        let pid = uuid::Uuid::from_u128(321);
        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
        let session = SessionState {
            active_project: Some(ProjectBinding {
                project_id: pid.to_string(),
                project_name: "proj".into(),
                updated_at: "".into(),
                forced_until: Some(future),
            }),
            ..Default::default()
        };
        let capture_binding = capture_binding(&session, None, None);

        let resp = ok_stream_response();
        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let mut warned = false;

        let got = send_stream_event(
            &client,
            &Attribution::ProjectOnly { project_id: pid },
            attribution_force(capture_binding.as_ref()),
            &req,
            &mut warned,
        )
        .await
        .expect("send_stream_event must succeed");
        assert_eq!(got.status, "accepted");

        let captured = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            captured
                .to_lowercase()
                .contains("x-tracevault-project-attribution: explicit"),
            "a session-scoped (no --user) force must reach the wire as `explicit`, got: {captured}"
        );
    }

    /// VIS-305 Part C review, Important finding 2: a LIVE force sitting on
    /// the machine-global user-level default must NOT leak onto a different,
    /// higher-precedence project that resolves instead. The old
    /// process-global `attribution_mode` couldn't tell the two apart — it
    /// declared `explicit` for ANY project as long as SOME force existed
    /// anywhere on disk. Here the user-default's force belongs to project A,
    /// but `TRACEVAULT_PROJECT` (a higher-precedence local tier) points this
    /// capture at project B, which was never forced.
    #[test]
    fn user_default_force_does_not_leak_onto_a_higher_precedence_project() {
        use crate::session_state::{ProjectBinding, SessionState};

        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let project_a = uuid::Uuid::from_u128(1);
        let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
        crate::user_project_default::save(&ProjectBinding {
            project_id: project_a.to_string(),
            project_name: "a".into(),
            updated_at: chrono::Utc::now().to_rfc3339(),
            forced_until: Some(future),
        })
        .unwrap();

        let project_b = uuid::Uuid::from_u128(2);
        _guard.set("TRACEVAULT_PROJECT", project_b.to_string());

        let capture_binding = capture_binding(&SessionState::default(), None, None);
        assert_eq!(
            capture_binding.as_ref().map(|b| b.project_id.as_str()),
            Some(project_b.to_string()).as_deref(),
            "TRACEVAULT_PROJECT must outrank the user-level default"
        );

        assert_eq!(
            attribution_mode(capture_binding.as_ref()),
            AttributionMode::Derived,
            "a force on the user-default project must not leak onto a DIFFERENT, \
             higher-precedence project that never asked to be forced"
        );
    }

    // ── send_stream_event: endpoint routing based on capture_pid ──────────────

    use std::io::BufReader;
    use std::net::TcpListener;
    use std::sync::mpsc;
    use std::thread;
    use std::time::{Duration, Instant};

    /// How long an accept loop waits for a connection that never arrives
    /// (e.g. a regression that stops the client from making an expected
    /// request) before giving up, so the server thread exits cleanly
    /// instead of blocking in `accept()` forever.
    const ACCEPT_DEADLINE: Duration = Duration::from_secs(5);

    /// Poll a non-blocking `listener` for a connection until one arrives or
    /// `ACCEPT_DEADLINE` elapses. Returns `None` on timeout (or any non-
    /// `WouldBlock` accept error) so callers can stop cleanly rather than
    /// block forever.
    fn accept_with_deadline(listener: &TcpListener) -> Option<std::net::TcpStream> {
        let deadline = Instant::now() + ACCEPT_DEADLINE;
        loop {
            match listener.accept() {
                Ok((stream, _)) => {
                    // The accepted stream's blocking mode isn't guaranteed to
                    // be inherited from the (non-blocking) listener across
                    // platforms — make it explicitly blocking so the
                    // subsequent read/write calls behave as before.
                    let _ = stream.set_nonblocking(false);
                    return Some(stream);
                }
                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
                    if Instant::now() >= deadline {
                        return None;
                    }
                    thread::sleep(Duration::from_millis(20));
                }
                Err(_) => return None,
            }
        }
    }

    /// How long a test waits for the captured request before failing (rather
    /// than hanging forever if the client never connects). Mirrors the
    /// harness in `tests/stream_event_project_test.rs`.
    const SEND_STREAM_EVENT_RECV_TIMEOUT: Duration = Duration::from_secs(5);

    /// Read one request's line and headers off `stream`, hand the pair to
    /// `tx` as a single string, then write `response` back.
    ///
    /// Shared by [`spawn_once_capturing_request`] and
    /// [`spawn_n_capturing_requests`], which grew this same capture
    /// independently and disagreed only on `trim()` vs `trim_end()` for the
    /// blank-line terminator (equivalent, since a bare CRLF trims empty
    /// either way).
    ///
    /// Deliberately NOT `test_helpers::read_request`: that one is private to
    /// its module and blocks in `accept()`, where these two use
    /// `set_nonblocking` plus a deadline.
    ///
    /// Headers are captured, not just the request line, so a test can assert
    /// on `x-tracevault-project-attribution` — without them a regression that
    /// hardcoded `"derived"` at a `stream_event_for_project` call site would
    /// pass the whole suite, since nothing in-crate ever looked at the header
    /// actually sent. They are appended AFTER the request line, leaving
    /// `starts_with`/`contains` assertions on the line itself unaffected.
    fn capture_request_and_respond(
        stream: std::net::TcpStream,
        tx: &mpsc::Sender<String>,
        response: &str,
    ) {
        let mut reader = BufReader::new(stream);
        let mut captured = String::new();
        let _ = reader.read_line(&mut captured);
        loop {
            let mut header = String::new();
            if reader.read_line(&mut header).unwrap_or(0) == 0 {
                break;
            }
            if header.trim().is_empty() {
                break;
            }
            captured.push_str(&header);
        }
        let _ = tx.send(captured);
        let mut stream = reader.into_inner();
        let _ = stream.write_all(response.as_bytes());
        let _ = stream.flush();
    }

    /// Spawn a one-shot server that returns `response` (a full HTTP response)
    /// to the first request, capturing it via
    /// [`capture_request_and_respond`]. Mirrors the harness in
    /// `tests/stream_event_project_test.rs` / `tests/resolve_remote_test.rs`.
    fn spawn_once_capturing_request(response: &'static str) -> (String, mpsc::Receiver<String>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            if let Some(stream) = accept_with_deadline(&listener) {
                capture_request_and_respond(stream, &tx, response);
            }
        });
        (format!("http://{addr}"), rx)
    }

    fn ok_stream_response() -> String {
        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
            session_db_id: uuid::Uuid::nil(),
            event_db_id: Some(uuid::Uuid::nil()),
            status: "accepted".to_string(),
        })
        .unwrap();
        format!(
            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        )
    }

    fn sample_stream_event_request() -> StreamEventRequest {
        StreamEventRequest {
            protocol_version: 2,
            tool: Some("claude-code".to_string()),
            event_type: StreamEventType::ToolUse,
            session_id: "sess-1".into(),
            timestamp: chrono::Utc::now(),
            hook_event_name: Some("PostToolUse".into()),
            tool_name: None,
            tool_use_id: None,
            tool_input: None,
            tool_response: None,
            tool_is_error: None,
            event_index: None,
            event_uuid: None,
            transcript_lines: None,
            transcript_offset: None,
            model: None,
            cwd: None,
            final_stats: None,
            flow_id: None,
            labels: None,
            params: None,
            billing_mode: None,
        }
    }

    /// With a `SessionState` whose `active_project` is set, `capture_project`
    /// resolves a `capture_pid`, and `send_stream_event` must route to the
    /// project-scoped endpoint (`/projects/{pid}/stream?repo_id=...`) rather
    /// than the repo-scoped one.
    #[tokio::test]
    async fn send_stream_event_routes_to_project_endpoint_when_binding_active() {
        use crate::session_state::{ProjectBinding, SessionState};

        // Isolate from any ambient user-level project default so this test's
        // `capture_project` call depends only on the SessionState below —
        // mirrors the isolation pattern in `commands::project`'s tests.
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        // `capture_project` reads `TRACEVAULT_PROJECT` above the
        // session-active tier asserted below — pin it unset. Ditto
        // `TRACEVAULT_PROJECT_ATTRIBUTION`, which the `derived` header
        // assertion at the end of this test depends on.
        _guard.remove("TRACEVAULT_PROJECT");
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let pid = uuid::Uuid::from_u128(99);
        let session = SessionState {
            active_project: Some(ProjectBinding {
                project_id: pid.to_string(),
                project_name: "proj".into(),
                updated_at: "".into(),
                forced_until: None,
            }),
            ..Default::default()
        };
        let capture_binding = capture_binding(&session, None, None);
        let capture_pid = capture_binding
            .as_ref()
            .and_then(crate::resolution::capture_project_id);
        assert_eq!(capture_pid, Some(pid));

        let resp = ok_stream_response();
        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();

        let mut warned = false;
        let got = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: capture_pid,
            },
            attribution_force(capture_binding.as_ref()),
            &req,
            &mut warned,
        )
        .await
        .expect("send_stream_event must succeed");
        assert_eq!(got.status, "accepted");

        let line = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            line.starts_with(&format!(
                "POST /api/v1/projects/{pid}/stream?repo_id=11111111-1111-1111-1111-111111111111 "
            )),
            "an active project binding must route to the project-scoped endpoint, got: {line}"
        );
        // Covers the `Attribution::Repo { project: Some(_) }` call site of
        // `stream_event_for_project` (the `ProjectOnly` call site is covered
        // by `session_scoped_force_is_honoured_on_the_wire` and
        // `send_stream_event_project_only_omits_repo_id`) — an unforced
        // binding must still send the header, declaring `derived`.
        assert!(
            line.to_lowercase()
                .contains("x-tracevault-project-attribution: derived"),
            "got: {line}"
        );
    }

    /// With an empty binding (default `SessionState`, no worktree override)
    /// and no user-level default present in the test env, `capture_project`
    /// resolves `None` and `send_stream_event` must fall back to the
    /// repo-scoped endpoint.
    #[tokio::test]
    async fn send_stream_event_routes_to_repo_endpoint_when_no_binding() {
        use crate::session_state::SessionState;

        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        // No user_project.toml under this isolated config dir, so there is no
        // ambient user-level default to leak in — and no `TRACEVAULT_PROJECT`
        // either, which `capture_project` would otherwise honour and turn
        // this "nothing resolves" case into a project-scoped send.
        _guard.set("XDG_CONFIG_HOME", tmp.path());
        _guard.remove("TRACEVAULT_PROJECT");

        let capture_binding = capture_binding(&SessionState::default(), None, None);
        assert_eq!(capture_binding, None);

        let resp = ok_stream_response();
        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();

        let mut warned = false;
        let got = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: None,
            },
            attribution_force(capture_binding.as_ref()),
            &req,
            &mut warned,
        )
        .await
        .expect("send_stream_event must succeed");
        assert_eq!(got.status, "accepted");

        let line = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            line.starts_with("POST /api/v1/repos/11111111-1111-1111-1111-111111111111/stream "),
            "no binding must fall back to the repo-scoped endpoint, got: {line}"
        );
    }

    // ── I1/I2: refused project-scoped send is an error + transient no-fallback ───

    /// Spawn a server that replies to up to `responses.len()` sequential
    /// connections with the given full HTTP responses, in order, capturing
    /// each request (line + headers, via [`capture_request_and_respond`])
    /// over the channel. The listening socket itself is dropped (closing it)
    /// once all responses have been served, so any further connection attempt
    /// fails fast (connection refused) rather than hanging for the client's
    /// request timeout — this lets a test assert "no further request was
    /// sent" cheaply.
    fn spawn_n_capturing_requests(
        responses: Vec<&'static str>,
    ) -> (String, mpsc::Receiver<String>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        listener.set_nonblocking(true).unwrap();
        let addr = listener.local_addr().unwrap();
        let (tx, rx) = mpsc::channel();
        thread::spawn(move || {
            for response in responses {
                // If a regression stops the client from making this request
                // (e.g. the expected Nth call never happens), don't block
                // forever in `accept()` — give up after `ACCEPT_DEADLINE`
                // and let the thread end so the test process can't hang.
                let Some(stream) = accept_with_deadline(&listener) else {
                    break;
                };
                capture_request_and_respond(stream, &tx, response);
            }
            // `listener` (and `tx`) drop here, closing the socket and the
            // channel — a stray extra request gets ECONNREFUSED immediately
            // instead of hanging, and a stray extra `rx.recv` returns
            // Disconnected immediately instead of blocking.
        });
        (format!("http://{addr}"), rx)
    }

    /// I1: a deterministic 400 ("is not a member of project ...") from the
    /// project-scoped endpoint must be an error, not a silent second send to
    /// the repo-scoped endpoint. TWO responses (400 then 200) are staged so
    /// the "no second request" check is non-vacuous — see the comment in
    /// `send_stream_event_project_only_drops_on_scoping_4xx` for why a single
    /// staged response would make that assertion pass vacuously.
    #[tokio::test]
    async fn send_stream_event_errors_on_deterministic_400_without_fallback() {
        let body_400 = "repo 11111111-1111-1111-1111-111111111111 is not a member of project 22222222-2222-2222-2222-222222222222";
        let resp_400 = format!(
            "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body_400.len(),
            body_400
        );
        let resp_200 = ok_stream_response();

        let (base, rx) = spawn_n_capturing_requests(vec![
            Box::leak(resp_400.into_boxed_str()),
            Box::leak(resp_200.into_boxed_str()),
        ]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(42);

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: Some(pid),
            },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a refused declared project must be an error, not a silent fallback");
        assert!(
            err.to_string().contains("400"),
            "propagated error must reflect the status, got: {err}"
        );
        assert!(
            warned,
            "the refusal must be printed (gated on `warned`) so it is visible"
        );

        let first = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no first request captured");
        assert!(
            first.contains(&format!("/projects/{pid}/stream")),
            "first request must hit the project-scoped endpoint, got: {first}"
        );
        assert!(
            first.contains("repo_id="),
            "first request must carry repo_id, got: {first}"
        );

        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "no second (repo-scoped fallback) request must be sent"
        );
    }

    /// A 403 from the project-scoped endpoint must likewise be an error, not a
    /// silent second send to the repo-scoped endpoint.
    #[tokio::test]
    async fn send_stream_event_errors_on_403_without_fallback() {
        let body_403 = "forbidden";
        let resp_403 = format!(
            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body_403.len(),
            body_403
        );
        let resp_200 = ok_stream_response();

        let (base, rx) = spawn_n_capturing_requests(vec![
            Box::leak(resp_403.into_boxed_str()),
            Box::leak(resp_200.into_boxed_str()),
        ]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(43);

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: Some(pid),
            },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a refused declared project must be an error, not a silent fallback");
        assert!(
            err.to_string().contains("403"),
            "propagated error must reflect the status, got: {err}"
        );
        assert!(
            warned,
            "the refusal must be printed (gated on `warned`) so it is visible"
        );

        let first = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no first request captured");
        assert!(
            first.contains(&format!("/projects/{pid}/stream")),
            "first request must hit the project-scoped endpoint, got: {first}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "no second (repo-scoped fallback) request must be sent"
        );
    }

    /// The refusal error must be printed at most once per hook invocation
    /// (i.e. per shared `warned` flag), even across multiple calls sharing
    /// it — mirroring how the pending-flush loop and the live send share one
    /// `warned` for a single invocation.
    #[tokio::test]
    async fn refused_error_is_printed_once_per_invocation() {
        let body_400 = "not a member";
        let resp_400 = || {
            format!(
                "HTTP/1.1 400 Bad Request\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
                body_400.len(),
                body_400
            )
        };
        let (base, _rx) = spawn_n_capturing_requests(vec![
            Box::leak(resp_400().into_boxed_str()),
            Box::leak(resp_400().into_boxed_str()),
        ]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(44);
        let attribution = Attribution::Repo {
            repo_id: "11111111-1111-1111-1111-111111111111".into(),
            project: Some(pid),
        };

        let mut warned = false;
        assert!(
            send_stream_event(
                &client,
                &attribution,
                attribution_force(None),
                &req,
                &mut warned
            )
            .await
            .is_err(),
            "a refused declared project must be an error"
        );
        assert!(warned, "the flag must be set after the first refusal");

        assert!(
            send_stream_event(
                &client,
                &attribution,
                attribution_force(None),
                &req,
                &mut warned
            )
            .await
            .is_err(),
            "a second refusal must also be an error"
        );
        assert!(warned, "the flag stays set across the shared invocation");
    }

    /// Finding 5's scenario end to end, on the repo-bound path, as VIS-316
    /// leaves it: a live persisted force makes this send declare `explicit`,
    /// the force gate refuses it with a 403 — and the event is now an ERROR
    /// queued for retry, never re-sent to the repo-scoped endpoint where the
    /// server would DEDUCE a project that is precisely not the one the
    /// operator forced.
    ///
    /// Pins the fact the refusal clause depends on: the mode that went on
    /// the wire really is `explicit`, and it is the same value
    /// `refused_error` is handed — the message and the wire cannot disagree.
    /// A spare 200 is staged so "no second request" is non-vacuous.
    #[tokio::test]
    async fn a_refused_force_declares_explicit_and_is_an_error_not_a_fallback() {
        let body_403 = "forbidden";
        let resp_403 = format!(
            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body_403.len(),
            body_403
        );
        let resp_200 = ok_stream_response();

        let (base, rx) = spawn_n_capturing_requests(vec![
            Box::leak(resp_403.into_boxed_str()),
            Box::leak(resp_200.into_boxed_str()),
        ]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(42);

        // A live persisted force on the winning binding — no env var needed,
        // so this test takes no env lock.
        let forced = crate::session_state::ProjectBinding {
            project_id: pid.to_string(),
            project_name: "forced".into(),
            updated_at: "".into(),
            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
        };

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: Some(pid),
            },
            attribution_force(Some(&forced)),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a refused force must be an error, not a silent fallback");
        assert!(
            err.to_string().contains("403"),
            "propagated error must reflect the status, got: {err}"
        );
        assert!(warned, "the refusal must be printed exactly once");

        let first = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no first request captured");
        assert!(
            first.contains(&format!("/projects/{pid}/stream")),
            "first request must hit the project-scoped endpoint, got: {first}"
        );
        assert!(
            first
                .to_lowercase()
                .contains("x-tracevault-project-attribution: explicit"),
            "the refused send must have DECLARED explicit — this is the mode \
             `refused_error` is handed: {first}"
        );

        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "a refused force must NOT be re-attributed via the repo-scoped endpoint"
        );
    }

    /// The repo-less send: a `ProjectOnly` attribution must hit the bare
    /// project endpoint with NO `repo_id` query pair. This is the wire shape
    /// the server documents as "repo-less (0-repo) projects are supported".
    ///
    /// Takes the env lock and pins `TRACEVAULT_PROJECT_ATTRIBUTION` unset:
    /// this test also asserts the `derived` attribution header, and
    /// `attribution_mode` reads that variable even when the binding passed
    /// in is `None`.
    #[tokio::test]
    async fn send_stream_event_project_only_omits_repo_id() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let resp = ok_stream_response();
        let (base, rx) = spawn_once_capturing_request(Box::leak(resp.into_boxed_str()));
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(11);

        let mut warned = false;
        let got = send_stream_event(
            &client,
            &Attribution::ProjectOnly { project_id: pid },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect("a repo-less project send must succeed");
        assert_eq!(got.status, "accepted");

        let line = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            line.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
            "expected a bare project path with no query string, got: {line}"
        );
        assert!(
            line.to_lowercase()
                .contains("x-tracevault-project-attribution: derived"),
            "with no forced binding, the header must declare `derived`, got: {line}"
        );
        assert!(
            !warned,
            "a repo-less send has no fallback and must not warn about one"
        );
    }

    /// VIS-1255 / VIS-316: a `Scoping` 4xx on a repo-less send is an ERROR
    /// that goes through the normal buffer path — `Err`, so the caller queues
    /// it in `pending-project-<pid>.jsonl` and `.stream_offset` stays put.
    /// It used to be dropped as `Ok(None)`, which advanced the offset and so
    /// lost the transcript lines for good. Exactly one request: there is no
    /// endpoint to fall back to, and none may be tried.
    #[tokio::test]
    async fn send_stream_event_project_only_buffers_on_scoping_4xx() {
        let body = "no such project";
        let resp_404 = format!(
            "HTTP/1.1 404 Not Found\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        // TWO responses are staged although only one request is expected. With
        // a single response the helper drops its sender the moment the list is
        // exhausted, so the "no second request" assertion below would pass on
        // `Disconnected` whether or not a second request happened — a vacuous
        // check. Staging a spare keeps the server accepting, so a stray
        // request really is captured and really fails the test.
        let (base, rx) = spawn_n_capturing_requests(vec![
            Box::leak(resp_404.clone().into_boxed_str()),
            Box::leak(resp_404.into_boxed_str()),
        ]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(12);

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::ProjectOnly { project_id: pid },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a refused repo-less send must propagate so the caller buffers it");
        assert_eq!(
            deterministic_client_error_kind(err.as_ref()),
            Some(ClientErrorKind::Scoping),
            "the original 404 must propagate unchanged, got: {err}"
        );
        assert!(warned, "the refusal is printed (once per invocation)");

        let first = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            first.starts_with(&format!("POST /api/v1/projects/{pid}/stream ")),
            "must hit the bare project-scoped endpoint, got: {first}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "a repo-less send must make exactly one request — no fallback exists"
        );
    }

    /// The repo-less refusal must not borrow the repo-scoped wording ("does
    /// not apply to this repo"), must say the event was queued (not dropped),
    /// and must name `repo switch` as a way out for a `Scoping` refusal.
    #[test]
    fn refused_project_only_error_wording() {
        let pid = uuid::Uuid::from_u128(0x55);
        let scoping =
            refused_project_only_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
        assert!(scoping.starts_with("tracevault: error:"), "{scoping}");
        assert!(scoping.contains(&pid.to_string()), "{scoping}");
        assert!(scoping.contains("queued"), "{scoping}");
        assert!(!scoping.contains("DROPPED"), "{scoping}");
        assert!(!scoping.contains("this repo"), "{scoping}");
        assert!(scoping.contains("tracevault repo switch"), "{scoping}");

        let forbidden = refused_project_only_error(
            pid,
            &ClientErrorKind::Forbidden,
            AttributionForce::default(),
        );
        assert!(forbidden.contains("(403)"), "{forbidden}");
        assert!(forbidden.contains("queued"), "{forbidden}");
        assert!(!forbidden.contains("FORCE"), "derived send: {forbidden}");

        let forced = AttributionForce {
            env: true,
            binding: false,
        };
        let explicit = refused_project_only_error(pid, &ClientErrorKind::Forbidden, forced);
        assert!(
            explicit.contains("FORCE itself"),
            "an explicit 403 must name the force, like the repo-scoped line: {explicit}"
        );
        assert!(
            !refused_project_only_error(pid, &ClientErrorKind::Scoping, forced)
                .contains("FORCE itself"),
            "a Scoping refusal never ran the force gate"
        );
    }

    /// `adopted_project_queue`: only `Repo { project: Some(pid) }` adopts, and
    /// only `pending-project-<pid>.jsonl` for that same pid.
    #[test]
    fn recording_line_names_each_attribution_shape() {
        let pid = uuid::Uuid::from_u128(0x99);
        let repo = "11111111-1111-1111-1111-111111111111".to_string();
        let only = recording_line(Some(&Attribution::ProjectOnly { project_id: pid }));
        assert!(only.starts_with("recording: project "), "{only}");
        assert!(
            only.contains(&pid.to_string()) && only.contains("no repo"),
            "{only}"
        );
        let both = recording_line(Some(&Attribution::Repo {
            repo_id: repo.clone(),
            project: Some(pid),
        }));
        assert!(
            both.contains(&repo) && both.contains(&pid.to_string()),
            "{both}"
        );
        let deduced = recording_line(Some(&Attribution::Repo {
            repo_id: repo.clone(),
            project: None,
        }));
        assert!(
            deduced.contains(&repo) && deduced.contains("deduces"),
            "{deduced}"
        );
        let none = recording_line(None);
        assert!(none.starts_with("recording: nothing"), "{none}");
    }

    fn repo_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(),
        }
    }

    /// A project-only session whose hook cached a repo for `checkout`.
    fn inferring_session(
        pid: uuid::Uuid,
        checkout: &str,
        repo: &str,
    ) -> crate::session_state::SessionState {
        let mut state = crate::session_state::SessionState {
            active_project: Some(crate::session_state::ProjectBinding {
                project_id: pid.to_string(),
                project_name: "p".into(),
                updated_at: "t".into(),
                forced_until: None,
            }),
            ..Default::default()
        };
        state.inferred_repos.insert(
            checkout.into(),
            crate::session_state::InferredRepo {
                project_id: pid.to_string(),
                retry_after: None,
                repo: Some(repo_binding(repo)),
            },
        );
        state
    }

    /// VIS-1258: an inferred repo applies only with no repo binding and a
    /// project, and is sent within that project.
    #[test]
    fn attribution_with_inference_never_overrides_a_binding() {
        let pid = uuid::Uuid::from_u128(0x1258);
        let bound = repo_binding("11111111-1111-1111-1111-111111111111");
        let inferred = repo_binding("22222222-2222-2222-2222-222222222222");
        let repo = |id: &str| Attribution::Repo {
            repo_id: id.into(),
            project: Some(pid),
        };

        assert_eq!(
            attribution_with_inference(None, Some(pid), Some(&inferred)),
            Some(repo(&inferred.repo_id))
        );
        assert_eq!(
            attribution_with_inference(Some(&bound), Some(pid), Some(&inferred)),
            Some(repo(&bound.repo_id))
        );
        // A corrupt binding is still the session's choice: project-only, as
        // before, never the inferred repo.
        let corrupt = repo_binding("not-a-uuid");
        assert_eq!(
            attribution_with_inference(Some(&corrupt), Some(pid), Some(&inferred)),
            Some(Attribution::ProjectOnly { project_id: pid })
        );
        // No project: nothing to infer within.
        assert_eq!(
            attribution_with_inference(None, None, Some(&inferred)),
            None
        );
        assert_eq!(
            attribution_with_inference(None, Some(pid), Some(&corrupt)),
            Some(Attribution::ProjectOnly { project_id: pid })
        );
    }

    /// `status` reports the cached inferred repo for its checkout, labelled as
    /// inferred; another checkout reads as project-only.
    #[test]
    fn recording_attribution_labels_an_inferred_repo() {
        // Reads `TRACEVAULT_PROJECT`, which other tests set for a while.
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut env = crate::test_helpers::EnvVarGuard::new();
        env.remove("TRACEVAULT_PROJECT");
        env.remove("VISDOM_PROJECT");
        let pid = uuid::Uuid::from_u128(0x1258);
        let repo = "22222222-2222-2222-2222-222222222222";
        let state = inferring_session(pid, "/umbrella/child", repo);

        let here = recording_attribution_for(&state, "/umbrella/child", None, None, None);
        assert_eq!(
            here.attribution,
            Some(Attribution::Repo {
                repo_id: repo.into(),
                project: Some(pid)
            })
        );
        assert_eq!(here.inferred_from.as_deref(), Some("/umbrella/child"));
        let line = recording_line_for(&here);
        assert!(
            line.contains(repo) && line.contains("inferred from the checkout /umbrella/child"),
            "{line}"
        );

        let elsewhere = recording_attribution_for(&state, "/umbrella", None, None, None);
        assert_eq!(
            elsewhere.attribution,
            Some(Attribution::ProjectOnly { project_id: pid })
        );
        assert_eq!(elsewhere.inferred_from, None);
        assert_eq!(
            recording_line_for(&elsewhere),
            recording_line(elsewhere.attribution.as_ref())
        );

        // A bound repo is reported as bound, not inferred.
        let bound = repo_binding("11111111-1111-1111-1111-111111111111");
        let explicit =
            recording_attribution_for(&state, "/umbrella/child", Some(bound.clone()), None, None);
        assert_eq!(
            explicit.attribution,
            Some(Attribution::Repo {
                repo_id: bound.repo_id,
                project: Some(pid)
            })
        );
        assert_eq!(explicit.inferred_from, None);

        // The project may come from the workspace config tier (VIS-1256)
        // instead of the session: inference applies all the same.
        let mut from_config = state.clone();
        from_config.active_project = None;
        let workspace = crate::session_state::ProjectBinding {
            project_id: pid.to_string(),
            project_name: String::new(),
            updated_at: String::new(),
            forced_until: None,
        };
        let via_config =
            recording_attribution_for(&from_config, "/umbrella/child", None, None, Some(workspace));
        assert_eq!(via_config.inferred_from.as_deref(), Some("/umbrella/child"));
    }

    #[test]
    fn adopted_project_queue_only_for_the_same_project() {
        let dir = Path::new("/tmp/sess");
        let pid = uuid::Uuid::from_u128(0x77);
        let repo_id = "11111111-1111-1111-1111-111111111111".to_string();
        assert_eq!(
            adopted_project_queue(
                dir,
                &Attribution::Repo {
                    repo_id: repo_id.clone(),
                    project: Some(pid),
                }
            ),
            Some(dir.join(format!("pending-project-{pid}.jsonl")))
        );
        assert_eq!(
            adopted_project_queue(
                dir,
                &Attribution::Repo {
                    repo_id,
                    project: None,
                }
            ),
            None,
            "with no declared project the server deduces one; adopting would re-attribute"
        );
        assert_eq!(
            adopted_project_queue(dir, &Attribution::ProjectOnly { project_id: pid }),
            None,
            "a project-only target already drains its own queue"
        );
    }

    /// A 403 is NOT dropped. It can mean the account has no `tracevault` grant,
    /// which an administrator can grant — after which the buffered events do
    /// deliver. It must propagate so the caller queues them.
    #[tokio::test]
    async fn send_stream_event_project_only_buffers_on_403() {
        let body = "forbidden";
        let resp_403 = format!(
            "HTTP/1.1 403 Forbidden\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body.len(),
            body
        );
        let (base, _rx) = spawn_n_capturing_requests(vec![Box::leak(resp_403.into_boxed_str())]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::ProjectOnly {
                project_id: uuid::Uuid::from_u128(13),
            },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a 403 is recoverable by a role grant, so it must buffer, not drop");
        assert!(
            err.to_string().contains("403"),
            "propagated error must reflect the status, got: {err}"
        );
    }

    /// I2: a transient 503 from the project-scoped endpoint must propagate as
    /// an `Err` WITHOUT falling back to the repo-scoped endpoint, so the
    /// existing buffer/retry logic in `run_stream` still handles it. Only one
    /// request (to the project endpoint) may be observed.
    #[tokio::test]
    async fn send_stream_event_does_not_fall_back_on_transient_503() {
        let body_503 = "internal error";
        let resp_503 = format!(
            "HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
            body_503.len(),
            body_503
        );
        let (base, rx) = spawn_n_capturing_requests(vec![Box::leak(resp_503.into_boxed_str())]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let req = sample_stream_event_request();
        let pid = uuid::Uuid::from_u128(7);

        let mut warned = false;
        let err = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: Some(pid),
            },
            attribution_force(None),
            &req,
            &mut warned,
        )
        .await
        .expect_err("a transient 503 must propagate as Err, not be swallowed by a fallback");
        assert!(
            err.to_string().contains("503"),
            "propagated error must reflect the transient status, got: {err}"
        );
        assert!(
            deterministic_client_error_kind(err.as_ref()).is_none(),
            "a 503 must not be classified as a deterministic client error"
        );

        let first = rx
            .recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT)
            .expect("no request captured");
        assert!(
            first.contains(&format!("/projects/{pid}/stream")),
            "must hit the project-scoped endpoint, got: {first}"
        );

        // The mock server only serves ONE response and then drops its
        // listener/sender — a stray fallback request would either fail the
        // `expect_err` above (if it somehow succeeded) or, if it also failed,
        // would still mean a second request was attempted. Confirming the
        // channel is immediately disconnected (rather than blocking) proves
        // no second request was ever sent.
        assert!(
            rx.recv_timeout(SEND_STREAM_EVENT_RECV_TIMEOUT).is_err(),
            "no second (fallback) request should have been sent for a transient error"
        );
    }

    /// A 403 must be classified apart from the binding/scoping statuses: since
    /// Keycloak it has a second, now more common cause (no `tracevault` grant
    /// at all) whose advice is completely different.
    #[test]
    fn a_403_is_classified_apart_from_the_scoping_statuses() {
        let err = |s: &str| -> Box<dyn std::error::Error> { s.to_string().into() };
        assert_eq!(
            deterministic_client_error_kind(err("Stream failed (403 Forbidden): {}").as_ref()),
            Some(ClientErrorKind::Forbidden)
        );
        for scoping in [
            "Stream failed (400 Bad Request): {}",
            "Stream failed (404 Not Found): {}",
            "Stream failed (409 Conflict): {}",
        ] {
            assert_eq!(
                deterministic_client_error_kind(err(scoping).as_ref()),
                Some(ClientErrorKind::Scoping),
                "{scoping}"
            );
        }
        // Unchanged: 401 and transient failures are not deterministic client
        // errors and must keep propagating to buffer/retry.
        for transient in [
            "Stream failed (401 Unauthorized): {}",
            "Stream failed (503 Service Unavailable): {}",
            "error sending request for url (http://x/stream)",
        ] {
            assert_eq!(
                deterministic_client_error_kind(err(transient).as_ref()),
                None,
                "{transient}"
            );
        }
    }

    /// The 403 error must not tell a user whose account has no `tracevault` grant
    /// to switch projects, which cannot possibly help. It names both causes,
    /// and — since the CLI no longer re-attributes to another project — must
    /// never claim it did.
    #[test]
    fn refused_error_names_both_403_causes_and_never_claims_re_attribution() {
        let pid = uuid::Uuid::from_u128(7);

        let forbidden = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            AttributionForce::default(),
        );
        assert!(forbidden.contains("403"), "{forbidden}");
        assert!(
            forbidden.contains("no `tracevault` grant in Control Plane"),
            "must offer the missing-role explanation: {forbidden}"
        );
        assert!(
            forbidden.contains("no `Operator` role on it"),
            "must still offer the project explanation: {forbidden}"
        );
        assert!(
            forbidden.starts_with("tracevault: error:"),
            "a refusal is an error, not a warning: {forbidden}"
        );
        assert!(forbidden.contains(&pid.to_string()));

        // A 400/404/409 genuinely IS a binding problem, so that wording stays
        // unhedged — hedging everything would dilute the useful case.
        let scoping = refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default());
        assert!(scoping.contains("project switch"), "{scoping}");
        assert!(
            !scoping.contains("`tracevault` grant"),
            "the scoping case must not mention the `tracevault` grant: {scoping}"
        );

        for s in [&forbidden, &scoping] {
            // A machine-wide default is rebound with `--user`; without the
            // hint, `project switch` in a session only shadows it.
            assert!(s.contains("--user"), "must name the --user fix: {s}");
            assert!(
                s.contains("user_project.toml"),
                "must name the machine-wide default's file: {s}"
            );
            assert!(
                !s.contains("repo deduction"),
                "must never describe re-attribution to another project: {s}"
            );
            assert!(
                !s.contains("Attributing via"),
                "must never claim the event was re-attributed: {s}"
            );
        }
    }

    /// VIS-305 whole-branch review, Important finding 5: a REFUSED FORCE
    /// said nothing about the force. The 403 the force gate returns for "not
    /// Operator on the project" or "`explicit` from a `tvk_` key" is
    /// indistinguishable from here (see `ClientErrorKind`) from a membership
    /// 403, so an operator who asked for `explicit` got a message about
    /// membership and realm roles and was never told the force itself was
    /// what got refused. Failing closed on trust is right; failing closed
    /// silently is the defect. (VIS-316 made the refusal an error rather
    /// than a fallback; the missing explanation is orthogonal to that and
    /// still has to be given.)
    #[test]
    fn the_403_error_says_the_force_was_refused_when_the_send_declared_explicit() {
        let pid = uuid::Uuid::from_u128(7);

        let explicit = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            AttributionForce {
                env: false,
                binding: true,
            },
        );
        assert!(
            explicit.contains("FORCE"),
            "the refusal of the force itself must be named: {explicit}"
        );
        assert!(
            explicit.contains("Operator"),
            "must name the grant forcing requires: {explicit}"
        );
        assert!(
            explicit.contains("Control Plane"),
            "must name the identity forcing requires: {explicit}"
        );
        // `main`'s Forbidden wording is ADDED TO, not replaced: the
        // membership causes it already names must survive alongside the
        // force clause.
        assert!(
            explicit.contains("`tracevault` grant")
                && explicit.contains("no `Operator` role on it"),
            "the membership causes must still be named: {explicit}"
        );
        // The event is queued, not re-attributed — the force clause must not
        // reintroduce the claim VIS-316 removed.
        assert!(
            !explicit.contains("repo deduction") && !explicit.contains("Attributing via"),
            "must never claim the event was re-attributed: {explicit}"
        );

        // Same 403, `derived` mode: no force was asked for, so none was
        // refused and the clause must not appear. This is the discriminating
        // half — without it the test would pass on a message that blamed the
        // force unconditionally, which is just a different wrong story.
        let derived = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            AttributionForce::default(),
        );
        assert!(
            !derived.contains("FORCE"),
            "a `derived` send never forced anything: {derived}"
        );
    }

    /// The force clause belongs to the 403 the force gate returns, and to
    /// nothing else: a 400/404/409 means the project id does not resolve, so
    /// the gate never ran. Blaming the force there would be a new wrong
    /// explanation of the same family as the one finding 5 reports.
    #[test]
    fn an_explicit_scoping_failure_does_not_blame_the_force() {
        let pid = uuid::Uuid::from_u128(7);
        let scoping = refused_error(
            pid,
            &ClientErrorKind::Scoping,
            AttributionForce {
                env: true,
                binding: true,
            },
        );
        assert!(!scoping.contains("FORCE"), "{scoping}");
        assert_eq!(
            scoping,
            refused_error(pid, &ClientErrorKind::Scoping, AttributionForce::default()),
            "the scoping wording does not depend on the mode"
        );
    }

    /// Copilot on PR #54: the remediation told EVERY forced sender to switch
    /// again without `--project-attribution explicit`. That clears a
    /// persisted `forced_until` and nothing else — so when the force came
    /// from `TRACEVAULT_PROJECT_ATTRIBUTION`, [`attribution_force`] goes on
    /// reading the environment, every later send still declares `explicit`,
    /// and the advice silently does nothing. On the one code path a confused
    /// operator reaches.
    ///
    /// Each case is driven through `attribution_force` and a REAL exported
    /// variable rather than a hand-built struct, so what this pins is the
    /// whole path: the value that decides the header is the value the
    /// wording is derived from, and the two cannot describe different
    /// worlds.
    ///
    /// Discriminating in both directions — each case asserts the fix that
    /// applies AND the absence of the one that doesn't — because a message
    /// that simply listed both remediations every time would pass a
    /// one-sided test while being the same "advice that may not apply"
    /// defect in a longer form.
    #[test]
    fn the_403_remediation_names_the_force_source_actually_in_effect() {
        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
        let mut _guard = crate::test_helpers::EnvVarGuard::new();
        let pid = uuid::Uuid::from_u128(7);
        let live = forced_binding(Some(
            &(chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339(),
        ));
        let never_forced = forced_binding(None);

        // ENV ONLY. The binding carries no force at all, so "switch again
        // without the flag" would change precisely nothing: the next send
        // reads the same variable and declares `explicit` again.
        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
        let env_only = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            attribution_force(Some(&never_forced)),
        );
        assert!(
            env_only.contains("FORCE"),
            "an env-sourced force is still a force: {env_only}"
        );
        assert!(
            env_only.contains("unset `TRACEVAULT_PROJECT_ATTRIBUTION`"),
            "must name the variable that is doing the forcing: {env_only}"
        );
        assert!(
            !env_only.contains("--project-attribution"),
            "must NOT tell the operator to drop a flag that would change \
             nothing here — this is the bug: {env_only}"
        );

        // BINDING ONLY. Now the flag advice is the right one, and naming the
        // env var would send the operator hunting for an export that isn't
        // set.
        _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
        let binding_only = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            attribution_force(Some(&live)),
        );
        assert!(
            binding_only.contains("--project-attribution"),
            "a persisted force IS cleared by switching without the flag: {binding_only}"
        );
        assert!(
            !binding_only.contains("TRACEVAULT_PROJECT_ATTRIBUTION"),
            "must not send the operator after an unset variable: {binding_only}"
        );

        // BOTH. Removing either one alone leaves the other forcing, which
        // would look exactly like the fix not working — so the message has
        // to say both must go.
        _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
        let both = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            attribution_force(Some(&live)),
        );
        assert!(
            both.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
                && both.contains("--project-attribution"),
            "both sources are in effect and both must be named: {both}"
        );
        assert!(
            both.contains("BOTH"),
            "must say that removing only one is not enough: {both}"
        );
    }

    /// The remediation is built from the same `AttributionForce` the header
    /// is, so it can never describe a force the send did not declare: with
    /// no source set there is no force clause at all, whatever the wording
    /// of the fixes would have been.
    #[test]
    fn no_force_means_no_remediation_clause() {
        let pid = uuid::Uuid::from_u128(7);
        let none = refused_error(
            pid,
            &ClientErrorKind::Forbidden,
            AttributionForce::default(),
        );
        assert!(
            !none.contains("TRACEVAULT_PROJECT_ATTRIBUTION")
                && !none.contains("--project-attribution"),
            "a derived send has no force to remove: {none}"
        );
    }

    // ── VIS-1018: a batch over the request cap is split, never dropped ────────

    /// A transcript of `n` lines, each about `line_bytes` long, written to
    /// `dir/transcript.jsonl`.
    fn write_transcript(dir: &Path, n: usize, line_bytes: usize) -> std::path::PathBuf {
        let path = dir.join("transcript.jsonl");
        let mut body = String::new();
        for i in 0..n {
            let line = serde_json::json!({
                "type": "user",
                "n": i,
                "message": {"content": "x".repeat(line_bytes)},
            });
            body.push_str(&line.to_string());
            body.push('\n');
        }
        fs::write(&path, body).unwrap();
        path
    }

    /// The tool event a hook would build around a transcript batch.
    fn event_with_lines(lines: Vec<serde_json::Value>, offset: i64) -> StreamEventRequest {
        StreamEventRequest {
            tool_name: Some("Bash".into()),
            tool_use_id: Some("toolu_1".into()),
            tool_input: Some(serde_json::json!({"command": "ls"})),
            event_uuid: Some(uuid::Uuid::now_v7()),
            transcript_lines: Some(lines),
            transcript_offset: Some(offset),
            ..sample_stream_event_request()
        }
    }

    fn part_lines(part: &StreamEventRequest) -> Vec<serde_json::Value> {
        part.transcript_lines.clone().unwrap_or_default()
    }

    /// `(chunk_index, line)` for every line of `parts`, as the server derives
    /// it: `transcript_offset + index within the request`.
    fn chunk_indexes(parts: &[StreamEventRequest]) -> Vec<(i64, serde_json::Value)> {
        parts
            .iter()
            .flat_map(|p| {
                let offset = p.transcript_offset.unwrap();
                part_lines(p)
                    .into_iter()
                    .enumerate()
                    .map(move |(i, l)| (offset + i as i64, l))
            })
            .collect()
    }

    /// `n` lines of about `bytes` each.
    fn big_lines(n: usize, bytes: usize) -> Vec<serde_json::Value> {
        (0..n)
            .map(|i| serde_json::json!({"n": i, "text": "y".repeat(bytes)}))
            .collect()
    }

    #[test]
    fn split_leaves_a_request_under_the_cap_unchanged() {
        let req = event_with_lines(big_lines(3, 100), 0);

        let parts = split_into_parts(req.clone());

        assert_eq!(parts.len(), 1);
        assert_eq!(
            serde_json::to_value(&parts[0]).unwrap(),
            serde_json::to_value(&req).unwrap()
        );
    }

    /// The prod loss: a batch over 512 KiB used to go out with
    /// `transcript_lines = None` while `.stream_offset` moved past it. Every
    /// line must now arrive, in order, in requests that each fit the cap.
    #[test]
    fn split_carries_every_line_of_a_batch_over_the_cap() {
        let dir = tempfile::tempdir().unwrap();
        // ~1.5 MiB: three to four requests' worth.
        let transcript = write_transcript(dir.path(), 300, 5_000);
        let (lines, start, _) =
            read_new_transcript_lines(&transcript, &dir.path().join(".stream_offset")).unwrap();
        let req = event_with_lines(lines.clone(), start);
        assert!(req.serialized_len() > MAX_REQUEST_BYTES);

        let parts = split_into_parts(req.clone());

        assert!(parts.len() >= 3, "got {} parts", parts.len());
        for part in &parts {
            assert!(
                part.serialized_len() <= MAX_REQUEST_BYTES,
                "part of {} bytes exceeds the cap",
                part.serialized_len()
            );
        }
        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
        assert_eq!(sent, lines, "every line, once, in order");

        // The event goes once, last; the parts before it are lines only.
        let (event, transcript_parts) = parts.split_last().unwrap();
        assert_eq!(event.event_type, StreamEventType::ToolUse);
        assert_eq!(event.event_uuid, req.event_uuid);
        assert_eq!(event.tool_input, req.tool_input);
        for part in transcript_parts {
            assert_eq!(part.event_type, StreamEventType::Transcript);
            assert!(part.event_uuid.is_none());
            assert!(part.tool_input.is_none());
            assert!(part.tool_name.is_none());
        }
        assert!(
            !part_lines(event).is_empty(),
            "the event keeps the lines that fit beside it"
        );
    }

    /// Every line gets the chunk_index it has unsplit (`batch offset + its
    /// index in the batch`), so the server stores the same rows as for one
    /// request.
    #[test]
    fn split_keeps_each_lines_unsplit_chunk_index() {
        let lines = big_lines(300, 5_000);
        let parts = split_into_parts(event_with_lines(lines.clone(), 1_000));

        let expected: Vec<_> = lines
            .into_iter()
            .enumerate()
            .map(|(i, l)| (1_000 + i as i64, l))
            .collect();
        assert_eq!(chunk_indexes(&parts), expected);
    }

    /// Two hooks of one session read from the same offset concurrently and
    /// see different lengths, so they cut the batch at different places: a
    /// line shared by both must still get one chunk_index, or ON CONFLICT
    /// keeps both copies.
    #[test]
    fn split_gives_a_line_one_chunk_index_whatever_the_batch_length() {
        let lines = big_lines(10, 200_000);
        let short = chunk_indexes(&split_into_parts(event_with_lines(lines[..4].to_vec(), 0)));
        let long = chunk_indexes(&split_into_parts(event_with_lines(lines.clone(), 0)));

        for (index, line) in &short {
            let in_long = long.iter().find(|(_, l)| l == line).unwrap();
            assert_eq!(in_long.0, *index, "line {line} indexed differently");
        }
    }

    /// A single line over the cap cannot be split: it goes alone rather than
    /// being dropped, and the lines around it still travel.
    #[test]
    fn split_sends_a_single_oversized_line_alone() {
        let lines = vec![
            serde_json::json!({"n": 0}),
            serde_json::json!({"n": 1, "text": "z".repeat(MAX_REQUEST_BYTES)}),
            serde_json::json!({"n": 2}),
        ];

        let parts = split_into_parts(event_with_lines(lines.clone(), 0));

        let sent: Vec<_> = parts.iter().flat_map(part_lines).collect();
        assert_eq!(sent, lines);
        let big = parts
            .iter()
            .find(|p| part_lines(p).contains(&lines[1]))
            .unwrap();
        assert_eq!(part_lines(big).len(), 1, "the oversized line travels alone");
        assert_eq!(big.transcript_offset, Some(1));
    }

    fn far_deadline() -> std::time::Instant {
        std::time::Instant::now() + Duration::from_secs(60)
    }

    fn captured_body(captured: &str) -> StreamEventRequest {
        let body = captured.splitn(3, " | ").nth(2).expect("captured body");
        serde_json::from_str(body).expect("request body is a StreamEventRequest")
    }

    /// Every part reaches the server, in order, with its own offset.
    #[tokio::test]
    async fn deliver_parts_sends_every_part() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));

        let all_accepted = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts.clone(),
            &pending_path,
            false,
            far_deadline(),
            Unsent::Inline,
            &mut false,
        )
        .await
        .unwrap()
        .all;

        assert!(all_accepted);
        for part in &parts {
            let got = captured_body(&rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap());
            assert_eq!(got.transcript_offset, part.transcript_offset);
            assert_eq!(got.transcript_lines, part.transcript_lines);
        }
        assert!(drain_pending(&pending_path).unwrap().is_empty());
    }

    /// A part that fails is queued with the parts after it, in order and
    /// unsent, and the delivery reports that not everything was accepted (so
    /// a file-based hook keeps `.stream_offset` where it was).
    #[tokio::test]
    async fn deliver_parts_queues_the_failed_part_and_the_rest() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
        assert!(parts.len() >= 3);
        let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));

        let all_accepted = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts.clone(),
            &pending_path,
            false,
            far_deadline(),
            Unsent::Inline,
            &mut false,
        )
        .await
        .unwrap()
        .all;

        assert!(!all_accepted);
        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
        assert!(rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).is_ok());
        assert!(
            rx.recv_timeout(Duration::from_millis(300)).is_err(),
            "nothing is sent after the first failure"
        );
        let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
            .unwrap()
            .iter()
            .map(|j| serde_json::from_str(j).unwrap())
            .collect();
        assert_eq!(queued.len(), parts.len() - 1);
        for (q, part) in queued.iter().zip(&parts[1..]) {
            assert_eq!(q.transcript_offset, part.transcript_offset);
            assert_eq!(q.transcript_lines, part.transcript_lines);
        }
    }

    /// Older events still queued (`send_failed`): the new parts queue behind
    /// them without a send.
    #[tokio::test]
    async fn deliver_parts_queues_everything_behind_an_earlier_failure() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let parts = split_into_parts(sample_stream_event_request());
        let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));

        let all_accepted = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts,
            &pending_path,
            true,
            far_deadline(),
            Unsent::Inline,
            &mut false,
        )
        .await
        .unwrap()
        .all;

        assert!(!all_accepted);
        assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
    }

    /// Past the delivery budget nothing more is sent: the parts are queued
    /// before the agent can kill the hook at its timeout and lose them.
    #[tokio::test]
    async fn deliver_parts_queues_the_rest_once_the_budget_is_spent() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let parts = split_into_parts(event_with_lines(big_lines(300, 5_000), 0));
        let (base, rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(); parts.len()]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));

        let all_accepted = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts.clone(),
            &pending_path,
            false,
            std::time::Instant::now(),
            Unsent::Inline,
            &mut false,
        )
        .await
        .unwrap()
        .all;

        assert!(!all_accepted);
        assert!(rx.recv_timeout(Duration::from_millis(300)).is_err());
        assert_eq!(drain_pending(&pending_path).unwrap().len(), parts.len());
    }

    /// A request that hangs is given up shortly after the budget and its part
    /// queued, rather than held until the client's 60 s timeout: the agent
    /// kills the hook first (losing the part), and the hook would keep a
    /// subagent file's lock a final hook is waiting for.
    #[tokio::test]
    async fn deliver_parts_queues_a_request_still_in_flight_past_the_grace() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        // Accepts (the kernel backlog does) but never answers.
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let started = Instant::now();

        let all_accepted = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            vec![event_with_lines(big_lines(1, 10), 0)],
            &pending_path,
            false,
            started + Duration::from_millis(100),
            Unsent::Inline,
            &mut false,
        )
        .await
        .unwrap()
        .all;

        assert!(!all_accepted);
        assert!(started.elapsed() < Duration::from_secs(10));
        assert_eq!(drain_pending(&pending_path).unwrap().len(), 1);
        drop(listener);
    }

    // ── VIS-1078: subagent transcripts, one file per request ─────────────────

    const PARENT_SESSION: &str = "parent-session";
    const SUBAGENT_REPO: &str = "11111111-1111-1111-1111-111111111111";

    /// A Claude Code session laid out as 2.1.x writes it: the main transcript
    /// `<dir>/<session>.jsonl` and its subagents' `<dir>/<session>/subagents/`.
    /// Returns `(main transcript, subagents dir, tracevault session dir)`.
    fn claude_session(dir: &Path) -> (std::path::PathBuf, std::path::PathBuf, std::path::PathBuf) {
        let main = dir.join(format!("{PARENT_SESSION}.jsonl"));
        fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
        let subagents = dir.join(PARENT_SESSION).join("subagents");
        fs::create_dir_all(&subagents).unwrap();
        let session_dir = dir.join("tv-session");
        fs::create_dir_all(&session_dir).unwrap();
        (main, subagents, session_dir)
    }

    fn subagent_line(agent: &str, n: usize) -> String {
        serde_json::json!({"agentId": agent, "sessionId": PARENT_SESSION, "n": n}).to_string()
    }

    fn append_raw(path: &Path, text: &str) {
        let mut f = fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(path)
            .unwrap();
        f.write_all(text.as_bytes()).unwrap();
    }

    fn append_subagent_lines(subagents: &Path, agent: &str, ns: std::ops::Range<usize>) {
        let path = subagents.join(format!("agent-{agent}.jsonl"));
        for n in ns {
            append_raw(&path, &format!("{}\n", subagent_line(agent, n)));
        }
    }

    /// One hook's sweep against a server that answers `responses` and then
    /// stops listening, so any request beyond them fails (and is queued).
    /// Returns the requests the server received, in order.
    async fn sweep(
        responses: Vec<String>,
        main: &Path,
        session_dir: &Path,
        pending_path: &Path,
    ) -> Vec<StreamEventRequest> {
        sweep_waiting(responses, main, session_dir, pending_path, None).await
    }

    /// [`sweep`] as a final hook, waiting for a busy file's lock until
    /// `wait_for_lock`.
    async fn sweep_waiting(
        responses: Vec<String>,
        main: &Path,
        session_dir: &Path,
        pending_path: &Path,
        wait_for_lock: Option<Instant>,
    ) -> Vec<StreamEventRequest> {
        let expected = responses.len();
        let (base, rx) = crate::test_helpers::spawn_seq(responses);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));
        let event = StreamEventRequest {
            session_id: PARENT_SESSION.into(),
            ..sample_stream_event_request()
        };
        deliver_subagent_transcripts(
            &client,
            &repo_attr(SUBAGENT_REPO),
            AttributionForce::default(),
            &transcript_template(&event),
            main,
            session_dir,
            pending_path,
            false,
            Instant::now() + Duration::from_secs(60),
            wait_for_lock,
            &mut false,
        )
        .await
        .unwrap();
        (0..expected)
            .map(|_| {
                let captured = rx.recv_timeout(Duration::from_secs(5)).expect("request");
                assert!(
                    captured.starts_with(&format!("POST /api/v1/repos/{SUBAGENT_REPO}/stream ")),
                    "{captured}"
                );
                let body = captured.splitn(3, " | ").nth(2).unwrap();
                serde_json::from_str(body).unwrap()
            })
            .collect()
    }

    fn agent_of(line: &serde_json::Value) -> &str {
        line["agentId"].as_str().unwrap()
    }

    /// Every request carries the lines of exactly one subagent, under the
    /// parent session, as lines only, and its `transcript_offset` is the byte
    /// offset of its first line in that subagent's own file.
    fn assert_one_file_per_request(subagents: &Path, reqs: &[StreamEventRequest]) {
        for req in reqs {
            assert_eq!(req.event_type, StreamEventType::Transcript);
            assert_eq!(req.session_id, PARENT_SESSION);
            assert!(req.event_uuid.is_none() && req.tool_name.is_none());
            let lines = part_lines(req);
            let agent = agent_of(&lines[0]);
            assert!(
                lines.iter().all(|l| agent_of(l) == agent),
                "a request mixes subagent files: {lines:?}"
            );
            let file = fs::read_to_string(subagents.join(format!("agent-{agent}.jsonl"))).unwrap();
            let first = file.find(&lines[0].to_string()).unwrap() as i64;
            assert_eq!(req.transcript_offset, Some(first));
        }
    }

    #[tokio::test]
    async fn subagent_lines_appended_across_hooks_are_each_sent_once_per_file() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        let ok = ok_stream_response;
        let mut all = Vec::new();

        // Hook 1: both subagents have started.
        append_subagent_lines(&subagents, "a1", 0..2);
        append_subagent_lines(&subagents, "b2", 0..1);
        fs::write(subagents.join("agent-a1.meta.json"), "{}").unwrap();
        let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
        assert_eq!(reqs.len(), 2);
        all.extend(reqs);

        // Hook 2: both appended; b2 is caught mid-line.
        append_subagent_lines(&subagents, "a1", 2..3);
        append_subagent_lines(&subagents, "b2", 1..2);
        let partial = subagent_line("b2", 2);
        let (head, tail) = partial.split_at(10);
        append_raw(&subagents.join("agent-b2.jsonl"), head);
        let reqs = sweep(vec![ok(), ok()], &main, &session_dir, &pending).await;
        assert_eq!(reqs.len(), 2);
        all.extend(reqs);

        // Hook 3: b2 finishes the line; a1 is idle.
        append_raw(&subagents.join("agent-b2.jsonl"), &format!("{tail}\n"));
        let reqs = sweep(vec![ok()], &main, &session_dir, &pending).await;
        assert_eq!(reqs.len(), 1);
        all.extend(reqs);

        // Hook 4: nothing new, nothing sent.
        assert!(sweep(vec![], &main, &session_dir, &pending)
            .await
            .is_empty());
        assert!(!pending.exists(), "nothing may have failed and been queued");

        assert_one_file_per_request(&subagents, &all);
        let mut sent: Vec<(String, u64)> = all
            .iter()
            .flat_map(part_lines)
            .map(|l| (agent_of(&l).to_string(), l["n"].as_u64().unwrap()))
            .collect();
        sent.sort();
        let expected: Vec<(String, u64)> = [
            ("a1", 0),
            ("a1", 1),
            ("a1", 2),
            ("b2", 0),
            ("b2", 1),
            ("b2", 2),
        ]
        .into_iter()
        .map(|(a, n)| (a.to_string(), n))
        .collect();
        assert_eq!(sent, expected, "each line exactly once");
    }

    #[tokio::test]
    async fn a_session_without_subagents_sends_nothing_extra() {
        let dir = tempfile::tempdir().unwrap();
        let main = dir.path().join(format!("{PARENT_SESSION}.jsonl"));
        fs::write(&main, "{\"type\":\"user\"}\n").unwrap();
        let session_dir = dir.path().join("tv-session");
        fs::create_dir_all(&session_dir).unwrap();
        let pending = session_dir.join("pending.jsonl");

        assert!(sweep(vec![], &main, &session_dir, &pending)
            .await
            .is_empty());
        assert_eq!(fs::read_dir(&session_dir).unwrap().count(), 0);
    }

    /// A failed send queues the file's batch and moves its offset past it, so
    /// the lines are in one place only: the next hook does not read them
    /// again. Files after the failure are queued too, behind it, rather than
    /// sent out of order, each under the offset within its own file.
    #[tokio::test]
    async fn a_failed_subagent_send_is_queued_once_and_not_read_again() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        append_subagent_lines(&subagents, "a1", 0..2);
        append_subagent_lines(&subagents, "b2", 0..1);

        let error =
            "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
        let failed = sweep(vec![error.to_string()], &main, &session_dir, &pending).await;
        assert_eq!(failed.len(), 1);
        let queued = |path: &Path| -> Vec<StreamEventRequest> {
            fs::read_to_string(path)
                .unwrap()
                .lines()
                .map(|j| serde_json::from_str(j).unwrap())
                .collect()
        };
        let first = queued(&pending);
        assert_eq!(first.len(), 2, "the failed batch and the one behind it");
        assert_one_file_per_request(&subagents, &first);
        assert_eq!(first[0].transcript_offset, failed[0].transcript_offset);
        assert_eq!(part_lines(&first[0]), part_lines(&failed[0]));
        assert!(first.iter().all(|r| r.transcript_offset == Some(0)));

        // The files are not read again: nothing is sent, nothing queued twice.
        for _ in 0..2 {
            assert!(sweep(vec![], &main, &session_dir, &pending)
                .await
                .is_empty());
        }
        assert_eq!(queued(&pending).len(), 2, "nothing was queued twice");
    }

    /// A hook reads one batch of a subagent's file and leaves the rest to
    /// the next; a final hook, which has no next, reads the file to its end
    /// and queues what it cannot send.
    #[tokio::test]
    async fn a_final_hook_reads_a_subagent_backlog_to_its_end() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        let file = subagents.join("agent-a1.jsonl");
        for n in 0..90 {
            let line = serde_json::json!({"agentId": "a1", "n": n, "pad": "x".repeat(100_000)});
            append_raw(&file, &format!("{line}\n"));
        }
        let len = fs::metadata(&file).unwrap().len() as i64;
        let offset = || -> i64 {
            fs::read_to_string(crate::subagents::offset_path(&session_dir, &file))
                .unwrap()
                .trim()
                .parse()
                .unwrap()
        };
        let queued_ns = || -> Vec<u64> {
            fs::read_to_string(&pending)
                .unwrap()
                .lines()
                .map(|j| serde_json::from_str::<StreamEventRequest>(j).unwrap())
                .flat_map(|r| part_lines(&r))
                .map(|l| l["n"].as_u64().unwrap())
                .collect()
        };

        assert!(sweep(vec![], &main, &session_dir, &pending)
            .await
            .is_empty());
        let after_one = offset();
        assert!(
            after_one >= MAX_BATCH_BYTES && after_one < len,
            "{after_one}"
        );

        let sent = sweep_waiting(vec![], &main, &session_dir, &pending, Some(Instant::now())).await;
        assert!(sent.is_empty());
        assert_eq!(offset(), len);
        assert_eq!(queued_ns(), (0..90).collect::<Vec<_>>(), "each line once");
    }

    /// Lines read from a file that could not be sent are queued whole, once,
    /// and count as dealt with: the read offset moves past them.
    #[tokio::test]
    async fn deliver_parts_queues_file_lines_and_counts_them() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let event = event_with_lines(big_lines(300, 5_000), 0);
        let parts = split_into_parts(event.clone());
        assert!(parts.len() >= 3);
        let unavailable = crate::test_helpers::http_json("503 Service Unavailable", "{}");
        let (base, _rx) = crate::test_helpers::spawn_seq(vec![ok_stream_response(), unavailable]);
        let client = crate::api_client::ApiClient::new(&base, Some("tok"));

        let delivered = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts.clone(),
            &pending_path,
            false,
            far_deadline(),
            Unsent::Queued,
            &mut false,
        )
        .await
        .unwrap();

        assert_eq!(
            delivered,
            Delivered {
                all: false,
                lines: 300
            }
        );
        let queued: Vec<StreamEventRequest> = drain_pending(&pending_path)
            .unwrap()
            .iter()
            .map(|j| serde_json::from_str(j).unwrap())
            .collect();
        assert_eq!(queued.len(), parts.len() - 1);
        for (q, part) in queued.iter().zip(&parts[1..]) {
            assert_eq!(q.transcript_offset, part.transcript_offset);
            assert_eq!(q.transcript_lines, part.transcript_lines);
        }
    }

    /// A full queue takes no more lines: they stay in the file, the count
    /// stops before them, and of the event only what cannot be read again is
    /// kept.
    #[tokio::test]
    async fn deliver_parts_leaves_lines_in_the_file_once_the_queue_is_full() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let event = event_with_lines(big_lines(300, 5_000), 0);
        let parts = split_into_parts(event.clone());
        assert!(parts.len() >= 3);
        // Room for the first part and the bare event, not for a second part.
        let first = serde_json::to_string(&parts[0]).unwrap().len() as u64;
        fs::write(&pending_path, "\n").unwrap();
        fs::OpenOptions::new()
            .write(true)
            .open(&pending_path)
            .unwrap()
            .set_len(crate::pending_queue::MAX_QUEUE_BYTES - first - 10_000)
            .unwrap();
        let before = fs::metadata(&pending_path).unwrap().len();
        let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));

        let delivered = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            parts.clone(),
            &pending_path,
            true,
            far_deadline(),
            Unsent::Queued,
            &mut false,
        )
        .await
        .unwrap();

        assert_eq!(
            delivered,
            Delivered {
                all: false,
                lines: part_lines(&parts[0]).len()
            }
        );
        let mut added = Vec::new();
        let mut file = fs::File::open(&pending_path).unwrap();
        file.seek(SeekFrom::Start(before)).unwrap();
        file.read_to_end(&mut added).unwrap();
        let queued: Vec<StreamEventRequest> = String::from_utf8(added)
            .unwrap()
            .lines()
            .map(|j| serde_json::from_str(j).unwrap())
            .collect();
        assert_eq!(
            queued.len(),
            2,
            "the first part, and the event without lines"
        );
        assert_eq!(queued[0].transcript_lines, parts[0].transcript_lines);
        assert_eq!(queued[1].event_uuid, event.event_uuid);
        assert_eq!(queued[1].tool_input, event.tool_input);
        assert_eq!(queued[1].transcript_lines, None);
    }

    /// `SessionEnd` lines stay in the file: nothing of them is queued and
    /// none counts, so the offset the catch-up sweep goes by does not move.
    #[tokio::test]
    async fn deliver_parts_can_leave_unsent_lines_in_the_file() {
        let dir = tempfile::tempdir().unwrap();
        let pending_path = dir.path().join("pending.jsonl");
        let lines_only = StreamEventRequest {
            event_type: StreamEventType::Transcript,
            ..event_with_lines(big_lines(3, 100), 0)
        };
        let client = crate::api_client::ApiClient::new("http://127.0.0.1:9", Some("tok"));

        let delivered = deliver_parts(
            &client,
            &repo_attr(&uuid::Uuid::new_v4().to_string()),
            AttributionForce::default(),
            split_into_parts(lines_only),
            &pending_path,
            false,
            far_deadline(),
            Unsent::StayInFile,
            &mut false,
        )
        .await
        .unwrap();

        assert_eq!(
            delivered,
            Delivered {
                all: false,
                lines: 0
            }
        );
        assert!(!pending_path.exists());
    }

    /// A read stops at the line that reaches the cap and tells where every
    /// line ends, so the offset can move to the end of any accepted prefix.
    #[test]
    fn a_batch_is_capped_and_knows_where_its_lines_end() {
        let dir = tempfile::tempdir().unwrap();
        let transcript = dir.path().join("t.jsonl");
        let offset_path = dir.path().join(".stream_offset");
        let line = |n: usize| format!("{}\n", serde_json::json!({"n": n, "pad": "x".repeat(90)}));
        let len = line(0).len() as i64;
        let body: String = (0..10).map(line).collect::<Vec<_>>().join("\n");
        // A blank line between records, as a reader must tolerate.
        fs::write(&transcript, &body).unwrap();

        let batch = read_transcript_batch(&transcript, &offset_path, 2 * len).unwrap();
        assert_eq!(batch.start, 0);
        assert_eq!(batch.lines.len(), 2, "two lines and the blank after each");
        assert_eq!(batch.ends, vec![len, 2 * len + 1]);
        assert_eq!(batch.end, 2 * len + 1);

        // No line dealt with: the offset stays. A prefix: its end. All: the
        // batch's, whether the server took them or the queue did.
        let none = Delivered {
            all: false,
            lines: 0,
        };
        let one = Delivered {
            all: false,
            lines: 1,
        };
        let all = Delivered {
            all: false,
            lines: 2,
        };
        assert_eq!(batch.next_offset(&none), None);
        assert_eq!(batch.next_offset(&one), Some(len));
        assert_eq!(batch.next_offset(&all), Some(batch.end));

        // Read on from a line's end: the next lines, nothing twice.
        fs::write(&offset_path, len.to_string()).unwrap();
        let rest = read_transcript_batch(&transcript, &offset_path, i64::MAX).unwrap();
        assert_eq!(rest.lines.len(), 9);
        assert_eq!(rest.lines[0]["n"], 1);
        assert_eq!(rest.end, body.len() as i64);
    }

    /// A tool's result is among the last lines written; a batch that stops
    /// short of them (a backlog) must not lose the event's error flag.
    #[test]
    fn a_tool_error_past_the_batch_is_still_found() {
        let dir = tempfile::tempdir().unwrap();
        let transcript = dir.path().join("t.jsonl");
        let result = |id: &str, is_error: bool| {
            serde_json::json!({"type": "user", "message": {"content": [
                {"type": "tool_result", "tool_use_id": id, "is_error": is_error}
            ]}})
            .to_string()
        };
        let backlog = serde_json::json!({"type": "assistant", "pad": "x".repeat(1000)}).to_string();
        let body = format!(
            "{backlog}\n{backlog}\n{}\n{}\n",
            result("toolu_ok", false),
            result("toolu_bad", true)
        );
        fs::write(&transcript, &body).unwrap();
        let after_backlog = 2 * (backlog.len() as i64 + 1);

        assert_eq!(
            tool_is_error_past(&transcript, after_backlog, "toolu_bad"),
            Some(true)
        );
        assert_eq!(
            tool_is_error_past(&transcript, after_backlog, "toolu_ok"),
            Some(false)
        );
        assert_eq!(
            tool_is_error_past(&transcript, after_backlog, "toolu_none"),
            None
        );
        // Nothing past the batch: nothing to look at.
        assert_eq!(
            tool_is_error_past(&transcript, body.len() as i64, "toolu_bad"),
            None
        );
        assert_eq!(
            tool_is_error_past(&dir.path().join("absent"), 0, "toolu_bad"),
            None
        );
    }

    #[test]
    fn a_413_is_told_from_other_failures() {
        assert!(too_large("Stream failed (413 Payload Too Large): "));
        assert!(!too_large("Stream failed (503 Service Unavailable): {}"));
        assert!(!too_large("Stream failed (404 Not Found): no repo 4130"));
    }

    #[test]
    fn the_read_offset_only_moves_forward() {
        let dir = tempfile::tempdir().unwrap();
        let offset_path = dir.path().join(".stream_offset");
        let read = || fs::read_to_string(&offset_path).unwrap();

        advance_offset(&offset_path, 100).unwrap();
        assert_eq!(read(), "100");
        advance_offset(&offset_path, 40).unwrap();
        assert_eq!(
            read(),
            "100",
            "a hook that got less through does not undo it"
        );
        advance_offset(&offset_path, 250).unwrap();
        assert_eq!(read(), "250");
        // An unreadable offset is replaced rather than kept for good.
        fs::write(&offset_path, "garbage").unwrap();
        advance_offset(&offset_path, 7).unwrap();
        assert_eq!(read(), "7");
    }

    /// A file another hook of the session is sending is left to it: not read,
    /// not sent, its offset untouched. The other files still go.
    #[tokio::test]
    async fn a_subagent_file_another_hook_is_sending_is_skipped() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        append_subagent_lines(&subagents, "a1", 0..2);
        append_subagent_lines(&subagents, "b2", 0..1);
        let a1_offset =
            crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
        let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();

        let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
        assert_eq!(reqs.len(), 1);
        assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "b2");
        assert!(!a1_offset.exists());

        drop(held);
        let reqs = sweep(vec![ok_stream_response()], &main, &session_dir, &pending).await;
        assert_eq!(reqs.len(), 1);
        assert_eq!(part_lines(&reqs[0]).len(), 2);
        assert_eq!(agent_of(&part_lines(&reqs[0])[0]), "a1");
    }

    /// A final hook does not skip a busy file: it waits for the holder, then
    /// sends what the holder left, here every line.
    #[tokio::test]
    async fn a_final_hook_waits_for_a_busy_subagent_file() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        append_subagent_lines(&subagents, "a1", 0..2);
        let a1_offset =
            crate::subagents::offset_path(&session_dir, &subagents.join("agent-a1.jsonl"));
        let held = crate::subagents::try_lock(&a1_offset).unwrap().unwrap();
        let release = thread::spawn(move || {
            thread::sleep(Duration::from_millis(300));
            drop(held);
        });

        let reqs = sweep_waiting(
            vec![ok_stream_response()],
            &main,
            &session_dir,
            &pending,
            Some(Instant::now() + Duration::from_secs(10)),
        )
        .await;
        release.join().unwrap();
        assert_eq!(reqs.len(), 1);
        assert_eq!(part_lines(&reqs[0]).len(), 2);
    }

    /// A subagent batch over the request cap is split like any other, within
    /// its own file: every part holds that file's lines only and every line
    /// keeps the chunk_index it would have had unsplit.
    #[tokio::test]
    async fn a_large_subagent_batch_is_split_within_its_file() {
        let dir = tempfile::tempdir().unwrap();
        let (main, subagents, session_dir) = claude_session(dir.path());
        let pending = session_dir.join("pending.jsonl");
        let big = subagents.join("agent-a1.jsonl");
        for n in 0..300 {
            let line = serde_json::json!({"agentId": "a1", "n": n, "text": "y".repeat(5_000)});
            append_raw(&big, &format!("{line}\n"));
        }
        append_subagent_lines(&subagents, "b2", 0..1);

        let scratch = dir.path().join("scratch-offset");
        let (lines, start, _) = crate::subagents::read_new_lines(&big, &scratch).unwrap();
        let unsplit = StreamEventRequest {
            transcript_lines: Some(lines.clone()),
            transcript_offset: Some(start),
            ..transcript_template(&sample_stream_event_request())
        };
        let a1_parts = split_into_parts(unsplit).len();
        assert!(a1_parts > 1, "the batch must exceed the cap");

        let reqs = sweep(
            vec![ok_stream_response(); a1_parts + 1],
            &main,
            &session_dir,
            &pending,
        )
        .await;
        assert!(!pending.exists());
        let (a1, b2) = reqs.split_at(a1_parts);
        assert!(a1.iter().flat_map(part_lines).all(|l| agent_of(&l) == "a1"));
        assert_eq!(
            chunk_indexes(a1),
            lines
                .into_iter()
                .enumerate()
                .map(|(i, l)| (start + i as i64, l))
                .collect::<Vec<_>>()
        );
        assert_eq!(b2.len(), 1);
        assert_eq!(agent_of(&part_lines(&b2[0])[0]), "b2");
        assert_eq!(b2[0].transcript_offset, Some(0));
    }
}