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
use crate::api_client::ApiClient;
use crate::credentials::resolve_credentials;
use std::fs;
use std::path::Path;
use tracevault_protocol::streaming::StreamEventRequest;

/// Shared spelling of the offline-queue filenames. These are the ONLY place
/// the shape is written down: `commands::stream` builds names from them and
/// this module parses names with them, so the writer and the reader cannot
/// drift apart. Drift would be silent — a name this module fails to classify
/// is skipped, stranding the queue while `status` keeps counting it.
pub(crate) const QUEUE_PREFIX: &str = "pending-";
/// Repo-less queues. Note this EXTENDS `QUEUE_PREFIX`, which is what makes an
/// older CLI skip these files rather than mis-drain them.
pub(crate) const PROJECT_QUEUE_PREFIX: &str = "pending-project-";
pub(crate) const QUEUE_SUFFIX: &str = ".jsonl";

/// Extract the repo id from a per-repo pending queue filename
/// (`pending-<repo_id>.jsonl`). Returns None for anything else (e.g. a legacy
/// `pending.jsonl`).
///
/// Note this also matches a repo-less `pending-project-<uuid>.jsonl` and
/// yields `project-<uuid>`, which is not a UUID. That is deliberate and is
/// what keeps an older CLI from mis-draining those queues; callers here must
/// try [`project_id_from_pending_filename`] FIRST.
pub(crate) fn repo_id_from_pending_filename(name: &str) -> Option<&str> {
    name.strip_prefix(QUEUE_PREFIX)?
        .strip_suffix(QUEUE_SUFFIX)
        .filter(|s| !s.is_empty())
}

/// Extract the project id from a repo-less pending queue filename
/// (`pending-project-<project_id>.jsonl`), written by the stream hook when a
/// session has a project binding but no usable repo binding.
pub(crate) fn project_id_from_pending_filename(name: &str) -> Option<&str> {
    name.strip_prefix(PROJECT_QUEUE_PREFIX)?
        .strip_suffix(QUEUE_SUFFIX)
        .filter(|s| !s.is_empty())
}

/// Which endpoint a pending queue file drains to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum QueueTarget {
    Repo(String),
    Project(uuid::Uuid),
}

/// Classify one directory entry's filename into a queue target. Project
/// queues are tested first: `pending-project-<uuid>.jsonl` also satisfies the
/// repo pattern (yielding a non-UUID `project-<uuid>`), so checking repo
/// first would reject it outright and strand the queue.
pub(crate) fn queue_target_from_filename(name: &str) -> Option<QueueTarget> {
    if let Some(pid) = project_id_from_pending_filename(name) {
        return uuid::Uuid::parse_str(pid).ok().map(QueueTarget::Project);
    }
    let repo_id = repo_id_from_pending_filename(name)?;
    // Validate repo_id is a UUID (guards against corrupted/hand-created files)
    uuid::Uuid::parse_str(repo_id).ok()?;
    Some(QueueTarget::Repo(repo_id.to_string()))
}

/// Classify a session dir's pending queue files. Returns
/// `(path, QueueTarget)` pairs: per-repo and repo-less project files each
/// carry their own id (see [`queue_target_from_filename`]), and the legacy
/// `pending.jsonl` is attributed to `bound_repo_id` (skipped entirely when
/// None). Files whose embedded id is not a valid UUID are excluded.
fn pending_queues_in(
    session_dir: &Path,
    bound_repo_id: Option<&str>,
) -> std::io::Result<Vec<(std::path::PathBuf, QueueTarget)>> {
    // A queue another reader claimed and never finished (a flush that was
    // interrupted, a hook that was killed) is listed under the queue it was
    // claimed from, which may itself be gone: draining that queue takes the
    // claim over (see `crate::pending_queue::claim`).
    let mut seen = std::collections::HashSet::new();
    let mut pending_queues: Vec<(std::path::PathBuf, QueueTarget)> = fs::read_dir(session_dir)?
        .filter_map(|e| e.ok())
        .filter_map(|e| {
            let path = crate::pending_queue::queue_of(&e.path())?;
            let name = path.file_name()?.to_str()?.to_string();
            let target = queue_target_from_filename(&name)?;
            seen.insert(path.clone()).then_some((path, target))
        })
        .collect();

    // Back-compat: releases before per-repo queue files existed wrote a
    // single `pending.jsonl`, implicitly attributed to the bound
    // `config.repo_id`. `status` counts these, so `flush` must be able to
    // drain them or they're stuck forever. If there's no bound repo_id,
    // skip it — there's nothing to attribute it to (best-effort).
    // Also when it exists only as a claim an interrupted reader left.
    let legacy_path = session_dir.join("pending.jsonl");
    let legacy_exists = fs::read_dir(session_dir)?
        .filter_map(|e| e.ok())
        .any(|e| crate::pending_queue::queue_of(&e.path()).as_ref() == Some(&legacy_path));
    if legacy_exists {
        if let Some(repo_id) = bound_repo_id {
            pending_queues.push((legacy_path, QueueTarget::Repo(repo_id.to_string())));
        }
    }

    Ok(pending_queues)
}

/// The progress line uses a short prefix of the session id for display; guards
/// against a prior `[..8]` panic on session ids shorter than 8 bytes.
fn display_prefix(id: &str) -> &str {
    id.get(..8).unwrap_or(id)
}

/// The attribution force a whole queue declares on the wire, resolved once
/// per queue (not per event: it reads the environment and parses an RFC3339
/// timestamp). The whole [`crate::commands::stream::AttributionForce`]
/// rather than just its mode, for the same reason the live path carries it:
/// a refusal has to name the force source it tells the operator to remove.
///
/// Both queue kinds read it off the capture binding [`queue_capture_binding`]
/// resolved — the same binding, and therefore the same rule, the live send
/// path applies in `commands::stream::send_stream_event`.
///
/// A repo queue sends under whatever project that binding names, so the
/// binding speaks for it unconditionally. A repo-less queue is keyed by a
/// project id of its own (`pending-project-<uuid>.jsonl`), fixed when its
/// events were buffered, so the binding speaks for it only while it still
/// resolves to THAT SAME project: `forced_until` is stored PER-BINDING (see
/// that field's own doc comment), and applying a force resolved for some
/// other project to this queue would be exactly the leak
/// `attribution_mode`'s binding-scoping exists to prevent (see
/// `attribution_mode`'s doc comment for the two-sided bug that motivated
/// this).
fn queue_attribution_force(
    target: &QueueTarget,
    capture_binding: Option<&crate::session_state::ProjectBinding>,
) -> crate::commands::stream::AttributionForce {
    let speaks_for_this_queue = match target {
        QueueTarget::Repo(_) => capture_binding,
        QueueTarget::Project(pid) => {
            capture_binding.filter(|b| crate::resolution::capture_project_id(b) == Some(*pid))
        }
    };
    crate::commands::stream::attribution_force(speaks_for_this_queue)
}

/// How long `flush` keeps sending the unread rest of one session's
/// transcripts. It is run by hand, with no hook timeout over it.
const REPLAY_BUDGET: std::time::Duration = std::time::Duration::from_secs(300);

/// What happened to one queued event on its way back to the server.
#[derive(Debug)]
pub(crate) enum QueuedSend {
    Sent,
    /// 413 even after truncation. Kept in the queue: its lines are nowhere
    /// else, and the limit may be a proxy's that later changes.
    TooLarge,
    /// Transient (5xx, network, 401, ...) — re-enqueue and retry later.
    Failed(String),
    /// The server deterministically refused the declared capture project
    /// (400/403/404/409 on the project-scoped send). The rest of the queue
    /// cannot succeed against the same binding, and sending the event
    /// anywhere else would re-attribute it, so the caller stops draining.
    Refused {
        pid: uuid::Uuid,
        kind: crate::commands::stream::ClientErrorKind,
    },
}

/// The capture BINDING a queue's events are sent under, resolved exactly as
/// the stream hook resolves it: the session's state (`session_state::load`,
/// keyed by the session directory's name) plus the worktree toplevel the hook
/// recorded in the session dir's `origin` marker (see `run_stream`).
///
/// Resolved the same way for BOTH queue kinds: nothing here needs the target.
/// The whole chain runs off `session_dir` alone — the session id is its file
/// name, the worktree override its `origin` marker, and
/// `commands::stream::capture_binding` takes no repo at all. Which endpoint
/// the queue then drains to is [`send_queued_event`]'s decision, and what the
/// binding is allowed to say about a repo-less queue is
/// [`queue_attribution_force`]'s.
///
/// Without this, `flush` would drain a repo queue to the repo-scoped endpoint
/// and let the server deduce a project, re-attributing the very events the
/// hook queued because the server REFUSED the declared project.
///
/// The whole binding, not just its id: its `forced_until` is what
/// [`queue_attribution_force`] reads, so a flushed event declares the same
/// attribution mode the live send would have (see
/// `commands::stream::attribution_mode` for why the force must come from the
/// binding that actually won, and no other).
fn queue_capture_binding(session_dir: &Path) -> Option<crate::session_state::ProjectBinding> {
    let session_id = session_dir.file_name()?.to_str()?;
    let session = crate::session_state::load(session_id);
    // Trimmed like the other `origin` readers (`check`, `verification_phase`):
    // the hook writes no trailing newline today, but a hand-edited marker
    // must not silently miss the subagent worktree override.
    let worktree = fs::read_to_string(session_dir.join("origin"))
        .ok()
        .map(|s| s.trim().to_string());
    let config_project = match worktree.as_deref() {
        Some(origin) if !origin.is_empty() => origin_config_project(Path::new(origin)),
        _ => session_dir_config_project(session_dir),
    };
    crate::commands::stream::capture_binding(&session, worktree.as_deref(), config_project)
}

/// The workspace project tier the stream hook read for the event whose
/// worktree it recorded in `origin`: the hook loads the config at
/// `resolve_project_root(event cwd)`, and `origin` is that cwd's worktree
/// toplevel (the cwd itself outside git), which resolves to the same root.
/// Preferred over the session dir's own root because a session's dir is
/// anchored where it STARTED (VIS-1257) — an umbrella — while a later event
/// may have come from a checkout below it, whose config the hook read instead.
fn origin_config_project(origin: &Path) -> Option<crate::session_state::ProjectBinding> {
    let root = crate::paths::resolve_project_root(origin).root;
    crate::config::TracevaultConfig::load(&root)
        .as_ref()
        .and_then(crate::resolution::project_from_config)
}

/// The workspace project tier (`.visdom/tracing.toml` `project_id`) of the
/// project root a session directory lives under
/// (`<root>/.visdom/sessions/<id>`), for a session dir with no `origin`
/// marker. `None` when the layout does not match or the config has none.
fn session_dir_config_project(session_dir: &Path) -> Option<crate::session_state::ProjectBinding> {
    let root = crate::layout::session_dir_root(session_dir)?;
    crate::config::TracevaultConfig::load(root)
        .as_ref()
        .and_then(crate::resolution::project_from_config)
}

/// Send one queued event to the endpoint its queue and the session's capture
/// project select: a repo queue with a capture project goes to the
/// project-scoped endpoint carrying the repo id, one without goes to the
/// repo-scoped endpoint (the server deduces). A refused project-scoped send
/// is reported as [`QueuedSend::Refused`] and is never retried at the
/// repo-scoped endpoint — that would be the silent re-attribution VIS-316
/// removes. A repo-less queue drains to the project endpoint with no repo id,
/// the same shape the stream hook buffered it as, and keeps its old rules.
///
/// `force` is the queue's attribution force ([`queue_attribution_force`]);
/// its mode goes on every project-scoped send as the
/// `x-tracevault-project-attribution` header, so a flushed event declares
/// exactly what the live send would have.
pub(crate) async fn send_queued_event(
    client: &ApiClient,
    target: &QueueTarget,
    capture_pid: Option<uuid::Uuid>,
    force: crate::commands::stream::AttributionForce,
    event: &StreamEventRequest,
) -> QueuedSend {
    let (sent, refusable_pid) = match (target, capture_pid) {
        (QueueTarget::Repo(repo_id), None) => (client.stream_event(repo_id, event).await, None),
        (QueueTarget::Repo(repo_id), Some(pid)) => (
            client
                .stream_event_for_project(pid, Some(repo_id), force.mode(), event)
                .await,
            Some(pid),
        ),
        (QueueTarget::Project(pid), _) => (
            client
                .stream_event_for_project(*pid, None, force.mode(), event)
                .await,
            None,
        ),
    };
    let e = match sent {
        Ok(_) => return QueuedSend::Sent,
        Err(e) => e,
    };
    // Refusal is checked BEFORE the 413 rule: that rule is a bare substring
    // match, and a refusal's body can name a UUID that contains "413".
    if let Some(pid) = refusable_pid {
        if let Some(kind) = crate::commands::stream::deterministic_client_error_kind(e.as_ref()) {
            return QueuedSend::Refused { pid, kind };
        }
    }
    let err_str = e.to_string();
    if err_str.contains("413") {
        QueuedSend::TooLarge
    } else {
        QueuedSend::Failed(err_str)
    }
}

/// Drain one queue file: send each event, re-enqueue whatever must be
/// retried (in order, to the SAME file), and return `(sent, failed)`. A
/// refusal stops the drain: its line is printed once, and the refused event
/// plus every event not yet attempted are re-enqueued and counted failed.
async fn drain_queue(
    client: &ApiClient,
    pending_path: &Path,
    target: &QueueTarget,
    capture_pid: Option<uuid::Uuid>,
    force: crate::commands::stream::AttributionForce,
) -> Result<(u64, u64), Box<dyn std::error::Error>> {
    // A queue an earlier release wrote can repeat the session's transcript
    // many times over; drop that first, one record at a time, before the
    // queue is loaded whole (see `crate::pending_queue`).
    if let Some(session_dir) = pending_path.parent() {
        crate::pending_queue::upgrade(session_dir)?;
    }
    // Claimed and read one record at a time, like a hook does: a queue's
    // lines are nowhere else (the transcript's read offset is past them), so
    // nothing may be held only in memory. What is not sent goes back to the
    // queue as it is reached, and a flush that is interrupted leaves its
    // claim for the next reader to take over.
    let claimed = crate::pending_queue::claim(pending_path)?;
    if claimed.is_empty() {
        return Ok((0, 0));
    }

    let mut sent = 0u64;
    let mut failed = 0u64;
    // Where the drain stopped, when it did: from there on the claim's
    // records stay queued as they are (see `Claimed::finish`).
    let mut rest = None;

    // Label the progress and warning lines with the session directory the
    // queue lives in. It is the same id the hook stamped on every event here
    // (`run_stream` writes the queue under `.visdom/sessions/<id>/`), but
    // taken from the path rather than the payload: the label is a directory
    // name, not data read out of the event.
    let queue_dir_name = pending_path
        .parent()
        .and_then(|d| d.file_name())
        .and_then(|n| n.to_str())
        .unwrap_or("?");

    let mut reader = claimed.reader();
    let mut n = 0u64;
    while let Some(record) = reader.next_record()? {
        let mut event = match serde_json::from_str::<StreamEventRequest>(&record) {
            Ok(event) => event,
            Err(e) => {
                eprintln!("Warning: skipping malformed pending event: {e}");
                continue;
            }
        };
        n += 1;
        eprint!(
            "\r  Session {} — event {n} ...",
            display_prefix(queue_dir_name),
        );
        event.truncate_large_fields();
        match send_queued_event(client, target, capture_pid, force, &event).await {
            QueuedSend::Sent => sent += 1,
            QueuedSend::TooLarge => {
                // Too large even after truncation. Kept as it was queued: a
                // hook moved the transcript's offset past its lines, so no
                // later read brings them back.
                eprintln!();
                eprintln!(
                    "  Warning: event kept in the queue (session {queue_dir_name}) — the server finds it too large"
                );
                crate::pending_queue::requeue(pending_path, &record)?;
                failed += 1;
            }
            QueuedSend::Failed(e) => {
                eprintln!();
                eprintln!("  Warning: failed to send event (session {queue_dir_name}): {e}");
                crate::pending_queue::requeue(pending_path, &serde_json::to_string(&event)?)?;
                failed += 1;
            }
            QueuedSend::Refused { pid, kind } => {
                eprintln!();
                eprintln!(
                    "{}",
                    crate::commands::stream::refused_error(pid, &kind, force)
                );
                // The refused event and the untried rest stay queued and
                // are failed, like the earlier failures.
                rest = Some(reader.before_last());
                failed += 1;
                while reader.next_record()?.is_some() {
                    failed += 1;
                }
                break;
            }
        }
    }
    eprintln!();
    drop(reader);
    claimed.finish(rest, pending_path)?;
    Ok((sent, failed))
}

pub async fn run_flush(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
    let (server_url, credential) = resolve_credentials(project_root)?;
    let server_url = server_url.ok_or("server_url not configured")?;
    let client = ApiClient::with_credential(&server_url, credential);

    // Lenient config load: used only to attribute the legacy `pending.jsonl`
    // (written by releases before per-repo queue files existed) to the bound
    // repo id, if any. Best-effort — a missing/malformed config just means
    // any legacy queue can't be attributed and is left in place.
    let bound_repo_id = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.repo_id);

    let sessions_dirs = crate::layout::existing_sessions_dirs(project_root);
    if sessions_dirs.is_empty() {
        println!("No sessions directory found. Nothing to flush.");
        return Ok(());
    }

    let mut total_sent = 0u64;
    let mut total_failed = 0u64;
    let mut caught_up = 0u64;
    let mut not_caught_up = 0u64;

    let session_entries: Vec<_> = sessions_dirs
        .iter()
        .map(fs::read_dir)
        .collect::<Result<Vec<_>, _>>()?
        .into_iter()
        .flatten()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().is_dir())
        .collect();

    for session_entry in session_entries {
        let session_dir = session_entry.path();
        // Collect (path, QueueTarget) pairs for every pending queue in this
        // session directory before draining, to keep the borrow/async loop
        // below simple.
        let pending_queues = pending_queues_in(&session_dir, bound_repo_id.as_deref())?;

        for (pending_path, target) in pending_queues {
            // Resolved once per queue, not per event — the force read costs
            // an env read and an RFC3339 parse.
            let capture_binding = queue_capture_binding(&session_dir);
            let capture_pid = capture_binding
                .as_ref()
                .and_then(crate::resolution::capture_project_id);
            let force = queue_attribution_force(&target, capture_binding.as_ref());
            let (sent, failed) =
                drain_queue(&client, &pending_path, &target, capture_pid, force).await?;
            total_sent += sent;
            total_failed += failed;
        }

        // Then what the session's transcripts hold that no hook read: the
        // queue is not the only place unsent lines wait (see `send_rest`).
        let deadline = std::time::Instant::now() + REPLAY_BUDGET;
        match crate::commands::catch_up::send_rest(project_root, &session_dir, deadline).await {
            Some(crate::commands::stream::Sent::Accepted) => caught_up += 1,
            Some(crate::commands::stream::Sent::Queued) => not_caught_up += 1,
            Some(crate::commands::stream::Sent::Skipped) | None => {}
        }
    }

    println!("Flush complete: {total_sent} sent, {total_failed} failed");
    if caught_up + not_caught_up > 0 {
        println!(
            "Transcripts: the unread rest of {caught_up} session(s) sent, of {not_caught_up} not"
        );
    }
    Ok(())
}

/// Write events to a queue file.
#[cfg(test)]
fn append_pending(
    path: &Path,
    events: &[StreamEventRequest],
) -> Result<(), Box<dyn std::error::Error>> {
    use std::io::Write;
    let mut file = fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;

    for event in events {
        let json = serde_json::to_string(event)?;
        writeln!(file, "{json}")?;
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::{display_prefix, pending_queues_in, repo_id_from_pending_filename, QueueTarget};
    use crate::paths::resolve_project_root;
    use crate::test_helpers::{add_worktree, init_git_repo};
    use std::fs;

    #[test]
    fn repo_id_from_pending_filename_extracts_id() {
        assert_eq!(
            repo_id_from_pending_filename("pending-abc.jsonl"),
            Some("abc")
        );
    }

    #[test]
    fn repo_id_from_pending_filename_none_for_legacy_name() {
        assert_eq!(repo_id_from_pending_filename("pending.jsonl"), None);
    }

    #[test]
    fn repo_id_from_pending_filename_none_for_unrelated_name() {
        assert_eq!(repo_id_from_pending_filename("events.jsonl"), None);
        assert_eq!(repo_id_from_pending_filename("pending-abc.txt"), None);
    }

    #[test]
    fn repo_id_from_pending_filename_none_for_empty_id() {
        assert_eq!(repo_id_from_pending_filename("pending-.jsonl"), None);
    }

    /// From a sibling worktree the resolved project root must point at the
    /// PRIMARY checkout, so `flush` looks for sessions under
    /// `<primary>/.visdom/sessions/` rather than a non-existent sibling dir.
    ///
    /// This test asserts only the resolution layer — draining the queue requires
    /// a live server, so the full end-to-end drain path is not exercised here.
    #[test]
    fn sessions_dir_from_sibling_worktree_is_under_primary() {
        let tmp = tempfile::tempdir().unwrap();
        let repo = tmp.path().join("repo");
        let wt = tmp.path().join("sibling-wt");

        fs::create_dir_all(&repo).unwrap();
        init_git_repo(&repo);
        add_worktree(&repo, &wt);

        // Place a pending.jsonl in the primary sessions dir.
        let session_id = "aabbccdd-0000-0000-0000-000000000001";
        let sessions_dir = repo.join(".visdom").join("sessions").join(session_id);
        fs::create_dir_all(&sessions_dir).unwrap();
        fs::write(sessions_dir.join("pending.jsonl"), "").unwrap();

        // Simulate what main.rs now does: resolve from the SIBLING worktree cwd.
        let resolved_root = resolve_project_root(&wt).root;
        let expected_sessions = repo
            .canonicalize()
            .unwrap()
            .join(".visdom")
            .join("sessions");
        let got_sessions = resolved_root
            .canonicalize()
            .unwrap()
            .join(".visdom")
            .join("sessions");

        assert_eq!(
            got_sessions, expected_sessions,
            "flush must look for sessions under the PRIMARY repo, not the sibling worktree dir"
        );
    }

    // ── pending_queues_in: per-session pending-queue enumeration ─────────────

    fn setup_session_dir_with_pending_files() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        fs::write(
            dir.path()
                .join("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl"),
            "",
        )
        .unwrap();
        fs::write(
            dir.path()
                .join("pending-550e8400-e29b-41d4-a716-446655440000.jsonl"),
            "",
        )
        .unwrap();
        fs::write(dir.path().join("pending.jsonl"), "").unwrap();
        fs::write(dir.path().join("notes.txt"), "").unwrap();
        fs::write(dir.path().join("pending-.jsonl"), "").unwrap();
        fs::write(dir.path().join("pending-not-a-uuid.jsonl"), "").unwrap();
        // A repo-less session's queue, written by the stream hook when only a
        // project binding resolved.
        fs::write(
            dir.path()
                .join("pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"),
            "",
        )
        .unwrap();
        dir
    }

    /// Render a classified target as a sortable label so the assertions below
    /// can compare whole queue sets, and so a repo queue and a project queue
    /// that happened to share an id would still be distinguishable.
    fn label(t: &QueueTarget) -> String {
        match t {
            QueueTarget::Repo(id) => id.clone(),
            QueueTarget::Project(id) => format!("project:{id}"),
        }
    }

    fn sorted_labels(got: &[(std::path::PathBuf, QueueTarget)]) -> Vec<String> {
        let mut v: Vec<String> = got.iter().map(|(_, t)| label(t)).collect();
        v.sort();
        v
    }

    #[test]
    fn pending_queues_in_with_bound_repo_includes_legacy() {
        let dir = setup_session_dir_with_pending_files();
        let got =
            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
        assert_eq!(
            sorted_labels(&got),
            vec![
                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
                "550e8400-e29b-41d4-a716-446655440000",
                "550e8400-e29b-41d4-a716-446655440001",
                "project:018f0000-0000-7000-8000-000000000abc",
            ]
        );

        let legacy = got
            .iter()
            .find(|(_, t)| matches!(t, QueueTarget::Repo(id) if id == "550e8400-e29b-41d4-a716-446655440001"))
            .unwrap();
        assert_eq!(legacy.0, dir.path().join("pending.jsonl"));
    }

    #[test]
    fn pending_queues_in_without_bound_repo_skips_legacy() {
        let dir = setup_session_dir_with_pending_files();
        let got = pending_queues_in(dir.path(), None).unwrap();
        assert_eq!(
            sorted_labels(&got),
            vec![
                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
                "550e8400-e29b-41d4-a716-446655440000",
                "project:018f0000-0000-7000-8000-000000000abc",
            ]
        );
    }

    #[test]
    fn pending_queues_in_ignores_unrelated_and_malformed_names() {
        let dir = setup_session_dir_with_pending_files();
        let got =
            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();

        assert!(!got.iter().any(|(p, _)| p.ends_with("notes.txt")));
        assert!(!got.iter().any(|(p, _)| p.ends_with("pending-.jsonl")));
        // Non-UUID repo_ids are silently skipped (guards against corrupted files)
        assert!(!got
            .iter()
            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
    }

    #[test]
    fn pending_queues_in_validates_uuid_in_per_repo_files() {
        let dir = setup_session_dir_with_pending_files();
        let got = pending_queues_in(dir.path(), None).unwrap();

        // Valid UUIDs are included
        assert!(got
            .iter()
            .any(|(p, _)| p.ends_with("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl")));
        assert!(got
            .iter()
            .any(|(p, _)| p.ends_with("pending-550e8400-e29b-41d4-a716-446655440000.jsonl")));
        // Non-UUID files are NOT included
        assert!(!got
            .iter()
            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
    }

    // ── display_prefix: display-only truncation, no panic on short ids ─────

    #[test]
    fn display_prefix_truncates_long_id() {
        assert_eq!(
            display_prefix("0190a1b2-cccc-dddd-eeee-ffffffffffff"),
            "0190a1b2"
        );
    }

    #[test]
    fn display_prefix_returns_whole_string_when_shorter_than_8() {
        assert_eq!(display_prefix("x"), "x");
    }

    #[test]
    fn display_prefix_handles_empty_string() {
        assert_eq!(display_prefix(""), "");
    }
}

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

    /// A repo-less queue must classify as a PROJECT target. The repo pattern
    /// also matches this filename (yielding `project-<uuid>`), so ordering
    /// inside `queue_target_from_filename` is what makes this pass.
    #[test]
    fn project_queue_classifies_as_project_not_repo() {
        let pid = uuid::Uuid::new_v4();
        assert_eq!(
            queue_target_from_filename(&format!("pending-project-{pid}.jsonl")),
            Some(QueueTarget::Project(pid))
        );
    }

    #[test]
    fn repo_queue_still_classifies_as_repo() {
        let repo = uuid::Uuid::new_v4();
        assert_eq!(
            queue_target_from_filename(&format!("pending-{repo}.jsonl")),
            Some(QueueTarget::Repo(repo.to_string()))
        );
    }

    /// The writer (`Attribution::pending_file_name`, in `commands::stream`)
    /// and the reader (`queue_target_from_filename`, here) are the two halves
    /// of one format that live in different modules. Nothing else fails if
    /// they diverge — an unparsable name is silently skipped, stranding the
    /// queue while `status` still counts it — so pin the round trip.
    #[test]
    fn every_attribution_round_trips_through_its_queue_filename() {
        use crate::commands::stream::Attribution;

        let repo = uuid::Uuid::new_v4();
        assert_eq!(
            queue_target_from_filename(
                &Attribution::Repo {
                    repo_id: repo.to_string(),
                    project: Some(uuid::Uuid::new_v4()),
                }
                .pending_file_name()
            ),
            Some(QueueTarget::Repo(repo.to_string())),
            "a repo queue must classify back to the same repo"
        );

        let pid = uuid::Uuid::new_v4();
        assert_eq!(
            queue_target_from_filename(
                &Attribution::ProjectOnly { project_id: pid }.pending_file_name()
            ),
            Some(QueueTarget::Project(pid)),
            "a repo-less queue must classify back to the same project, NOT to a repo"
        );
    }

    /// Traversal-shaped names are rejected by the UUID parse on both arms.
    /// `pending_queues_in` builds its paths from `fs::read_dir`, which never
    /// yields `.` or `..` as entries, so a traversal component cannot reach
    /// here in the first place — this pins the second line of defence, the
    /// one that would still hold if the source of the names ever changed.
    #[test]
    fn traversal_shaped_names_are_rejected() {
        for name in [
            "pending-../../etc/passwd.jsonl",
            "pending-project-../../etc/passwd.jsonl",
            "pending-..%2f..%2fetc.jsonl",
            "pending-/etc/passwd.jsonl",
        ] {
            assert_eq!(queue_target_from_filename(name), None, "accepted: {name}");
        }
    }

    /// Non-UUID ids are rejected on both arms — these names can only come
    /// from a corrupted or hand-created file.
    #[test]
    fn non_uuid_ids_are_rejected() {
        assert_eq!(queue_target_from_filename("pending-nope.jsonl"), None);
        assert_eq!(
            queue_target_from_filename("pending-project-nope.jsonl"),
            None
        );
        assert_eq!(queue_target_from_filename("pending-.jsonl"), None);
        assert_eq!(queue_target_from_filename("pending.jsonl"), None);
    }
}

/// VIS-316: `flush` must drain a repo queue under the session's capture
/// project, never re-attributing a refused event via the repo-scoped endpoint.
#[cfg(test)]
mod send_tests {
    use super::*;
    use crate::api_client::AttributionMode;
    use crate::commands::stream::AttributionForce;
    use crate::test_helpers::{http_json, lock_env_mutation, spawn_seq, EnvVarGuard, RECV_TIMEOUT};
    use std::path::PathBuf;
    use std::time::Duration;
    use tracevault_protocol::streaming::StreamEventType;

    const REPO: &str = "11111111-1111-1111-1111-111111111111";

    fn event(n: u128) -> StreamEventRequest {
        StreamEventRequest {
            protocol_version: 1,
            tool: Some("claude-code".to_string()),
            event_type: StreamEventType::ToolUse,
            session_id: "sess-flush".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: Some(uuid::Uuid::from_u128(n)),
            transcript_lines: None,
            transcript_offset: None,
            model: None,
            cwd: None,
            final_stats: None,
            flow_id: None,
            labels: None,
            params: None,
            billing_mode: None,
        }
    }

    fn ok() -> 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();
        http_json("200 OK", &body)
    }

    fn bad_request() -> String {
        http_json(
            "400 Bad Request",
            r#"{"error":"repo is not a member of project"}"#,
        )
    }

    /// The request line of a captured request (`spawn_seq` renders
    /// `"<request line> | <headers> | <body>"`).
    fn request_line(captured: &str) -> &str {
        captured.split(" | ").next().unwrap_or_default()
    }

    /// Event uuids held by a queue file, in order; every line must parse.
    fn queued_uuids(path: &Path) -> Vec<uuid::Uuid> {
        fs::read_to_string(path)
            .unwrap()
            .lines()
            .filter(|l| !l.trim().is_empty())
            .map(|l| {
                serde_json::from_str::<StreamEventRequest>(l)
                    .expect("every queued line parses")
                    .event_uuid
                    .unwrap()
            })
            .collect()
    }

    #[tokio::test]
    async fn repo_queue_with_capture_project_goes_to_the_project_endpoint() {
        let (base, rx) = spawn_seq(vec![ok()]);
        let client = ApiClient::new(&base, Some("tok"));
        let pid = uuid::Uuid::from_u128(0xA);

        let got = send_queued_event(
            &client,
            &QueueTarget::Repo(REPO.into()),
            Some(pid),
            AttributionForce::default(),
            &event(1),
        )
        .await;
        assert!(matches!(got, QueuedSend::Sent), "{got:?}");

        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            request_line(&captured).starts_with(&format!(
                "POST /api/v1/projects/{pid}/stream?repo_id={REPO} "
            )),
            "got: {captured}"
        );
    }

    /// VIS-305: a flushed event declares the SAME attribution mode the live
    /// send would have. `queue_attribution_force` reads it off the capture
    /// binding that decided the repo queue's project — so a live
    /// `forced_until` on that binding must reach the wire as `explicit`, and
    /// an unforced one as `derived`. Without this, a queued event would
    /// silently downgrade to membership-checked attribution on drain.
    #[tokio::test]
    async fn repo_queue_declares_the_capture_bindings_attribution_mode() {
        let _env_lock = lock_env_mutation().await;
        let mut guard = EnvVarGuard::new();
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let pid = uuid::Uuid::from_u128(0xF);
        let forced = crate::session_state::ProjectBinding {
            project_id: pid.to_string(),
            project_name: "p".into(),
            updated_at: String::new(),
            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
        };
        let unforced = crate::session_state::ProjectBinding {
            forced_until: None,
            ..forced.clone()
        };
        let target = QueueTarget::Repo(REPO.into());

        for (binding, expected) in [
            (&forced, AttributionMode::Explicit),
            (&unforced, AttributionMode::Derived),
        ] {
            let force = queue_attribution_force(&target, Some(binding));
            assert_eq!(force.mode(), expected, "mode for {binding:?}");

            let (base, rx) = spawn_seq(vec![ok()]);
            let client = ApiClient::new(&base, Some("tok"));
            let got = send_queued_event(&client, &target, Some(pid), force, &event(1)).await;
            assert!(matches!(got, QueuedSend::Sent), "{got:?}");

            let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
            assert!(
                captured
                    .to_lowercase()
                    .contains(&format!("x-tracevault-project-attribution: {expected}")),
                "got: {captured}"
            );
        }
    }

    /// Seed a session whose `active_project` is `pid`, forced until `forced`,
    /// and hand back the session directory `flush` would resolve it from.
    /// The directory is deliberately EMPTY apart from its name: that name is
    /// the session id, and it is the only input `queue_capture_binding` needs.
    fn seed_forced_session(
        state_root: &Path,
        session_id: &str,
        pid: uuid::Uuid,
        forced: Option<String>,
    ) -> PathBuf {
        crate::session_state::save(
            session_id,
            &crate::session_state::SessionState {
                active_project: Some(crate::session_state::ProjectBinding {
                    project_id: pid.to_string(),
                    project_name: "p".into(),
                    updated_at: String::new(),
                    forced_until: forced,
                }),
                ..Default::default()
            },
        )
        .unwrap();
        let session_dir = state_root.join("sessions").join(session_id);
        fs::create_dir_all(&session_dir).unwrap();
        session_dir
    }

    fn in_four_hours() -> String {
        (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()
    }

    /// VIS-305: a repo-LESS queue resolves the SAME capture binding a repo
    /// queue does, so a SESSION-scoped force reaches the wire when that queue
    /// is drained.
    ///
    /// `queue_capture_binding` derives everything from the session directory
    /// — the session id is its name, the worktree override its `origin`
    /// marker, and `commands::stream::capture_binding` takes no repo at all
    /// — so nothing about a project queue makes the binding unrecoverable.
    /// An earlier version early-returned `None` for a non-repo target and
    /// consulted only the user-level default, which made a session-scoped
    /// force (the ordinary case whenever a session id is set) invisible: the
    /// header silently downgraded to `derived` on drain.
    #[tokio::test]
    async fn project_queue_honours_a_session_scoped_force() {
        let _env_lock = lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut guard = EnvVarGuard::new();
        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
        guard.set("HOME", tmp.path());
        // Both are read ABOVE the session binding this test pins (and the
        // second would decide the header outright).
        guard.remove("TRACEVAULT_PROJECT");
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let pid = uuid::Uuid::from_u128(0xA1);
        let session_dir = seed_forced_session(
            &tmp.path().join("state"),
            "flush-project-force",
            pid,
            Some(in_four_hours()),
        );

        let binding = queue_capture_binding(&session_dir);
        let want = pid.to_string();
        assert_eq!(
            binding.as_ref().map(|b| b.project_id.as_str()),
            Some(want.as_str()),
            "a project queue's binding is recoverable from the session dir alone"
        );

        let target = QueueTarget::Project(pid);
        let force = queue_attribution_force(&target, binding.as_ref());
        assert_eq!(
            force.mode(),
            AttributionMode::Explicit,
            "a live session force must not be dropped"
        );

        let (base, rx) = spawn_seq(vec![ok()]);
        let client = ApiClient::new(&base, Some("tok"));
        let got = send_queued_event(&client, &target, None, force, &event(1)).await;
        assert!(matches!(got, QueuedSend::Sent), "{got:?}");
        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            captured
                .to_lowercase()
                .contains("x-tracevault-project-attribution: explicit"),
            "got: {captured}"
        );
    }

    /// VIS-1256: a queue under a workspace directory recovers the workspace
    /// tier (`.visdom/tracing.toml` `project_id` at the session dir's
    /// root) exactly as the live send did, and drains a repo queue to the
    /// project-scoped endpoint carrying the repo id. A session dir outside
    /// the `<root>/.visdom/sessions/<id>` layout has no config tier.
    #[tokio::test]
    async fn queue_binding_recovers_the_workspace_project_from_the_session_dir() {
        let _env_lock = lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut guard = EnvVarGuard::new();
        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
        guard.set("HOME", tmp.path());
        guard.remove("TRACEVAULT_PROJECT");
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let pid = uuid::Uuid::from_u128(0x1256);
        let root = tmp.path().join("umbrella");
        let session_dir = root.join(".visdom/sessions/flush-workspace");
        fs::create_dir_all(&session_dir).unwrap();
        fs::write(
            root.join(".visdom/tracing.toml"),
            format!("project_id = \"{pid}\"\nproject_name = \"visdom\"\n"),
        )
        .unwrap();

        let binding = queue_capture_binding(&session_dir).expect("workspace tier recovered");
        assert_eq!(binding.project_id, pid.to_string());

        let repo: uuid::Uuid = REPO.parse().unwrap();
        let target = QueueTarget::Repo(REPO.to_string());
        let force = queue_attribution_force(&target, Some(&binding));
        let (base, rx) = spawn_seq(vec![ok()]);
        let client = ApiClient::new(&base, Some("tok"));
        let got = send_queued_event(&client, &target, Some(pid), force, &event(1)).await;
        assert!(matches!(got, QueuedSend::Sent), "{got:?}");
        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            captured.starts_with(&format!("POST /api/v1/projects/{pid}/stream")),
            "got: {captured}"
        );
        assert!(
            captured.contains(&repo.to_string()),
            "repo id carried: {captured}"
        );

        // Not under `.visdom/sessions/`: no config tier.
        let stray = tmp.path().join("elsewhere/flush-workspace");
        fs::create_dir_all(&stray).unwrap();
        assert_eq!(session_dir_config_project(&stray), None);

        // The dir is anchored at the umbrella (VIS-1257) but the last event
        // came from a checkout below it, recorded in `origin`: the hook read
        // THAT checkout's config (no project_id), so flush must too.
        let child = root.join("child");
        fs::create_dir_all(&child).unwrap();
        crate::test_helpers::init_git_repo(&child);
        fs::write(
            session_dir.join("origin"),
            crate::paths::worktree_toplevel(&child),
        )
        .unwrap();
        assert_eq!(queue_capture_binding(&session_dir), None);
        // ...and from a non-git sub-directory it is the umbrella's again.
        let notes = root.join("notes");
        fs::create_dir_all(&notes).unwrap();
        fs::write(
            session_dir.join("origin"),
            crate::paths::worktree_toplevel(&notes),
        )
        .unwrap();
        assert_eq!(
            queue_capture_binding(&session_dir).map(|b| b.project_id),
            Some(pid.to_string())
        );
    }

    /// The flush-path echo of the "does a force leak onto a different
    /// project" bug, now over the WHOLE precedence chain rather than the
    /// user default alone: a live force on the binding that currently
    /// resolves (project A) must NOT apply to a queue keyed by a DIFFERENT
    /// project B — e.g. the user switched projects since B's events were
    /// buffered.
    #[tokio::test]
    async fn project_queue_does_not_take_a_force_resolved_for_another_project() {
        let _env_lock = lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut guard = EnvVarGuard::new();
        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
        guard.set("HOME", tmp.path());
        guard.remove("TRACEVAULT_PROJECT");
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let project_a = uuid::Uuid::from_u128(0xA);
        let project_b = uuid::Uuid::from_u128(0xB);
        let session_dir = seed_forced_session(
            &tmp.path().join("state"),
            "flush-project-leak",
            project_a,
            Some(in_four_hours()),
        );

        let binding = queue_capture_binding(&session_dir);
        assert_eq!(
            queue_attribution_force(&QueueTarget::Project(project_a), binding.as_ref()).mode(),
            AttributionMode::Explicit,
            "the queue the force was resolved FOR still gets it"
        );
        assert_eq!(
            queue_attribution_force(&QueueTarget::Project(project_b), binding.as_ref()).mode(),
            AttributionMode::Derived,
            "a force resolved for a DIFFERENT project must not leak onto this queue"
        );
    }

    /// The user-level default is the lowest tier of that same chain, so a
    /// force persisted by `project switch --user` still reaches a repo-less
    /// queue keyed by that project — with no session binding in the way.
    #[tokio::test]
    async fn project_queue_honours_a_user_default_force() {
        let _env_lock = lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let mut guard = EnvVarGuard::new();
        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
        guard.set("HOME", tmp.path());
        guard.remove("TRACEVAULT_PROJECT");
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let pid = uuid::Uuid::from_u128(0xC);
        crate::user_project_default::save(&crate::session_state::ProjectBinding {
            project_id: pid.to_string(),
            project_name: "p".into(),
            updated_at: chrono::Utc::now().to_rfc3339(),
            forced_until: Some(in_four_hours()),
        })
        .unwrap();

        // No session state at all: the directory's name resolves to nothing,
        // so the user default is what the chain lands on.
        let session_dir = tmp
            .path()
            .join("state")
            .join("sessions")
            .join("flush-no-session");
        fs::create_dir_all(&session_dir).unwrap();

        let binding = queue_capture_binding(&session_dir);
        assert_eq!(
            queue_attribution_force(&QueueTarget::Project(pid), binding.as_ref()).mode(),
            AttributionMode::Explicit
        );
        assert_eq!(
            queue_attribution_force(
                &QueueTarget::Project(uuid::Uuid::from_u128(0xD)),
                binding.as_ref()
            )
            .mode(),
            AttributionMode::Derived,
            "and still does not leak onto another project's queue"
        );
    }

    #[tokio::test]
    async fn repo_queue_without_capture_project_goes_to_the_repo_endpoint() {
        let (base, rx) = spawn_seq(vec![ok()]);
        let client = ApiClient::new(&base, Some("tok"));

        let got = send_queued_event(
            &client,
            &QueueTarget::Repo(REPO.into()),
            None,
            AttributionForce::default(),
            &event(1),
        )
        .await;
        assert!(matches!(got, QueuedSend::Sent), "{got:?}");

        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            request_line(&captured).starts_with(&format!("POST /api/v1/repos/{REPO}/stream ")),
            "got: {captured}"
        );
    }

    /// A 400 on the project-scoped send is a refusal: exactly one request (a
    /// spare 200 is staged so a repo-scoped retry WOULD be captured), and the
    /// outcome says so, which is what makes `drain_queue` re-enqueue it.
    #[tokio::test]
    async fn refused_project_send_makes_one_request_and_is_classified_refused() {
        use crate::commands::stream::ClientErrorKind;

        let (base, rx) = spawn_seq(vec![bad_request(), ok()]);
        let client = ApiClient::new(&base, Some("tok"));
        let pid = uuid::Uuid::from_u128(0xB);

        let got = send_queued_event(
            &client,
            &QueueTarget::Repo(REPO.into()),
            Some(pid),
            AttributionForce::default(),
            &event(1),
        )
        .await;
        assert!(
            matches!(
                got,
                QueuedSend::Refused { pid: p, kind: ClientErrorKind::Scoping } if p == pid
            ),
            "{got:?}"
        );

        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            request_line(&first).contains(&format!("/projects/{pid}/stream?repo_id={REPO}")),
            "got: {first}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "a refused event must not be re-sent to the repo-scoped endpoint"
        );
    }

    /// A transient failure keeps today's per-event retry: `Failed`, not
    /// `Refused`, so the drain goes on to the next event.
    #[tokio::test]
    async fn transient_project_send_failure_is_not_a_refusal() {
        let (base, _rx) = spawn_seq(vec![http_json("503 Service Unavailable", "{}")]);
        let client = ApiClient::new(&base, Some("tok"));

        let got = send_queued_event(
            &client,
            &QueueTarget::Repo(REPO.into()),
            Some(uuid::Uuid::from_u128(0xC)),
            AttributionForce::default(),
            &event(1),
        )
        .await;
        assert!(matches!(got, QueuedSend::Failed(_)), "{got:?}");
    }

    /// A refusal mid-queue stops the drain: the events already sent stay
    /// sent, and the refused event plus every untried one are re-enqueued in
    /// their original order and counted failed. The third event is never
    /// attempted (the spare response stays unclaimed).
    #[tokio::test]
    async fn drain_queue_stops_at_a_refusal_and_requeues_the_rest_in_order() {
        let (base, rx) = spawn_seq(vec![ok(), bad_request(), ok()]);
        let client = ApiClient::new(&base, Some("tok"));
        let pid = uuid::Uuid::from_u128(0xD);
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join(format!("pending-{REPO}.jsonl"));
        append_pending(&path, &[event(1), event(2), event(3)]).unwrap();

        let (sent, failed) = drain_queue(
            &client,
            &path,
            &QueueTarget::Repo(REPO.into()),
            Some(pid),
            AttributionForce::default(),
        )
        .await
        .unwrap();

        assert_eq!((sent, failed), (1, 2));
        assert_eq!(
            queued_uuids(&path),
            vec![uuid::Uuid::from_u128(2), uuid::Uuid::from_u128(3)]
        );
        for _ in 0..2 {
            let captured = rx.recv_timeout(RECV_TIMEOUT).expect("request missing");
            assert!(
                request_line(&captured).contains(&format!("/projects/{pid}/stream?repo_id=")),
                "got: {captured}"
            );
        }
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "no request after the refusal"
        );
    }

    /// End to end through `run_flush`: the capture project comes from the
    /// session state the hook reads (`XDG_STATE_HOME`, keyed by the session
    /// directory's name), and a refusal leaves every event in the queue.
    #[tokio::test]
    async fn run_flush_applies_the_session_capture_project_and_keeps_refused_events() {
        let _env_lock = lock_env_mutation().await;
        let tmp = tempfile::tempdir().unwrap();
        let root = tmp.path().join("repo");
        let mut guard = EnvVarGuard::new();
        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
        guard.set("HOME", tmp.path());
        // `queue_capture_binding` runs the capture chain, which reads
        // `TRACEVAULT_PROJECT` ABOVE the session-active binding this test
        // pins; an ambient export would redirect the drain at another
        // project. `TRACEVAULT_PROJECT_ATTRIBUTION` would likewise change
        // the header the assertions below do not expect.
        guard.remove("TRACEVAULT_PROJECT");
        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");

        let (base, rx) = spawn_seq(vec![bad_request(), ok()]);
        guard.set("TRACEVAULT_SERVER_URL", &base);
        guard.set("TRACEVAULT_API_KEY", "tvk_test");

        let session_id = "flush-session-1";
        let pid = uuid::Uuid::from_u128(0xE);
        crate::session_state::save(
            session_id,
            &crate::session_state::SessionState {
                active_project: Some(crate::session_state::ProjectBinding {
                    project_id: pid.to_string(),
                    project_name: "p".into(),
                    updated_at: String::new(),
                    forced_until: None,
                }),
                ..Default::default()
            },
        )
        .unwrap();

        let session_dir = root.join(".visdom").join("sessions").join(session_id);
        fs::create_dir_all(&session_dir).unwrap();
        fs::write(
            session_dir.join("origin"),
            root.to_string_lossy().as_bytes(),
        )
        .unwrap();
        let queue = session_dir.join(format!("pending-{REPO}.jsonl"));
        append_pending(&queue, &[event(1), event(2)]).unwrap();

        run_flush(&root).await.unwrap();

        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
        assert!(
            request_line(&first).starts_with(&format!(
                "POST /api/v1/projects/{pid}/stream?repo_id={REPO} "
            )),
            "got: {first}"
        );
        assert!(
            rx.recv_timeout(Duration::from_millis(500)).is_err(),
            "exactly one request: no repo-scoped fallback, no second event"
        );
        assert_eq!(
            queued_uuids(&queue),
            vec![uuid::Uuid::from_u128(1), uuid::Uuid::from_u128(2)]
        );
    }
}