tracevault-cli 0.28.2

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
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,
};

/// 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> {
    // 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((vec![], 0, 0));
    }

    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 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);
        }
    }

    Ok((lines, offset, bytes_read))
}

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 `.tracevault/`, 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 }),
    }
}

/// 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())
}

/// 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**
/// `.tracevault/` directory from any worktree — including sibling linked
/// worktrees where the primary `.tracevault/` 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 `.tracevault/`) and `session_dir`
/// under `<resolved.root>/.tracevault/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 = resolved
        .root
        .join(".tracevault")
        .join("sessions")
        .join(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)
}

/// Resolve the capture-time project from LOCAL, UUID-bearing bindings only — no
/// network (the hook fires per event in a short-lived process). Precedence:
/// subagent worktree override -> session `active_project` -> user-level default.
/// Repo config `default_project` (a name) is intentionally excluded: honoring it
/// would need a per-event `list_projects` call. `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.
pub(crate) fn capture_project(
    session: &crate::session_state::SessionState,
    worktree_path: Option<&str>,
) -> Option<uuid::Uuid> {
    use crate::resolution::{effective_project, ProjectResolveInputs};
    let local = effective_project(&ProjectResolveInputs {
        project_flag: None,
        session,
        worktree_path,
        config_default: None,
    })
    .map(|(b, _)| b)
    .or_else(crate::user_project_default::load)?;
    local.project_id.parse::<uuid::Uuid>().ok()
}

/// The one-line warning printed when a repo-less event is dropped as
/// permanently undeliverable. Pure, so the wording is asserted directly.
fn undeliverable_warning(pid: uuid::Uuid) -> String {
    format!(
        "tracevault: warning: project {pid} does not resolve (400/404/409); this session has no \
         repo binding, so there is nothing to attribute these events to and they are being \
         DROPPED rather than queued. Run `tracevault project switch <name>` to bind a project \
         that exists."
    )
}

/// 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 fallback warning can name a
/// cause that is actually possible instead of assuming one.
#[derive(Debug, PartialEq, Eq)]
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 warning printed when a project-scoped send falls back to
/// repo deduction. Pure, so the wording is asserted directly rather than by
/// capturing stderr.
fn fallback_warning(pid: uuid::Uuid, kind: &ClientErrorKind) -> String {
    match kind {
        // Since Keycloak, a 403 has a SECOND and now more common cause: the
        // account has no `tracing` realm role 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 is not
        // distinguishable from here (see `ClientErrorKind`), so name both.
        ClientErrorKind::Forbidden => format!(
            "tracevault: warning: 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 \
             missing TracePush) — run `tracevault project switch <name>` — or this account lacks \
             the `tracing` Keycloak realm role entirely, which an administrator must grant. \
             Attributing via repo deduction instead."
        ),
        ClientErrorKind::Scoping => format!(
            "tracevault: warning: active project {pid} does not apply to this repo (not a member, \
             or missing permission); attributing via repo deduction instead. Run `tracevault \
             project switch <name>` to update."
        ),
    }
}

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 repo-scoped fallback uses
    // the SAME token — it would also 401, so falling back just wastes a
    // request before the error propagates to buffer/retry. 403 stays in: it can
    // mean the token is valid but lacks TracePush on the bound project, and the
    // repo-scoped fallback (a different authorization check) can help.
    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. Having no fallback endpoint, it decides
/// instead between buffering and dropping: a `Scoping` 4xx (the project does
/// not resolve) can never succeed on retry — the offline queue is keyed by
/// that same project id — so it warns and returns `Ok(None)`, while a 403 or
/// any transient error propagates to be buffered. See the arm itself for why
/// the two differ.
///
/// `Ok(None)` therefore means "deliberately dropped, do not queue": callers
/// must treat it like a success for offset/queue purposes, not like an error.
///
/// When the attribution carries BOTH a repo and a project and the
/// project-scoped send fails with a
/// deterministic client error (the bound project doesn't apply to this repo:
/// not a member, or the caller lacks `TracePush` on it, or — after a prior
/// fallback — the repo-scoped 409 multi-project refusal), this falls back to
/// the repo-scoped endpoint ONCE and lets the server deduce the repo's
/// project, warning so the miss is visible. A transient error (5xx,
/// network/transport, timeout) is NOT retried here — it propagates so the
/// caller's existing buffer/retry logic runs unchanged.
///
/// `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`, not on a fallback that itself
/// returns `Ok` — so a stale binding whose repo-scoped fallback keeps
/// succeeding would otherwise print the warning once per buffered event.
/// Gating on `*warned` caps it at one warning per invocation while leaving the
/// fallback behavior itself unchanged. The repo-less drop warning shares the
/// flag for the same reason: draining a queue of undeliverable events would
/// otherwise print one line per buffered event.
async fn send_stream_event(
    client: &crate::api_client::ApiClient,
    attribution: &Attribution,
    req: &StreamEventRequest,
    warned: &mut bool,
) -> Result<Option<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, so the
        // only choice is buffer-for-retry vs. drop, and that turns on whether
        // a retry could EVER succeed.
        //
        // `Scoping` (400/404/409) means the project itself does not resolve.
        // The offline queue is keyed by that same project id
        // (`pending-project-<uuid>.jsonl`), so re-binding to a project that
        // does exist writes to a DIFFERENT file and these events are never
        // retried under the corrected binding — they would accumulate forever,
        // one per tool call, each hook fire re-reading and re-appending the
        // whole queue. Warn and drop instead: undeliverable is undeliverable,
        // and a growing queue only hides it.
        //
        // `Forbidden` (403) is deliberately NOT dropped. It can mean the
        // account lacks the realm role entirely, which an administrator can
        // grant — after which the buffered events do deliver. Same for any
        // transient error. Both propagate so the caller queues them.
        Attribution::ProjectOnly { project_id } => {
            let attempt = client
                .stream_event_for_project(*project_id, None, req)
                .await;
            return match attempt {
                Ok(r) => Ok(Some(r)),
                Err(e) => match deterministic_client_error_kind(e.as_ref()) {
                    Some(ClientErrorKind::Scoping) => {
                        if !*warned {
                            eprintln!("{}", undeliverable_warning(*project_id));
                            *warned = true;
                        }
                        Ok(None)
                    }
                    _ => Err(e),
                },
            };
        }
        Attribution::Repo { repo_id, project } => (repo_id.as_str(), *project),
    };
    match capture_pid {
        None => client.stream_event(repo_id, req).await.map(Some),
        Some(pid) => {
            let attempt = client
                .stream_event_for_project(pid, Some(repo_id), req)
                .await;
            let kind = match &attempt {
                Ok(_) => None,
                Err(e) => deterministic_client_error_kind(e.as_ref()),
            };
            match (attempt, kind) {
                (Ok(r), _) => Ok(Some(r)),
                (Err(_), Some(kind)) => {
                    if !*warned {
                        // Since Keycloak, a 403 has a SECOND and now more common
                        // cause: the account has no `tracing` realm role 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!("{}", fallback_warning(pid, &kind));
                        *warned = true;
                    }
                    // Repo-scoped fallback: the server deduces the project itself.
                    client.stream_event(repo_id, req).await.map(Some)
                }
                // 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)
}

/// 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. Returns `Some(true|false)` for the first `toolResult`
/// record 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 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;
}

pub async fn run_stream(
    event_type: &str,
    agent: crate::agent::Agent,
) -> Result<(), Box<dyn std::error::Error>> {
    // 1. Read HookEvent from stdin
    let mut input = String::new();
    io::stdin().read_to_string(&mut input)?;
    let mut 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
    // `.tracevault/` 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 `.tracevault/`) 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.
    let hook_cwd = Path::new(&hook_event.cwd);
    let (resolved, session_dir) = resolve_session_paths(hook_cwd, &hook_event.session_id);
    if resolved.source == crate::paths::ProjectRootSource::Fallback {
        // Neither git nor an ancestor `.tracevault/` resolved a project root, so
        // we are about to create a fresh `.tracevault/` at the hook's working
        // directory — which is how stray per-subdirectory `.tracevault/` dirs
        // appear. Surface it (best-effort; stderr never blocks the hook).
        eprintln!(
            "tracevault: warning: could not resolve a git project root from {}; \
             creating .tracevault/ 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 `.tracevault/` 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.
    let _ = crate::config::TracevaultConfig::ensure_gitignore(&project_root.join(".tracevault"));

    // 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);

    // 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).
    let (transcript_lines, start_offset, new_offset) =
        read_new_transcript_lines(transcript_path, &offset_path)?;

    // 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 = match event_type {
        "notification" => StreamEventType::SessionStart,
        "stop" => StreamEventType::SessionEnd,
        _ => StreamEventType::ToolUse,
    };

    // 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))
        .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: if transcript_lines.is_empty() {
            None
        } else {
            Some(transcript_lines)
        },
        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,
    };

    stamp_agent(&mut req, agent);

    req.truncate_large_fields();

    // 6. Resolve credentials
    let (server_url, credential) = crate::credentials::resolve_credentials(&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 .tracevault/config.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 binding = resolve_stream_binding(&session, &worktree_top, bound, user_default);
    // Graceful no-op, exactly like the hook's normal success path. Do NOT
    // error: a failing hook would block the tool.
    let no_op_allow = || -> Result<(), Box<dyn std::error::Error>> {
        let response = HookResponse::allow();
        println!("{}", serde_json::to_string(&response)?);
        Ok(())
    };
    // 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.
    let capture_pid = capture_project(&session, Some(worktree_top.as_str()));

    // 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.)
    let Some(attribution) = attribution_for(binding.as_ref(), capture_pid) else {
        no_op_allow()?;
        return Ok(());
    };

    // 8. Create ApiClient
    let server_url = server_url.ok_or("server_url not configured")?;
    let client = crate::api_client::ApiClient::with_credential(&server_url, credential);

    // 9. Try drain pending queue and send
    let pending_path = pending_path_for(&session_dir, &attribution);
    let pending_events = drain_pending(&pending_path)?;

    let mut send_failed = false;
    // Spans the whole invocation (pending-flush loop + live send below) so a
    // stale binding whose repo-scoped fallback keeps succeeding warns at most
    // once, not once per buffered event.
    let mut warned = false;

    // Send pending events first
    for pending_json in &pending_events {
        if let Ok(pending_req) = serde_json::from_str::<StreamEventRequest>(pending_json) {
            if send_stream_event(&client, &attribution, &pending_req, &mut warned)
                .await
                .is_err()
            {
                // Re-queue all remaining pending events
                for evt in &pending_events {
                    append_pending(&pending_path, evt)?;
                }
                send_failed = true;
                break;
            }
        }
    }

    // Send current event
    let req_json = serde_json::to_string(&req)?;
    // The inline (OpenCode) path CONSUMES its records from the hook event — they
    // are not re-readable like a transcript file — so its `.stream_offset` record
    // counter must advance whenever the event is accepted for delivery, INCLUDING
    // when it is queued after a failure. Otherwise the next inline event reuses
    // these chunk_indexes and the server drops the overlap via ON CONFLICT. The
    // queued request already carries this event's `transcript_offset`, so the
    // records keep their indices on drain. (File-based agents must NOT advance on
    // failure: their next read re-covers these lines cumulatively/idempotently.)
    if send_failed {
        append_pending(&pending_path, &req_json)?;
        if is_inline {
            fs::write(&offset_path, new_offset.to_string())?;
        }
    } else {
        match send_stream_event(&client, &attribution, &req, &mut warned).await {
            Ok(_) => {
                // 10. On success update .stream_offset
                fs::write(&offset_path, new_offset.to_string())?;
            }
            Err(_) => {
                // 11. On failure append to pending.jsonl (advance the inline
                // record counter regardless — see the note above).
                append_pending(&pending_path, &req_json)?;
                if is_inline {
                    fs::write(&offset_path, new_offset.to_string())?;
                }
            }
        }
    }

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

    Ok(())
}

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

    // ── 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(".tracevault").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(".tracevault").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 `.tracevault/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>/.tracevault/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 .tracevault/ in the primary root to match a real init.
        std::fs::create_dir_all(repo.join(".tracevault")).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(".tracevault")
                .join("sessions")
                .join("sess-primary-123"),
            "primary checkout: session_dir must be <repo>/.tracevault/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 .tracevault/ ONLY in the primary repo — not in the worktree.
        std::fs::create_dir_all(repo.join(".tracevault")).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 .tracevault/, 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(".tracevault")
                    .join("sessions")
                    .join("sess-sibling-456")
            ),
            "session_dir must end with .tracevault/sessions/<session_id>"
        );
    }

    /// Non-git directory with no `.tracevault/` 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 .tracevault/ 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(".tracevault")
                .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(".tracevault")
            .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"
        );
    }

    // ── 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,
        };
        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 ──────────────────────────

    #[test]
    fn capture_project_precedence_local_only() {
        use crate::session_state::{ProjectBinding, SessionState};
        let pb = |id: &str| ProjectBinding {
            project_id: id.into(),
            project_name: "n".into(),
            updated_at: "".into(),
        };
        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")), 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")), Some(u(1)));
        // no worktree match -> session active
        assert_eq!(capture_project(&s, Some("/other")), Some(u(2)));
        // empty session -> None (user-default file is not present in this unit test env)
        assert_eq!(capture_project(&SessionState::default(), 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);
    }

    // ── 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);

    /// Spawn a one-shot server that returns `response` (a full HTTP response)
    /// to the first request. Captures the HTTP request line (method + path +
    /// query) over the returned channel before writing the response. 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) {
                let mut reader = BufReader::new(stream);
                let mut request_line = String::new();
                let _ = reader.read_line(&mut request_line);
                let _ = tx.send(request_line);
                let mut stream = reader.into_inner();
                let _ = stream.write_all(response.as_bytes());
                let _ = stream.flush();
            }
        });
        (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,
        }
    }

    /// 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());

        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(),
            }),
            ..Default::default()
        };
        let capture_pid = capture_project(&session, None);
        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,
            },
            &req,
            &mut warned,
        )
        .await
        .expect("send_stream_event must succeed");
        assert_eq!(
            got.expect("a successful send returns a response").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}"
        );
    }

    /// 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.
        _guard.set("XDG_CONFIG_HOME", tmp.path());

        let capture_pid = capture_project(&SessionState::default(), None);
        assert_eq!(capture_pid, 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: capture_pid,
            },
            &req,
            &mut warned,
        )
        .await
        .expect("send_stream_event must succeed");
        assert_eq!(
            got.expect("a successful send returns a response").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: deterministic-client-error fallback + 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 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;
                };
                let mut reader = BufReader::new(stream);
                let mut request_line = String::new();
                let _ = reader.read_line(&mut request_line);
                let _ = tx.send(request_line);
                let mut stream = reader.into_inner();
                let _ = stream.write_all(response.as_bytes());
                let _ = stream.flush();
            }
            // `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 fall back to the repo-scoped endpoint —
    /// which then succeeds — rather than being buffered/retried forever. Both
    /// endpoints must be hit, project first, then repo.
    #[tokio::test]
    async fn send_stream_event_falls_back_to_repo_scoped_on_deterministic_400() {
        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 got = send_stream_event(
            &client,
            &Attribution::Repo {
                repo_id: "11111111-1111-1111-1111-111111111111".into(),
                project: Some(pid),
            },
            &req,
            &mut warned,
        )
        .await
        .expect("a deterministic 400 must fall back to repo-scoped and succeed");
        assert_eq!(
            got.expect("a successful send returns a response").status,
            "accepted"
        );

        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}"
        );

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

    /// 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".
    #[tokio::test]
    async fn send_stream_event_project_only_omits_repo_id() {
        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 },
            &req,
            &mut warned,
        )
        .await
        .expect("a repo-less project send must succeed");
        assert_eq!(
            got.expect("a successful send returns a response").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!(
            !warned,
            "a repo-less send has no fallback and must not warn about one"
        );
    }

    /// A `Scoping` 4xx is permanently undeliverable for a repo-less session:
    /// the queue is keyed by the very project id the server says does not
    /// resolve, so a corrected binding writes to a different file and these
    /// events would never be retried — they would just accumulate, one per
    /// tool call. They must be DROPPED (`Ok(None)`), loudly, and must not
    /// trigger a second, impossible request.
    #[tokio::test]
    async fn send_stream_event_project_only_drops_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 got = send_stream_event(
            &client,
            &Attribution::ProjectOnly { project_id: pid },
            &req,
            &mut warned,
        )
        .await
        .expect("an undeliverable repo-less event is dropped, not surfaced as Err");
        assert!(
            got.is_none(),
            "Ok(None) signals the deliberate drop; Some(_) would read as a real send"
        );
        assert!(
            warned,
            "dropping data silently is the failure mode to avoid"
        );

        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}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "a repo-less send must make exactly one request — no fallback exists"
        );
    }

    /// A 403 is NOT dropped. It can mean the account lacks the realm role,
    /// 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),
            },
            &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),
            },
            &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 `tracing` realm role
    /// 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 warning must not tell a user whose account has no `tracing` role
    /// to switch projects, which cannot possibly help. It names both causes; the
    /// scoping statuses keep the precise project wording.
    #[test]
    fn the_403_warning_names_the_realm_role_as_well_as_the_project() {
        let pid = uuid::Uuid::from_u128(7);

        let forbidden = fallback_warning(pid, &ClientErrorKind::Forbidden);
        assert!(
            forbidden.contains("`tracing` Keycloak realm role"),
            "must offer the missing-role explanation: {forbidden}"
        );
        assert!(
            forbidden.contains("project switch"),
            "must still offer the project explanation: {forbidden}"
        );
        assert!(
            forbidden.contains("Either"),
            "must present them as alternatives, not assert one: {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 = fallback_warning(pid, &ClientErrorKind::Scoping);
        assert!(scoping.contains("project switch"), "{scoping}");
        assert!(
            !scoping.contains("realm role"),
            "the scoping case must not mention the realm role: {scoping}"
        );
    }
}