tracevault-cli 0.29.8

CLI tool for Visdom Trace - AI code tracing and attribution
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
use crate::api_client::{ApiClient, CheckPoliciesRequest, SessionCheckData};
use crate::credentials::resolve_credentials;
use crate::program::CLI;
use crate::resolution::{resolve_repo_by_name, ResolveRepoByNameError};
use std::collections::HashSet;
use std::fs;
use std::path::Path;
use std::process::Command;

fn git_head_sha(project_root: &Path) -> Option<String> {
    let out = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(project_root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if sha.is_empty() {
        None
    } else {
        Some(sha)
    }
}

/// One ref being pushed, as described by git's pre-push stdin protocol.
#[derive(Debug, PartialEq)]
pub(crate) struct PushRef {
    pub local_sha: String,
    pub remote_sha: String,
}

fn is_zero_sha(sha: &str) -> bool {
    !sha.is_empty() && sha.chars().all(|c| c == '0')
}

/// Parse git's pre-push stdin. Malformed lines are skipped rather than
/// failing the push: this is an enrichment, and a parse error must never be
/// the reason a developer cannot push. Branch deletions (all-zero LOCAL sha)
/// are dropped — no content is being pushed for them.
pub(crate) fn parse_push_refs(stdin: &str) -> Vec<PushRef> {
    stdin
        .lines()
        .filter_map(|line| {
            let mut parts = line.split_whitespace();
            let _local_ref = parts.next()?;
            let local_sha = parts.next()?;
            let _remote_ref = parts.next()?;
            let remote_sha = parts.next()?;
            if is_zero_sha(local_sha) {
                return None;
            }
            Some(PushRef {
                local_sha: local_sha.to_string(),
                remote_sha: remote_sha.to_string(),
            })
        })
        .collect()
}

/// Files changed by the refs being pushed, repo-relative as git emits them.
/// Over-inclusion is the safe direction: a larger set only means less pruning
/// of AI-touched paths, never a missed violation.
fn changed_files_for_refs(project_root: &Path, refs: &[PushRef]) -> Vec<String> {
    let mut seen = HashSet::new();
    let mut out = Vec::new();
    for r in refs {
        // A new branch has no remote sha to diff from. `git diff --name-only
        // <sha>` (one argument) diffs the working tree against that commit,
        // which is wrong here, so name the empty tree explicitly.
        let base = if is_zero_sha(&r.remote_sha) {
            match git_empty_tree_sha(project_root) {
                Some(t) => t,
                None => continue,
            }
        } else {
            r.remote_sha.clone()
        };
        let out_bytes = Command::new("git")
            .args([
                "diff",
                "--name-only",
                // `-z`: NUL-delimit output and disable git's default path
                // quoting (`core.quotePath`), which otherwise renders any
                // path outside plain ASCII — accents, CJK, a literal space
                // in some locales — as an octal-escaped, double-quoted
                // string that can never match the hook-recorded path.
                "-z",
                // Rename detection is on by default and reports only the
                // destination path, hiding the source. A larger
                // `changed_paths` only ever means less pruning, never a
                // missed violation, so always disable it here.
                "--no-renames",
                &format!("{base}..{}", r.local_sha),
            ])
            .current_dir(project_root)
            .output();
        let Ok(o) = out_bytes else { continue };
        if !o.status.success() {
            continue;
        }
        for p in split_nul_delimited_paths(&o.stdout) {
            if seen.insert(p.clone()) {
                out.push(p);
            }
        }
    }
    out
}

/// Split `git diff -z` output into paths.
///
/// `-z` NUL-*terminates* each path rather than NUL-*separating* them, so a
/// naive split always yields one trailing empty element — filtered out here,
/// along with any other empty segment. Paths are NOT trimmed: a NUL-split
/// path needs no trimming, and trimming could corrupt a path with legal
/// leading/trailing whitespace. `String::from_utf8_lossy` is used rather than
/// a strict UTF-8 parse so a non-UTF-8 path degrades gracefully instead of
/// dropping the whole diff.
fn split_nul_delimited_paths(bytes: &[u8]) -> Vec<String> {
    String::from_utf8_lossy(bytes)
        .split('\0')
        .filter(|p| !p.is_empty())
        .map(|p| p.to_string())
        .collect()
}

/// The well-known empty tree object, resolved via git so it is correct for
/// both sha1 and sha256 repositories rather than hardcoded.
fn git_empty_tree_sha(project_root: &Path) -> Option<String> {
    let out = Command::new("git")
        .args(["hash-object", "-t", "tree", "/dev/null"])
        .current_dir(project_root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
    if s.is_empty() {
        None
    } else {
        Some(s)
    }
}

/// How long to wait for git's pre-push stdin to close before falling back to
/// `@{upstream}..HEAD`. A pre-push hook writes its ref lines and closes the
/// pipe immediately, so this bound is never hit in normal operation — it
/// exists only to protect against a stalled non-TTY pipe (see
/// `resolve_changed_paths` and `read_stdin_with_timeout`).
const STDIN_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);

/// Run `f` on a detached background thread and wait up to `timeout` for it
/// to produce a value, returning `None` on timeout.
///
/// `f` is not cancelled on timeout: a blocked read has no way to be aborted
/// from the outside, so the thread is deliberately leaked and we let the
/// process exit around it rather than wait for it to unblock.
///
/// Generic over the read so the timeout mechanism can be exercised in tests
/// without touching the process's real, global stdin — see
/// `read_stdin_with_timeout`, which is the thin, untested wrapper that calls
/// this with `std::io::stdin().read_to_string(..)`.
fn read_with_timeout<F>(f: F, timeout: std::time::Duration) -> Option<String>
where
    F: FnOnce() -> Option<String> + Send + 'static,
{
    let (tx, rx) = std::sync::mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(f());
    });
    rx.recv_timeout(timeout).ok().flatten()
}

/// Read all of stdin, giving up after `timeout`.
///
/// `read_to_string` blocks until EOF, and a non-TTY pipe whose writer never
/// closes never sends one. A git pre-push hook always closes the pipe, so
/// this bound is not hit in normal operation — but `tracevault check` sits in
/// the push path, and hanging there with no output is far worse than losing
/// the push-diff optimisation.
fn read_stdin_with_timeout(timeout: std::time::Duration) -> Option<String> {
    use std::io::Read;
    read_with_timeout(
        || {
            let mut buf = String::new();
            std::io::stdin().read_to_string(&mut buf).ok().map(|_| buf)
        },
        timeout,
    )
}

/// Files in the push being attempted, or `None` if it cannot be determined.
///
/// Order: git's pre-push stdin (authoritative — correct for new branches,
/// force pushes, and multi-ref pushes), then `@{upstream}..HEAD`, then give
/// up. `None` is safe: the server falls back to evaluating the raw AI-touched
/// set, which over-blocks rather than under-blocks. Once stdin has yielded
/// usable refs, its diff is final — even if empty — and the function returns
/// without trying `@{upstream}..HEAD`; that fallback is only for when stdin
/// gave no usable refs at all, never a second opinion on an authoritative
/// empty diff (see the comment inline below).
fn resolve_changed_paths(project_root: &Path) -> Option<Vec<String>> {
    use std::io::IsTerminal;

    // `tracevault check` is also run by hand. Reading stdin unconditionally
    // would block waiting for EOF, hanging the terminal. That guard alone is
    // incomplete, though: a non-TTY pipe whose writer never closes (e.g. a
    // stalled hook, a misbehaving wrapper script) also never sends EOF, so
    // the read is additionally bounded in time.
    if !std::io::stdin().is_terminal() {
        if let Some(buf) = read_stdin_with_timeout(STDIN_READ_TIMEOUT) {
            let refs = parse_push_refs(&buf);
            if !refs.is_empty() {
                // Authoritative: stdin gave us real push refs, so whatever
                // `changed_files_for_refs` returns for them — including
                // nothing — IS the answer for this push. Do not fall through
                // to the `@{upstream}..HEAD` fallback below: that is a
                // DIFFERENT range that can contain files not in this push at
                // all, and sending paths from the wrong range corrupts the
                // server's intersection against AI-touched paths. An
                // authoritative empty diff must resolve to `None`, not to
                // whatever the fallback range happens to contain.
                let files = changed_files_for_refs(project_root, &refs);
                return if files.is_empty() { None } else { Some(files) };
            }
        }
    }

    // Only reached when stdin gave us no usable refs at all (no stdin, a
    // terminal, a timeout, or every line malformed) — never as a fallback
    // from an authoritative-but-empty diff above.
    let out = Command::new("git")
        .args([
            "diff",
            "--name-only",
            "-z",
            "--no-renames",
            "@{upstream}..HEAD",
        ])
        .current_dir(project_root)
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let files = split_nul_delimited_paths(&out.stdout);
    if files.is_empty() {
        None
    } else {
        Some(files)
    }
}

fn collect_session_data(session_dir: &Path) -> Option<SessionCheckData> {
    let session_id = session_dir.file_name()?.to_string_lossy().to_string();

    // Read events.jsonl for files_modified
    let events_path = session_dir.join("events.jsonl");
    let mut files_modified = Vec::new();
    let mut files_seen = HashSet::new();

    if events_path.exists() {
        if let Ok(content) = fs::read_to_string(&events_path) {
            for line in content.lines() {
                let event: serde_json::Value = match serde_json::from_str(line) {
                    Ok(v) => v,
                    Err(_) => continue,
                };
                if let Some(path) = event
                    .get("tool_input")
                    .and_then(|v| v.get("file_path"))
                    .and_then(|v| v.as_str())
                {
                    if files_seen.insert(path.to_string()) {
                        files_modified.push(path.to_string());
                    }
                }
            }
        }
    }

    // Read transcript for tool_calls
    let meta_path = session_dir.join("metadata.json");
    let metadata: Option<serde_json::Value> = meta_path
        .exists()
        .then(|| fs::read_to_string(&meta_path).ok())
        .flatten()
        .and_then(|c| serde_json::from_str(&c).ok());

    let transcript_path = metadata
        .as_ref()
        .and_then(|m| m.get("transcript_path"))
        .and_then(|v| v.as_str())
        .map(|s| s.to_string());

    let tool_calls_map = transcript_path
        .as_deref()
        .map(|p| crate::transcript::count_tool_calls(Path::new(p)))
        .unwrap_or_default();
    let total_tool_calls: i32 = tool_calls_map.values().sum();

    let tool_calls = if tool_calls_map.is_empty() {
        None
    } else {
        serde_json::to_value(&tool_calls_map).ok()
    };

    Some(SessionCheckData {
        session_id,
        tool_calls,
        files_modified: if files_modified.is_empty() {
            None
        } else {
            Some(files_modified)
        },
        total_tool_calls: if total_tool_calls > 0 {
            Some(total_tool_calls)
        } else {
            None
        },
    })
}

/// Select the session directories that belong to the current worktree.
/// Keeps sessions whose `origin` marker == `worktree_top` OR that have no
/// marker (legacy/unmarked — kept conservatively). Marked sessions from other
/// worktrees are excluded.
///
/// Safety rail: if filtering would drop EVERY session while sessions exist,
/// return all of them with `fell_back = true` — never under-enforce by sending
/// zero sessions for a push that has unpushed work.
///
/// `pub` so the integration test in Task 7 can drive it.
pub fn select_worktree_sessions(
    session_dirs: Vec<std::path::PathBuf>,
    worktree_top: &str,
) -> (Vec<std::path::PathBuf>, bool) {
    let belongs = |dir: &std::path::Path| -> bool {
        match fs::read_to_string(dir.join("origin")) {
            // Marked: keep only if mine — the latest event ran here, or an
            // anchored session lists this worktree as one it ran in (VIS-1257).
            Ok(s) => s.trim() == worktree_top || crate::session_state::ran_in(dir, worktree_top),
            // Only a genuinely-absent marker counts as unmarked/legacy (keep).
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => true,
            // Marker present but unreadable (permissions/IO): we can't prove it's
            // ours, so exclude it rather than risk cross-worktree interference.
            // The safety rail below still prevents under-enforcement if this
            // drops everything.
            Err(_) => false,
        }
    };
    let filtered: Vec<_> = session_dirs
        .iter()
        .filter(|d| belongs(d))
        .cloned()
        .collect();
    if filtered.is_empty() && !session_dirs.is_empty() {
        (session_dirs, true)
    } else {
        (filtered, false)
    }
}

/// [`select_worktree_sessions`] over the local dirs, plus the `external` ones
/// (already known to belong to this worktree). The fall-back to every local
/// session applies only when neither matched: an external session is a match.
fn select_with_external(
    local: Vec<std::path::PathBuf>,
    external: Vec<std::path::PathBuf>,
    worktree_top: &str,
) -> Vec<std::path::PathBuf> {
    let (mut selected, fell_back) = select_worktree_sessions(local, worktree_top);
    if fell_back {
        if external.is_empty() {
            eprintln!(
                "Warning: no unpushed session matched this worktree by origin marker — \
                 checking all unpushed sessions to avoid skipping policy enforcement."
            );
        } else {
            selected.clear();
        }
    }
    selected.extend(external);
    selected
}

/// Add a session dir that lives outside `sessions_dir` to the sessions a
/// push is checked against, unless it is gone, pushed, or already there.
///
/// A session keeps its dir in the `.visdom/` it STARTED in (VIS-1257), so
/// one started in an umbrella directory that then works in this checkout has
/// no dir here. A dir inside `sessions_dir` was already considered by the
/// worktree selection, and its verdict stands.
fn add_external_session(
    selected: &mut Vec<std::path::PathBuf>,
    sessions_dir: &Path,
    dir: std::path::PathBuf,
) {
    let local = dir
        .parent()
        .is_some_and(|parent| crate::session_state::is_local_sessions_dir(parent, sessions_dir));
    if local || !dir.is_dir() || dir.join(".pushed").exists() {
        return;
    }
    if !selected.contains(&dir) {
        selected.push(dir);
    }
}

/// The server repo a push is checked under.
#[derive(Debug, Clone, PartialEq, Eq)]
struct PushedRepo {
    id: uuid::Uuid,
    /// The codebase it belongs to, when resolved through the origin remote.
    remote_id: Option<uuid::Uuid>,
}

/// Resolve the repo being pushed — the policy authority for this push.
///
/// First through the checkout's origin remote, exactly as
/// `tracevault repo switch <path>` binds a session (VIS-601): a session bound
/// to this checkout then streams to the very repo it is checked under, so the
/// server finds its verification window and tool stats. Then, for a checkout
/// whose remote the server does not know (or that has none), by the primary
/// checkout's directory name — the only resolution `check` had before.
///
/// Never the sessions' own bindings: a `repo switch` to another repo, or a
/// machine-wide user default, must not decide which repo's policies a push
/// to THIS checkout is held to.
async fn resolve_pushed_repo(
    client: &ApiClient,
    project_root: &Path,
) -> Result<PushedRepo, Box<dyn std::error::Error>> {
    match crate::resolution::resolve_path_to_binding(project_root, client).await {
        Ok(Some(b)) => {
            if let Ok(id) = b.repo_id.parse() {
                return Ok(PushedRepo {
                    id,
                    remote_id: b.remote_id,
                });
            }
        }
        Ok(None) => {}
        Err(e) => return Err(connectivity_message(&e.to_string()).into()),
    }
    match resolve_repo_by_name(client, project_root).await {
        Ok(r) => Ok(PushedRepo {
            id: r.id,
            remote_id: None,
        }),
        Err(ResolveRepoByNameError::ListFailed(e)) => {
            Err(connectivity_message(&e.to_string()).into())
        }
        Err(ResolveRepoByNameError::NotFound { repo_name }) => {
            Err(format!("Repo '{repo_name}' not found on server. Run `{CLI} sync` first.").into())
        }
    }
}

/// A warning for a session whose events went to a different repo than the
/// one this push is checked under, or `None` when they agree (or the session
/// has no repo binding at all).
///
/// The session is still checked under the pushed repo — enforcement fails
/// closed — but the server looks verification-phase data up by exact repo
/// id, so that session's window and tool stats will not be found there.
///
/// Names the repos, not the session: the session id is not needed to act on
/// it (the fix is a `repo switch` in whichever session is bound elsewhere),
/// and CodeQL treats session ids as sensitive in log output.
fn streamed_elsewhere_warning(
    streamed_to: Option<&crate::session_state::RepoBinding>,
    pushed: &PushedRepo,
) -> Option<String> {
    let b = streamed_to?;
    if b.repo_id == pushed.id.to_string() {
        return None;
    }
    let scope = match (b.remote_id, pushed.remote_id) {
        (Some(a), Some(p)) if a == p => "another repo of this codebase",
        (Some(_), Some(_)) => "a different codebase",
        _ => "a different repo",
    };
    Some(format!(
        "Warning: an unpushed session streamed its events to {scope} ({}), not to the repo \
         this push is checked under ({}). Its verification-phase data will not be found; \
         run `{CLI} repo switch <this checkout>` in that session.",
        b.repo_id, pushed.id
    ))
}

/// Check unpushed sessions against server policies.
///
/// `project_root` — the git-resolved PRIMARY worktree root (from
///   `paths::resolve_project_root`). Used to load config/credentials, locate
///   `.visdom/sessions/`, and resolve the server-registered repo (by its
///   origin remote, else by the primary checkout's basename; a sibling
///   worktree's own directory basename would not match the registered repo).
/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used for
///   git *state* (`HEAD`) so the reported `commit_sha` is the commit being
///   pushed from the invoking worktree, not the primary's unrelated HEAD.
pub async fn check_policies(
    project_root: &Path,
    cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
    let (server_url, credential) = resolve_credentials(project_root)?;

    let server_url = server_url.ok_or(crate::program::say(
        "No server URL configured. Run `tracevault login --server-url=<url>` to set one.",
    ))?;

    if credential.is_none() {
        return Err(crate::program::say(
            "Not logged in. Run `tracevault login --server-url=<server_url>` to authenticate.",
        )
        .into());
    }

    let client = ApiClient::with_credential(&server_url, credential);

    // Resolve the pushed repo.
    //
    // Connectivity errors here (auth expired, server down, network
    // unreachable) propagate so the pre-push hook exits non-zero — if a
    // repo is opted into Visdom, every push must be evaluated, full
    // stop. Letting pushes slip when TV is unreachable would defeat the
    // point of enforcement. We attach an actionable next step to each
    // error so the user (or agent) knows the recovery command without
    // guessing — see `connectivity_message` below.
    let repo = resolve_pushed_repo(&client, project_root).await?;

    // Collect unpushed session dirs from the shared primary .visdom/.
    let sessions_dir = crate::layout::sessions_dir(project_root);
    let mut unpushed_dirs: Vec<std::path::PathBuf> = Vec::new();
    for dir in crate::layout::existing_sessions_dirs(project_root) {
        for entry in fs::read_dir(&dir)? {
            let entry = entry?;
            if !entry.file_type()?.is_dir() {
                continue;
            }
            let session_dir = entry.path();
            if session_dir.join(".pushed").exists() {
                continue;
            }
            unpushed_dirs.push(session_dir);
        }
    }

    // Filter to the worktree that is actually pushing, so a push is not
    // evaluated against sessions belonging to other worktrees.
    let worktree_top = crate::paths::worktree_toplevel(cwd);
    //
    // Sessions that keep their dir in the `.visdom/` they started in (an
    // umbrella dir, VIS-1257) and worked in this worktree, plus the session
    // running this push, wherever its dir is, belong to it too — found
    // first, so they count before falling back to every local session.
    let invoking = crate::session_state::env_session_id()
        .filter(|id| crate::session_state::is_safe_session_id(id))
        .map(|id| crate::session_state::session_dir(project_root, &id));
    let mut external = Vec::new();
    for dir in crate::session_state::anchored_session_dirs(&sessions_dir, &worktree_top)
        .into_iter()
        .chain(invoking)
    {
        add_external_session(&mut external, &sessions_dir, dir);
    }
    let selected_dirs = select_with_external(unpushed_dirs, external, &worktree_top);

    // Where each session's events actually went, resolved as the stream hook
    // resolves it — only to warn when that is not the pushed repo. A
    // malformed config.toml costs the bound tier here, nothing more: the
    // check never needed the config before.
    let bound = match crate::config::TracevaultConfig::try_load(project_root) {
        Ok(cfg) => cfg
            .as_ref()
            .and_then(crate::resolution::binding_from_config),
        Err(e) => {
            eprintln!("Warning: ignoring malformed .visdom/tracing.toml: {e}");
            None
        }
    };
    let user_default = crate::user_default::load();

    let mut sessions = Vec::new();
    for session_dir in &selected_dirs {
        if let Some(data) = collect_session_data(session_dir) {
            let state = crate::session_state::load(&data.session_id);
            let streamed_to = crate::resolution::recorded_session_binding(
                session_dir,
                &worktree_top,
                &state,
                bound.clone(),
                user_default.clone(),
            );
            if let Some(w) = streamed_elsewhere_warning(streamed_to.as_ref(), &repo) {
                eprintln!("{w}");
            }
            sessions.push(data);
        }
    }

    if sessions.is_empty() {
        println!("No unpushed sessions to check.");
        return Ok(());
    }

    println!("Checking {} session(s) against policies...", sessions.len());

    // HEAD comes from the invoking worktree (`cwd`), not the primary root —
    // the commit being pushed lives on the current worktree's branch.
    let commit_sha = git_head_sha(cwd);
    let changed_paths = resolve_changed_paths(cwd);
    let result = client
        .check_policies(
            &repo.id,
            CheckPoliciesRequest {
                sessions,
                commit_sha,
                changed_paths,
            },
        )
        .await
        .map_err(|e| connectivity_message(&e.to_string()))?;

    // Print results
    for r in &result.results {
        let icon = match r.result.as_str() {
            "pass" => "\x1b[32m✓\x1b[0m",                             // green
            "fail" if r.action == "block_push" => "\x1b[31m✗\x1b[0m", // red
            "fail" => "\x1b[33m!\x1b[0m",                             // yellow
            _ => " ",
        };
        println!(
            "  {} [{}] {} — {}",
            icon, r.severity, r.rule_name, r.details
        );
    }

    if result.blocked {
        eprintln!("\n\x1b[31mPolicy check failed: push blocked.\x1b[0m");
        std::process::exit(1);
    } else if result.passed {
        println!("\n\x1b[32mAll policy checks passed.\x1b[0m");
    } else {
        println!("\n\x1b[33mPolicy warnings found (push not blocked).\x1b[0m");
    }

    Ok(())
}

/// Wrap an opaque API-client error string with the most useful next step.
/// Today the api_client surfaces errors as `"Stream failed (401 ...)"` or
/// `"Server returned 500 Internal Server Error: ..."` strings; we sniff for
/// the common shapes and surface a one-line action. A 404 gets its own
/// version-mismatch hint rather than the generic fallback, since the calls
/// that route through here have no legitimate domain reason to 404 — see
/// the 404 branch below.
fn connectivity_message(raw: &str) -> String {
    let lower = raw.to_ascii_lowercase();

    // 401 — token rejected. An expired session is the most common cause of
    // a surprise blocked push, so point straight at the refresh command.
    if lower.contains("401") || lower.contains("unauthorized") {
        return with_action(
            raw,
            &crate::program::say("Session token may be expired. Run `tracevault login --server-url=<server_url>` to refresh."),
        );
    }
    // 403 — authenticated but not allowed. Re-login won't help; the token
    // itself is not authorized for this repo's policies.
    if lower.contains("403") || lower.contains("forbidden") {
        return with_action(
            raw,
            &crate::program::say("Your token is not authorized for this repo's policies. Confirm the token/service account has access and rerun `tracevault login`."),
        );
    }
    // 404 — the route itself wasn't found. Neither call that reaches this
    // function (`list_repos`, `check_policies`) has a legitimate domain
    // reason to 404 — a missing repo is already turned into its own message
    // by `resolve_repo_by_name`'s `NotFound` variant before it gets here —
    // so a 404 this far down most plausibly means this server build doesn't
    // recognize the route at all: a CLI/server version mismatch (e.g. this
    // CLI shipped ahead of a server still on the old routes).
    if lower.contains("404") {
        return with_action(
            raw,
            "This server may not recognize this endpoint yet — this can happen when the CLI is newer than the server. Confirm the server has been upgraded, or downgrade the CLI to match it.",
        );
    }
    // 5xx — server-side fault. Checked before the transport keywords below
    // so a `504 Gateway Timeout` reads as a server issue, not a local one.
    if is_server_error(&lower) {
        return with_action(
            raw,
            "Visdom server returned an error. The team has likely been paged; retry shortly.",
        );
    }
    // Transport-level failure with no HTTP status — DNS, refused, timeout.
    // ("connect" also covers "connection refused"/"connection reset".)
    if lower.contains("dns")
        || lower.contains("connect")
        || lower.contains("timed out")
        || lower.contains("timeout")
    {
        return with_action(
            raw,
            "Could not reach the Visdom server. Check network and `server_url` in .visdom/tracing.toml.",
        );
    }
    // Unrecognized — surface the raw error verbatim, no invented advice.
    format!("Policy check could not run: {raw}.")
}

/// Format the standard "could not run" line with an actionable next step.
fn with_action(raw: &str, action: &str) -> String {
    format!("Policy check could not run: {raw}.\n  → {action}")
}

/// Heuristic for a 5xx server-side failure. Matches the textual status
/// (`internal`, `server error`) and the concrete 5xx codes so a bare
/// `503 Service Unavailable` — which carries neither phrase — is still
/// recognized.
fn is_server_error(lower: &str) -> bool {
    lower.contains("internal")
        || lower.contains("server error")
        || ["500", "501", "502", "503", "504"]
            .iter()
            .any(|code| lower.contains(code))
}

#[cfg(test)]
mod worktree_tests {
    use super::{add_external_session, select_with_external, select_worktree_sessions};

    #[test]
    fn an_external_match_stops_the_fall_back_to_every_local_session() {
        let tmp = tempfile::tempdir().unwrap();
        let other = seed(tmp.path(), "other", Some("/wt/b"));
        let ext = tmp.path().join("umbrella-session");
        assert_eq!(
            select_with_external(vec![other.clone()], vec![ext.clone()], "/wt/a"),
            vec![ext.clone()]
        );
        assert_eq!(
            select_with_external(vec![other.clone()], vec![], "/wt/a"),
            vec![other.clone()],
            "no match at all still checks everything"
        );
        let mine = seed(tmp.path(), "mine", Some("/wt/a"));
        assert_eq!(
            select_with_external(vec![mine.clone(), other], vec![ext.clone()], "/wt/a"),
            vec![mine, ext]
        );
    }
    use std::path::PathBuf;

    /// A session kept here that ran here and moved to another repo: its
    /// `origin` names the other repo, its worktree list names this one.
    #[test]
    fn keeps_a_session_that_ran_here_before_moving_on() {
        let tmp = tempfile::tempdir().unwrap();
        let moved = seed(tmp.path(), "moved", Some("/wt/b"));
        crate::session_state::record_worktree(&moved, "/wt/a").unwrap();
        crate::session_state::record_worktree(&moved, "/wt/b").unwrap();
        let mine = seed(tmp.path(), "mine", Some("/wt/a"));
        let other = seed(tmp.path(), "other", Some("/wt/b"));
        let (mut kept, fell_back) =
            select_worktree_sessions(vec![moved.clone(), mine.clone(), other], "/wt/a");
        kept.sort();
        assert_eq!(kept, vec![mine, moved]);
        assert!(!fell_back);
    }

    #[test]
    fn adds_an_external_session_only_when_it_lives_elsewhere() {
        let tmp = tempfile::tempdir().unwrap();
        let here = tmp.path().join("repo/.visdom/sessions");
        let local = seed(&here, "local", Some("/wt/b"));
        let elsewhere = seed(
            &tmp.path().join("umbrella/.visdom/sessions"),
            "s",
            Some("/u"),
        );
        let pushed = seed(&tmp.path().join("umbrella/.visdom/sessions"), "p", None);
        std::fs::write(pushed.join(".pushed"), "").unwrap();

        let mut selected = vec![];
        add_external_session(&mut selected, &here, local);
        assert!(
            selected.is_empty(),
            "a local dir is the worktree filter's call"
        );

        add_external_session(&mut selected, &here, elsewhere.clone());
        add_external_session(&mut selected, &here, elsewhere.clone());
        add_external_session(&mut selected, &here, tmp.path().join("missing"));
        add_external_session(&mut selected, &here, pushed);
        assert_eq!(selected, vec![elsewhere]);
    }

    fn seed(tmp: &std::path::Path, id: &str, origin: Option<&str>) -> PathBuf {
        let d = tmp.join(id);
        std::fs::create_dir_all(&d).unwrap();
        if let Some(o) = origin {
            std::fs::write(d.join("origin"), o).unwrap();
        }
        d
    }

    #[test]
    fn keeps_current_worktree_and_unmarked_excludes_other() {
        let tmp = tempfile::tempdir().unwrap();
        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
        let other = seed(tmp.path(), "other", Some("/wt/there"));
        let legacy = seed(tmp.path(), "legacy", None);

        let (kept, fell_back) = select_worktree_sessions(
            vec![mine.clone(), other.clone(), legacy.clone()],
            "/wt/here",
        );

        assert!(!fell_back);
        assert!(kept.contains(&mine), "current worktree session kept");
        assert!(
            kept.contains(&legacy),
            "unmarked legacy session kept (conservative)"
        );
        assert!(
            !kept.contains(&other),
            "other worktree's marked session excluded"
        );
    }

    #[test]
    fn excludes_session_with_unreadable_marker() {
        let tmp = tempfile::tempdir().unwrap();
        let mine = seed(tmp.path(), "mine", Some("/wt/here"));
        // A present-but-unreadable marker: make `origin` a directory so
        // read_to_string fails with a non-NotFound error.
        let bad = tmp.path().join("bad");
        std::fs::create_dir_all(bad.join("origin")).unwrap();

        let (kept, fell_back) =
            select_worktree_sessions(vec![mine.clone(), bad.clone()], "/wt/here");

        assert!(!fell_back);
        assert!(kept.contains(&mine), "current worktree session kept");
        assert!(
            !kept.contains(&bad),
            "session with a present-but-unreadable marker must be excluded, not kept as legacy"
        );
    }

    #[test]
    fn falls_back_to_all_when_nothing_matches() {
        let tmp = tempfile::tempdir().unwrap();
        let a = seed(tmp.path(), "a", Some("/wt/there"));
        let b = seed(tmp.path(), "b", Some("/wt/elsewhere"));

        let (kept, fell_back) = select_worktree_sessions(vec![a.clone(), b.clone()], "/wt/here");

        assert!(fell_back, "must flag fallback when filter matches nothing");
        assert_eq!(
            kept.len(),
            2,
            "never under-enforce: send all rather than zero"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::{collect_session_data, connectivity_message};

    /// The stream hook's `metadata.json` is what lets `check` see a streaming
    /// session's tool calls; without it every session sent `tool_calls: None`
    /// and a "must call X" policy could never pass.
    #[test]
    fn counts_tool_calls_from_the_transcript_the_stream_hook_recorded() {
        let tmp = tempfile::tempdir().unwrap();
        let transcript = tmp.path().join("t.jsonl");
        std::fs::write(
            &transcript,
            concat!(
                r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
                "\n",
                r#"{"type":"assistant","message":{"content":[{"type":"tool_use","name":"Bash"},{"type":"tool_use","name":"mcp__cargo__cargo_check"}]}}"#,
                "\n",
            ),
        )
        .unwrap();
        let session_dir = tmp.path().join("sess-1");
        std::fs::create_dir_all(&session_dir).unwrap();

        let before = collect_session_data(&session_dir).unwrap();
        assert!(
            before.tool_calls.is_none(),
            "no metadata.json, no tool calls"
        );

        crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
            .unwrap();
        let after = collect_session_data(&session_dir).unwrap();

        assert_eq!(after.session_id, "sess-1");
        assert_eq!(after.total_tool_calls, Some(3));
        assert_eq!(
            after.tool_calls,
            Some(serde_json::json!({"mcp__cargo__cargo_check": 2, "Bash": 1}))
        );
    }

    /// Write `lines` as a transcript, record it the way the stream hook does,
    /// and return the tool calls `check` counts from it.
    fn tool_calls_from_transcript(lines: &[&str]) -> Option<serde_json::Value> {
        let tmp = tempfile::tempdir().unwrap();
        let transcript = tmp.path().join("t.jsonl");
        std::fs::write(&transcript, lines.join("\n")).unwrap();
        let session_dir = tmp.path().join("sess");
        std::fs::create_dir_all(&session_dir).unwrap();
        crate::commands::stream::record_transcript_path(&session_dir, transcript.to_str().unwrap())
            .unwrap();
        collect_session_data(&session_dir).unwrap().tool_calls
    }

    #[test]
    fn counts_tool_calls_from_a_codex_rollout() {
        let calls = tool_calls_from_transcript(&[
            r#"{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}"#,
            r#"{"type":"response_item","payload":{"type":"custom_tool_call","name":"apply_patch","input":"*** Begin Patch\n*** End Patch\n"}}"#,
            r#"{"type":"response_item","payload":{"type":"function_call","name":"mcp__cargo__cargo_check","arguments":"{}"}}"#,
            r#"{"type":"response_item","payload":{"type":"local_shell_call","command":"ls"}}"#,
            r#"{"type":"event_msg","payload":{"type":"token_count"}}"#,
        ]);
        assert_eq!(
            calls,
            Some(serde_json::json!({"apply_patch": 1, "mcp__cargo__cargo_check": 1, "Bash": 1}))
        );
    }

    #[test]
    fn counts_tool_calls_from_a_gsd_session() {
        let calls = tool_calls_from_transcript(&[
            r#"{"type":"model_change","provider":"anthropic","modelId":"claude-opus-4-7"}"#,
            r#"{"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"ok"},{"type":"toolCall","id":"t1","name":"write","arguments":{}},{"type":"toolCall","id":"t2","name":"bash","arguments":{}}]}}"#,
            r#"{"type":"message","message":{"role":"toolResult","toolName":"write","content":[]}}"#,
        ]);
        assert_eq!(calls, Some(serde_json::json!({"write": 1, "bash": 1})));
    }

    /// OpenCode sends no transcript path, only inline records; the stream hook
    /// keeps their tool calls in a local log that `check` then counts.
    #[test]
    fn counts_tool_calls_from_opencode_inline_records() {
        let tmp = tempfile::tempdir().unwrap();
        let tool_event = [
            serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"toolCall","name":"bash","arguments":{"command":"ls"}}]}}),
            serde_json::json!({"type":"message","message":{"role":"toolResult","toolName":"bash","isError":false,"content":[{"type":"text","text":"a.rs"}]}}),
        ];
        let assistant_turn = [
            serde_json::json!({"type":"message","message":{"role":"assistant","content":[{"type":"text","text":"done"}]}}),
        ];

        crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
        crate::commands::stream::record_inline_tool_calls(tmp.path(), &assistant_turn).unwrap();
        assert!(collect_session_data(tmp.path())
            .unwrap()
            .tool_calls
            .is_none());

        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
        let data = collect_session_data(tmp.path()).unwrap();
        assert_eq!(data.tool_calls, Some(serde_json::json!({"bash": 2})));
        assert_eq!(data.total_tool_calls, Some(2));
    }

    /// Amp's plugin sends Amp's own messages in an `amp_message` envelope;
    /// policies name Amp's tools exactly (`shell_command`, `Task`, ...).
    #[test]
    fn counts_tool_calls_from_amp_inline_records() {
        let tmp = tempfile::tempdir().unwrap();
        let tool_event = [
            serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"assistant","content":[{"type":"tool_use","id":"TU-1","name":"shell_command","input":{"command":"ls"}}]}}),
            serde_json::json!({"type":"amp_message","event":"tool.result","message":{"role":"user","content":[{"type":"tool_result","toolUseID":"TU-1","status":"done","output":{"output":"","exitCode":1}}]}}),
        ];
        let turn_end = [
            serde_json::json!({"type":"amp_message","event":"agent.end","message":{"role":"assistant","content":[{"type":"text","text":"ok"},{"type":"tool_use","id":"TU-2","name":"Task","input":{}}],"usage":{"inputTokens":1}}}),
        ];

        crate::commands::stream::record_transcript_path(tmp.path(), "").unwrap();
        crate::commands::stream::record_inline_tool_calls(tmp.path(), &tool_event).unwrap();
        crate::commands::stream::record_inline_tool_calls(tmp.path(), &turn_end).unwrap();
        let data = collect_session_data(tmp.path()).unwrap();
        assert_eq!(
            data.tool_calls,
            Some(serde_json::json!({"shell_command": 1, "Task": 1}))
        );
        assert_eq!(data.total_tool_calls, Some(2));
    }

    #[test]
    fn connectivity_message_suggests_login_on_401() {
        let m = connectivity_message("Stream failed (401 Unauthorized): bad token");
        assert!(
            m.contains("tracevault login"),
            "401 errors must surface the login hint; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_suggests_login_on_unauthorized_text() {
        let m = connectivity_message("Server returned: unauthorized request");
        assert!(m.contains("tracevault login"));
    }

    #[test]
    fn connectivity_message_suggests_network_check_on_dns_error() {
        let m = connectivity_message("error sending request for url: dns error");
        assert!(
            m.to_lowercase().contains("network") || m.to_lowercase().contains("server_url"),
            "DNS errors must surface a network hint; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_suggests_network_check_on_connection_refused() {
        let m = connectivity_message("connection refused");
        assert!(m.to_lowercase().contains("network"));
    }

    #[test]
    fn connectivity_message_falls_back_when_unrecognized() {
        let m = connectivity_message("some weird new error shape we have not seen before");
        // No suggestion — but the raw error must still be in the message so
        // the user can debug.
        assert!(m.contains("some weird new error shape"));
        assert!(!m.contains("→")); // no action arrow
    }

    #[test]
    fn connectivity_message_does_not_collide_on_403() {
        let m = connectivity_message("403 Forbidden");
        // 403 should point at token authorization, NOT a re-login.
        assert!(
            m.to_lowercase().contains("authorized"),
            "403 should mention authorization; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_flags_404_as_version_mismatch() {
        // Simulates an old-server-404 skew: a route the CLI expects to exist
        // (e.g. `Failed to list repos (404 Not Found)`) doesn't exist yet on
        // this server build. Must hint at a version mismatch, not just
        // report a bare 404 with no next step.
        let m = connectivity_message("Failed to list repos (404 Not Found): ");
        assert!(
            m.to_lowercase().contains("newer than the server")
                || m.to_lowercase().contains("version mismatch"),
            "404 should hint at a possible CLI/server version mismatch; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_flags_500_as_server_error() {
        let m = connectivity_message("Server returned 500 Internal Server Error: oops");
        assert!(
            m.to_lowercase().contains("server returned an error"),
            "500 should surface the server-error hint; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_flags_503_without_internal_text() {
        // `503 Service Unavailable` carries neither "internal" nor
        // "server error" — the bare code must still be recognized.
        let m = connectivity_message("Server returned 503 Service Unavailable: ");
        assert!(
            m.to_lowercase().contains("server returned an error"),
            "503 should surface the server-error hint; got: {m}"
        );
    }

    #[test]
    fn connectivity_message_treats_504_as_server_not_network() {
        // A gateway timeout is a server-side fault even though it contains
        // the word "timeout"; it must not be misreported as a local network
        // problem.
        let m = connectivity_message("Server returned 504 Gateway Timeout: ");
        assert!(
            m.to_lowercase().contains("server returned an error"),
            "504 should be treated as a server error; got: {m}"
        );
    }
}

#[cfg(test)]
mod push_ref_tests {
    use super::{is_zero_sha, parse_push_refs};

    #[test]
    fn parses_a_single_ref_line() {
        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456\n");
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].local_sha, "abc123");
        assert_eq!(refs[0].remote_sha, "def456");
    }

    #[test]
    fn parses_multiple_refs() {
        let refs = parse_push_refs(
            "refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444\n",
        );
        assert_eq!(refs.len(), 2);
    }

    #[test]
    fn parses_a_single_ref_line_without_trailing_newline() {
        // This is the exact shape the generated pre-push hook produces: it
        // captures git's stdin with `$(cat)` (which strips trailing
        // newlines) and replays it with `printf '%s'` (which adds none
        // back), so the real input to `check` has no trailing newline on
        // its final line. Here that unterminated line is the *only* line.
        // Do not delete this as a duplicate of `parses_a_single_ref_line`;
        // it pins a different, easy-to-break input shape.
        let refs = parse_push_refs("refs/heads/main abc123 refs/heads/main def456");
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].local_sha, "abc123");
        assert_eq!(refs[0].remote_sha, "def456");
    }

    #[test]
    fn parses_multiple_refs_when_last_line_has_no_trailing_newline() {
        // Same hook-stdin shape as above, but with two refs: only the final
        // line is unterminated, matching a real multi-ref push through
        // `$(cat)` + `printf '%s'`.
        let refs =
            parse_push_refs("refs/heads/a 111 refs/heads/a 222\nrefs/heads/b 333 refs/heads/b 444");
        assert_eq!(refs.len(), 2);
        assert_eq!(refs[0].local_sha, "111");
        assert_eq!(refs[1].local_sha, "333");
    }

    #[test]
    fn skips_branch_deletions() {
        let zeros = "0".repeat(40);
        let line = format!("(delete) {zeros} refs/heads/gone abc123\n");
        assert!(parse_push_refs(&line).is_empty());
    }

    #[test]
    fn keeps_new_branches_whose_remote_sha_is_zero() {
        let zeros = "0".repeat(40);
        let line = format!("refs/heads/new abc123 refs/heads/new {zeros}\n");
        let refs = parse_push_refs(&line);
        assert_eq!(refs.len(), 1);
        assert!(is_zero_sha(&refs[0].remote_sha));
    }

    #[test]
    fn skips_malformed_lines_without_panicking() {
        assert!(parse_push_refs("garbage\n\nalso garbage here\n").is_empty());
    }

    #[test]
    fn zero_sha_detection_handles_sha256_length() {
        assert!(is_zero_sha(&"0".repeat(64)));
        assert!(!is_zero_sha("0000000000000000000000000000000000000001"));
        assert!(!is_zero_sha(""));
    }
}

/// Real-git coverage for the functions `resolve_changed_paths` composes:
/// `changed_files_for_refs` (the two-dot range and the empty-tree base for
/// new branches) and `git_empty_tree_sha`.
///
/// `resolve_changed_paths` itself is deliberately NOT driven directly here.
/// It reads `std::io::stdin()` when stdin is not a terminal, and `cargo
/// test` runs every test in one process sharing that real, global stdin —
/// there is no per-test way to inject or close it without invasive,
/// process-wide fd surgery, and a test that consumes it would make unrelated
/// tests in the same binary flaky. Testing the two git-backed branches it
/// falls back to (below) is the safe substitute; the stdin-parsing branch
/// itself is already covered without touching stdin by `push_ref_tests`
/// (`parse_push_refs`) plus `two_dot_range_returns_only_the_newer_commits_files`
/// and `new_branch_zero_remote_sha_resolves_via_empty_tree` below, which
/// together exercise every step `resolve_changed_paths` performs once it has
/// a parsed `Vec<PushRef>` in hand. The timeout mechanism that bounds the
/// stdin read (`read_with_timeout`) is factored generically over the reading
/// closure precisely so it can be tested without touching stdin at all —
/// see `read_with_timeout_tests` below.
#[cfg(test)]
mod git_diff_tests {
    use super::{changed_files_for_refs, git_empty_tree_sha, PushRef};
    use crate::test_helpers::init_git_repo;
    use std::path::Path;
    use std::process::Command;

    /// Write `name` with `content` in `dir`, stage it, and commit it,
    /// returning the new commit's sha. Assumes `init_git_repo` already
    /// configured a local `user.name`/`user.email` in `dir`.
    fn commit_file(dir: &Path, name: &str, content: &str) -> String {
        std::fs::write(dir.join(name), content).unwrap();
        let ok = Command::new("git")
            .args(["-C", &dir.to_string_lossy(), "add", name])
            .status()
            .expect("git add failed")
            .success();
        assert!(ok, "git add must succeed");
        let ok = Command::new("git")
            .args([
                "-C",
                &dir.to_string_lossy(),
                "commit",
                "-m",
                &format!("add {name}"),
            ])
            .status()
            .expect("git commit failed")
            .success();
        assert!(ok, "git commit must succeed");
        head_sha(dir)
    }

    fn head_sha(dir: &Path) -> String {
        let out = Command::new("git")
            .args(["-C", &dir.to_string_lossy(), "rev-parse", "HEAD"])
            .output()
            .expect("git rev-parse failed");
        assert!(out.status.success());
        String::from_utf8_lossy(&out.stdout).trim().to_string()
    }

    #[test]
    fn two_dot_range_returns_only_the_newer_commits_files() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path()); // empty "init" commit

        let sha1 = commit_file(tmp.path(), "a.txt", "a");
        let sha2 = commit_file(tmp.path(), "b.txt", "b");

        let refs = vec![PushRef {
            local_sha: sha2,
            remote_sha: sha1,
        }];
        let files = changed_files_for_refs(tmp.path(), &refs);

        // Must be exactly the file the newer commit touched. A single-arg
        // `git diff --name-only <sha>` would instead diff against the
        // working tree and silently pull in every tracked file (here, also
        // "a.txt") — this is the mistake this test exists to catch.
        assert_eq!(files, vec!["b.txt".to_string()]);
    }

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

        commit_file(tmp.path(), "a.txt", "a");
        let sha2 = commit_file(tmp.path(), "b.txt", "b");

        let refs = vec![PushRef {
            local_sha: sha2,
            remote_sha: "0".repeat(40),
        }];
        let mut files = changed_files_for_refs(tmp.path(), &refs);
        files.sort();

        // A brand-new branch has no remote sha to diff from; the base must
        // resolve to the empty tree, so the full branch history shows up.
        assert_eq!(files, vec!["a.txt".to_string(), "b.txt".to_string()]);
    }

    #[test]
    fn identical_shas_yield_an_empty_file_list() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        let sha = commit_file(tmp.path(), "a.txt", "a");

        let refs = vec![PushRef {
            local_sha: sha.clone(),
            remote_sha: sha,
        }];
        let files = changed_files_for_refs(tmp.path(), &refs);

        assert!(
            files.is_empty(),
            "a no-op push (same local and remote sha) must yield no files, got {files:?}"
        );
    }

    #[test]
    fn non_ascii_path_is_returned_raw_not_octal_quoted() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();

        let sha1 = commit_file(tmp.path(), "src/café.rs", "one");
        let sha2 = commit_file(tmp.path(), "src/café.rs", "two");

        let refs = vec![PushRef {
            local_sha: sha2,
            remote_sha: sha1,
        }];
        let files = changed_files_for_refs(tmp.path(), &refs);

        // Without `-z`, git's default `core.quotePath` behaviour renders this
        // as the 20-character literal string `"src/caf\303\251.rs"`
        // (surrounding quotes included) instead of the real path — see the
        // fix's doc comment. That string can never match the hook-recorded
        // path, so the file is silently pruned from `changed_paths`.
        assert_eq!(
            files,
            vec!["src/café.rs".to_string()],
            "must be the raw UTF-8 path, not git's octal-quoted rendering; got {files:?}"
        );
    }

    #[test]
    fn path_containing_a_space_is_returned_intact() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();

        let sha1 = commit_file(tmp.path(), "src/has space.rs", "one");
        let sha2 = commit_file(tmp.path(), "src/has space.rs", "two");

        let refs = vec![PushRef {
            local_sha: sha2,
            remote_sha: sha1,
        }];
        let files = changed_files_for_refs(tmp.path(), &refs);

        assert_eq!(files, vec!["src/has space.rs".to_string()]);
    }

    #[test]
    fn rename_reports_both_source_and_destination() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        let sha1 = commit_file(tmp.path(), "src/plain.rs", "identical content");

        let ok = Command::new("git")
            .args([
                "-C",
                &tmp.path().to_string_lossy(),
                "mv",
                "src/plain.rs",
                "src/renamed.rs",
            ])
            .status()
            .expect("git mv failed")
            .success();
        assert!(ok, "git mv must succeed");
        let ok = Command::new("git")
            .args([
                "-C",
                &tmp.path().to_string_lossy(),
                "commit",
                "-m",
                "rename plain.rs to renamed.rs",
            ])
            .status()
            .expect("git commit failed")
            .success();
        assert!(ok, "git commit must succeed");
        let sha2 = head_sha(tmp.path());

        let refs = vec![PushRef {
            local_sha: sha2,
            remote_sha: sha1,
        }];
        let mut files = changed_files_for_refs(tmp.path(), &refs);
        files.sort();

        // Git's rename detection is on by default, so a plain `git diff
        // --name-only` here would report only `src/renamed.rs`, hiding the
        // fact that `src/plain.rs` ever existed in this diff. If
        // `src/plain.rs` were a protected path, that silence is exactly what
        // lets an agent rename it away undetected.
        assert_eq!(
            files,
            vec!["src/plain.rs".to_string(), "src/renamed.rs".to_string()],
            "a rename must surface BOTH the source and destination path; got {files:?}"
        );
    }

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

        let empty_tree =
            git_empty_tree_sha(tmp.path()).expect("git hash-object must resolve the empty tree");
        // The well-known empty-tree object id for sha1 repositories (git's
        // default) — asserted against the literal, not just "non-empty", so
        // a regression that resolves some other tree can't slip through.
        assert_eq!(empty_tree, "4b825dc642cb6eb9a060e54bf8d69288fbee4904");
    }

    /// Not a call into `resolve_changed_paths` (see the module doc comment
    /// above for why) — this drives the exact git invocation its
    /// `@{{upstream}}` fallback branch makes, in a repo with no upstream
    /// configured, confirming that branch fails cleanly (non-zero exit) and
    /// so `resolve_changed_paths` would correctly return `None` rather than
    /// erroring or panicking.
    #[test]
    fn upstream_fallback_diff_fails_cleanly_with_no_upstream_configured() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        commit_file(tmp.path(), "a.txt", "a");

        let out = Command::new("git")
            .args([
                "diff",
                "--name-only",
                "-z",
                "--no-renames",
                "@{upstream}..HEAD",
            ])
            .current_dir(tmp.path())
            .output()
            .expect("git diff must run");

        assert!(
            !out.status.success(),
            "no upstream is configured, so this must fail rather than \
             silently resolve to something else"
        );
    }

    /// Companion to the test above: with an upstream configured but no diff
    /// between it and `HEAD`, the same invocation must succeed with empty
    /// output — the shape `resolve_changed_paths` treats as `None`.
    #[test]
    fn upstream_fallback_diff_is_empty_when_upstream_matches_head() {
        let tmp = tempfile::tempdir().unwrap();
        init_git_repo(tmp.path());
        commit_file(tmp.path(), "a.txt", "a");

        let branch_out = Command::new("git")
            .args(["symbolic-ref", "--short", "HEAD"])
            .current_dir(tmp.path())
            .output()
            .expect("git symbolic-ref must run");
        assert!(branch_out.status.success());
        let branch = String::from_utf8_lossy(&branch_out.stdout)
            .trim()
            .to_string();

        // Track a same-commit local branch as upstream, so `@{upstream}`
        // resolves but the diff against it is empty — without needing an
        // actual remote.
        for args in [
            vec!["branch", "tracking", &branch],
            vec!["branch", "--set-upstream-to=tracking", &branch],
        ] {
            let ok = Command::new("git")
                .args(&args)
                .current_dir(tmp.path())
                .status()
                .expect("git command must run")
                .success();
            assert!(ok, "git {args:?} must succeed");
        }

        let out = Command::new("git")
            .args([
                "diff",
                "--name-only",
                "-z",
                "--no-renames",
                "@{upstream}..HEAD",
            ])
            .current_dir(tmp.path())
            .output()
            .expect("git diff must run");

        assert!(out.status.success());
        assert!(
            out.stdout.is_empty(),
            "identical upstream/HEAD must diff to no files"
        );
    }
}

/// Coverage for the generic timeout mechanism behind `read_stdin_with_timeout`.
///
/// These drive `read_with_timeout` directly with an injected closure instead
/// of the real `stdin()` — see the doc comment on `git_diff_tests` above for
/// why touching the process's real, global stdin from a test is unsafe here.
/// `read_stdin_with_timeout` itself is left thin and untested; once the
/// generic helper is proven to time out and to pass through a prompt result,
/// there is nothing stdin-specific left to verify.
#[cfg(test)]
mod read_with_timeout_tests {
    use super::read_with_timeout;
    use std::time::Duration;

    #[test]
    fn returns_the_value_when_it_arrives_before_the_deadline() {
        let got = read_with_timeout(|| Some("hi".to_string()), Duration::from_secs(1));
        assert_eq!(got, Some("hi".to_string()));
    }

    #[test]
    fn returns_none_when_the_closure_itself_returns_none() {
        let got = read_with_timeout(|| None, Duration::from_secs(1));
        assert_eq!(got, None);
    }

    #[test]
    fn times_out_instead_of_hanging_on_a_closure_that_never_returns() {
        // The stalled-pipe case in miniature: the closure blocks well past
        // the deadline (in the real bug, forever). Margins are kept wide so
        // this cannot flake on a loaded CI machine — a 50ms timeout that
        // must return within 1s, against a closure that sleeps for 10s.
        let start = std::time::Instant::now();
        let got = read_with_timeout(
            || {
                std::thread::sleep(Duration::from_secs(10));
                Some("too late".to_string())
            },
            Duration::from_millis(50),
        );
        assert_eq!(got, None, "must give up rather than wait for the closure");
        assert!(
            start.elapsed() < Duration::from_secs(1),
            "must return promptly on timeout, not block on the stalled closure; took {:?}",
            start.elapsed()
        );
    }
}

#[cfg(test)]
mod pushed_repo_tests {
    use super::{streamed_elsewhere_warning, PushedRepo};
    use crate::session_state::RepoBinding;

    /// The repo the checkout's origin remote resolves to.
    const PUSHED: uuid::Uuid = uuid::uuid!("44000761-0000-4000-8000-000000000001");
    /// The repo registered under the checkout's directory name.
    const BY_NAME: uuid::Uuid = uuid::uuid!("7995d35d-0000-4000-8000-000000000002");
    /// Some other repo a session could be bound to.
    const OTHER: uuid::Uuid = uuid::uuid!("aaaaaaaa-0000-4000-8000-000000000003");
    const CODEBASE: uuid::Uuid = uuid::uuid!("cccccccc-0000-4000-8000-000000000004");
    const OTHER_CODEBASE: uuid::Uuid = uuid::uuid!("dddddddd-0000-4000-8000-000000000005");
    const PASS: &str = r#"{"passed":true,"results":[],"blocked":false}"#;

    fn binding(repo: uuid::Uuid, remote: Option<uuid::Uuid>) -> RepoBinding {
        RepoBinding {
            repo_id: repo.to_string(),
            git_url: None,
            remote_id: remote,
            codebase_name: None,
            updated_at: "t".into(),
        }
    }

    // ── streamed_elsewhere_warning ───────────────────────────────────────────

    #[test]
    fn no_warning_when_the_session_streamed_to_the_pushed_repo_or_is_unbound() {
        let pushed = PushedRepo {
            id: PUSHED,
            remote_id: Some(CODEBASE),
        };
        assert_eq!(
            streamed_elsewhere_warning(Some(&binding(PUSHED, None)), &pushed),
            None
        );
        assert_eq!(streamed_elsewhere_warning(None, &pushed), None);
    }

    #[test]
    fn warning_names_both_repos_and_how_far_apart_they_are() {
        let pushed = PushedRepo {
            id: PUSHED,
            remote_id: Some(CODEBASE),
        };
        let same =
            streamed_elsewhere_warning(Some(&binding(OTHER, Some(CODEBASE))), &pushed).unwrap();
        assert!(same.contains("another repo of this codebase"), "{same}");
        assert!(same.contains(&OTHER.to_string()) && same.contains(&PUSHED.to_string()));
        let far = streamed_elsewhere_warning(Some(&binding(OTHER, Some(OTHER_CODEBASE))), &pushed)
            .unwrap();
        assert!(far.contains("a different codebase"), "{far}");
        let unknown = streamed_elsewhere_warning(Some(&binding(OTHER, None)), &pushed).unwrap();
        assert!(unknown.contains("a different repo"), "{unknown}");
    }

    // ── check_policies end to end against a one-shot server ──────────────────

    /// Isolated config/state homes and a saved login for a server answering
    /// `responses` in order; a primary checkout named `tracing` (with an
    /// origin remote when `remote` is set) holding the given sessions, all
    /// marked as this worktree's.
    struct Fixture {
        _guard: crate::test_helpers::EnvVarGuard,
        _home: tempfile::TempDir,
        _tmp: tempfile::TempDir,
        repo: std::path::PathBuf,
        rx: std::sync::mpsc::Receiver<String>,
    }

    fn fixture(remote: bool, sessions: &[&str], responses: Vec<String>) -> Fixture {
        let home = tempfile::tempdir().unwrap();
        let mut guard = crate::test_helpers::EnvVarGuard::new();
        guard.set("XDG_CONFIG_HOME", home.path());
        guard.set("XDG_STATE_HOME", home.path());
        guard.remove("TRACEVAULT_API_KEY");
        guard.remove("TRACEVAULT_SERVER_URL");
        let (server, rx) = crate::test_helpers::spawn_seq(responses);
        let creds_dir = home.path().join("visdom");
        std::fs::create_dir_all(&creds_dir).unwrap();
        std::fs::write(
            creds_dir.join("credentials.json"),
            format!(
                r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
            ),
        )
        .unwrap();

        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("tracing");
        std::fs::create_dir_all(&repo).unwrap();
        crate::test_helpers::init_git_repo(&repo);
        if remote {
            let ok = std::process::Command::new("git")
                .args([
                    "remote",
                    "add",
                    "origin",
                    "https://github.com/example/visdom-tracing.git",
                ])
                .current_dir(&repo)
                .status()
                .unwrap()
                .success();
            assert!(ok, "git remote add failed");
        }
        let top = crate::paths::worktree_toplevel(&repo);
        for id in sessions {
            let dir = repo.join(".visdom").join("sessions").join(id);
            std::fs::create_dir_all(&dir).unwrap();
            std::fs::write(dir.join("origin"), &top).unwrap();
        }
        Fixture {
            _guard: guard,
            _home: home,
            _tmp: tmp,
            repo,
            rx,
        }
    }

    fn bind_with_repo_switch(session_id: &str, repo_id: uuid::Uuid) {
        let state = crate::session_state::SessionState {
            active: Some(binding(repo_id, None)),
            ..Default::default()
        };
        crate::session_state::save(session_id, &state).unwrap();
    }

    /// The origin remote resolves to codebase `CODEBASE`, whose only repo is
    /// `PUSHED` — what `repo switch <checkout>` binds a session to.
    fn remote_resolves_to_pushed() -> Vec<String> {
        vec![
            crate::test_helpers::http_json(
                "200 OK",
                &format!(
                    r#"{{"remote_id":"{CODEBASE}","name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready"}}"#
                ),
            ),
            crate::test_helpers::http_json(
                "200 OK",
                &format!(
                    r#"{{"name":"visdom-tracing","normalized_url":"github.com/example/visdom-tracing","clone_status":"ready","repos":[{{"id":"{PUSHED}","name":"visdom-tracing"}}]}}"#
                ),
            ),
        ]
    }

    fn repos_listing() -> String {
        crate::test_helpers::http_json(
            "200 OK",
            &format!(r#"[{{"id":"{BY_NAME}","name":"tracing"}}]"#),
        )
    }

    fn pass() -> String {
        crate::test_helpers::http_json("200 OK", PASS)
    }

    fn recv(f: &Fixture) -> String {
        f.rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT)
            .expect("expected another request")
    }

    fn assert_checked_under(request: &str, repo: uuid::Uuid) {
        assert!(
            request.starts_with(&format!("POST /api/v1/repos/{repo}/policies/check")),
            "expected the check under {repo}: {request}"
        );
    }

    /// VIS-601 (first hit on VIS-536's PR): a session bound with
    /// `repo switch <checkout>` streamed to the repo the checkout's remote
    /// resolves to, but was checked under the repo found by directory name.
    /// The push is now checked under the remote-resolved repo, where that
    /// session's data lives.
    #[tokio::test]
    async fn a_push_is_checked_under_the_repo_its_remote_resolves_to() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut responses = remote_resolves_to_pushed();
        responses.push(pass());
        let f = fixture(true, &["sess-bound"], responses);
        bind_with_repo_switch("sess-bound", PUSHED);

        super::check_policies(&f.repo, &f.repo).await.unwrap();

        assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
        assert!(recv(&f).starts_with(&format!("GET /api/v1/remotes/{CODEBASE} ")));
        let check = recv(&f);
        assert_checked_under(&check, PUSHED);
        assert!(check.contains("sess-bound"), "{check}");
    }

    /// The pushed repo is the policy authority: a session bound elsewhere —
    /// by `repo switch` or by a machine-wide user default — must not move the
    /// push to that repo's (possibly laxer) policies.
    #[tokio::test]
    async fn a_session_bound_elsewhere_does_not_change_which_repo_the_push_is_checked_under() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let mut responses = remote_resolves_to_pushed();
        responses.push(pass());
        let f = fixture(true, &["sess-switched", "sess-default"], responses);
        bind_with_repo_switch("sess-switched", OTHER);
        crate::user_default::save(&binding(OTHER, None)).unwrap();
        assert_eq!(
            crate::user_default::load().map(|b| b.repo_id),
            Some(OTHER.to_string()),
            "fixture must actually set a user default"
        );

        super::check_policies(&f.repo, &f.repo).await.unwrap();

        recv(&f);
        recv(&f);
        let check = recv(&f);
        assert_checked_under(&check, PUSHED);
        assert!(
            check.contains("sess-switched") && check.contains("sess-default"),
            "every session is still evaluated (fail closed): {check}"
        );
    }

    /// No origin remote: the directory-name lookup, exactly as before VIS-601.
    #[tokio::test]
    async fn without_a_remote_the_push_is_checked_under_the_name_resolved_repo() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let f = fixture(false, &["sess-free"], vec![repos_listing(), pass()]);

        super::check_policies(&f.repo, &f.repo).await.unwrap();

        assert!(recv(&f).starts_with("GET /api/v1/repos "));
        let check = recv(&f);
        assert_checked_under(&check, BY_NAME);
        assert!(check.contains("sess-free"), "{check}");
    }

    /// A remote the server does not know falls back to the name lookup too.
    #[tokio::test]
    async fn an_unknown_remote_falls_back_to_the_name_resolved_repo() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let f = fixture(
            true,
            &["sess-free"],
            vec![
                crate::test_helpers::http_json("404 Not Found", r#"{"error":"remote not found"}"#),
                repos_listing(),
                pass(),
            ],
        );

        super::check_policies(&f.repo, &f.repo).await.unwrap();

        assert!(recv(&f).starts_with("GET /api/v1/remotes/resolve?git_url="));
        assert!(recv(&f).starts_with("GET /api/v1/repos "));
        assert_checked_under(&recv(&f), BY_NAME);
    }

    /// An unregistered repo still fails the push, even with nothing to check.
    #[tokio::test]
    async fn an_unregistered_repo_fails_the_push_even_without_sessions() {
        let _env_lock = crate::test_helpers::lock_env_mutation().await;
        let f = fixture(
            false,
            &[],
            vec![crate::test_helpers::http_json("200 OK", "[]")],
        );

        let err = super::check_policies(&f.repo, &f.repo)
            .await
            .expect_err("an unregistered repo must fail the push");
        assert!(err.to_string().contains("'tracing' not found"), "{err}");
    }
}