Skip to main content

tracevault_cli/commands/
flush.rs

1use crate::api_client::ApiClient;
2use crate::credentials::resolve_credentials;
3use std::fs;
4use std::io::{BufRead, BufReader, Write};
5use std::path::Path;
6use tracevault_protocol::streaming::StreamEventRequest;
7
8/// Shared spelling of the offline-queue filenames. These are the ONLY place
9/// the shape is written down: `commands::stream` builds names from them and
10/// this module parses names with them, so the writer and the reader cannot
11/// drift apart. Drift would be silent — a name this module fails to classify
12/// is skipped, stranding the queue while `status` keeps counting it.
13pub(crate) const QUEUE_PREFIX: &str = "pending-";
14/// Repo-less queues. Note this EXTENDS `QUEUE_PREFIX`, which is what makes an
15/// older CLI skip these files rather than mis-drain them.
16pub(crate) const PROJECT_QUEUE_PREFIX: &str = "pending-project-";
17pub(crate) const QUEUE_SUFFIX: &str = ".jsonl";
18
19/// Extract the repo id from a per-repo pending queue filename
20/// (`pending-<repo_id>.jsonl`). Returns None for anything else (e.g. a legacy
21/// `pending.jsonl`).
22///
23/// Note this also matches a repo-less `pending-project-<uuid>.jsonl` and
24/// yields `project-<uuid>`, which is not a UUID. That is deliberate and is
25/// what keeps an older CLI from mis-draining those queues; callers here must
26/// try [`project_id_from_pending_filename`] FIRST.
27pub(crate) fn repo_id_from_pending_filename(name: &str) -> Option<&str> {
28    name.strip_prefix(QUEUE_PREFIX)?
29        .strip_suffix(QUEUE_SUFFIX)
30        .filter(|s| !s.is_empty())
31}
32
33/// Extract the project id from a repo-less pending queue filename
34/// (`pending-project-<project_id>.jsonl`), written by the stream hook when a
35/// session has a project binding but no usable repo binding.
36pub(crate) fn project_id_from_pending_filename(name: &str) -> Option<&str> {
37    name.strip_prefix(PROJECT_QUEUE_PREFIX)?
38        .strip_suffix(QUEUE_SUFFIX)
39        .filter(|s| !s.is_empty())
40}
41
42/// Which endpoint a pending queue file drains to.
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub(crate) enum QueueTarget {
45    Repo(String),
46    Project(uuid::Uuid),
47}
48
49/// Classify one directory entry's filename into a queue target. Project
50/// queues are tested first: `pending-project-<uuid>.jsonl` also satisfies the
51/// repo pattern (yielding a non-UUID `project-<uuid>`), so checking repo
52/// first would reject it outright and strand the queue.
53pub(crate) fn queue_target_from_filename(name: &str) -> Option<QueueTarget> {
54    if let Some(pid) = project_id_from_pending_filename(name) {
55        return uuid::Uuid::parse_str(pid).ok().map(QueueTarget::Project);
56    }
57    let repo_id = repo_id_from_pending_filename(name)?;
58    // Validate repo_id is a UUID (guards against corrupted/hand-created files)
59    uuid::Uuid::parse_str(repo_id).ok()?;
60    Some(QueueTarget::Repo(repo_id.to_string()))
61}
62
63/// Classify a session dir's pending queue files. Returns
64/// `(path, QueueTarget)` pairs: per-repo and repo-less project files each
65/// carry their own id (see [`queue_target_from_filename`]), and the legacy
66/// `pending.jsonl` is attributed to `bound_repo_id` (skipped entirely when
67/// None). Files whose embedded id is not a valid UUID are excluded.
68fn pending_queues_in(
69    session_dir: &Path,
70    bound_repo_id: Option<&str>,
71) -> std::io::Result<Vec<(std::path::PathBuf, QueueTarget)>> {
72    let mut pending_queues: Vec<(std::path::PathBuf, QueueTarget)> = fs::read_dir(session_dir)?
73        .filter_map(|e| e.ok())
74        .filter_map(|e| {
75            let path = e.path();
76            let name = path.file_name()?.to_str()?.to_string();
77            Some((path, queue_target_from_filename(&name)?))
78        })
79        .collect();
80
81    // Back-compat: releases before per-repo queue files existed wrote a
82    // single `pending.jsonl`, implicitly attributed to the bound
83    // `config.repo_id`. `status` counts these, so `flush` must be able to
84    // drain them or they're stuck forever. If there's no bound repo_id,
85    // skip it — there's nothing to attribute it to (best-effort).
86    let legacy_path = session_dir.join("pending.jsonl");
87    if legacy_path.exists() {
88        if let Some(repo_id) = bound_repo_id {
89            pending_queues.push((legacy_path, QueueTarget::Repo(repo_id.to_string())));
90        }
91    }
92
93    Ok(pending_queues)
94}
95
96/// The progress line uses a short prefix of the session id for display; guards
97/// against a prior `[..8]` panic on session ids shorter than 8 bytes.
98fn display_prefix(id: &str) -> &str {
99    id.get(..8).unwrap_or(id)
100}
101
102/// The attribution force a whole queue declares on the wire, resolved once
103/// per queue (not per event: it reads the environment and parses an RFC3339
104/// timestamp). The whole [`crate::commands::stream::AttributionForce`]
105/// rather than just its mode, for the same reason the live path carries it:
106/// a refusal has to name the force source it tells the operator to remove.
107///
108/// Both queue kinds read it off the capture binding [`queue_capture_binding`]
109/// resolved — the same binding, and therefore the same rule, the live send
110/// path applies in `commands::stream::send_stream_event`.
111///
112/// A repo queue sends under whatever project that binding names, so the
113/// binding speaks for it unconditionally. A repo-less queue is keyed by a
114/// project id of its own (`pending-project-<uuid>.jsonl`), fixed when its
115/// events were buffered, so the binding speaks for it only while it still
116/// resolves to THAT SAME project: `forced_until` is stored PER-BINDING (see
117/// that field's own doc comment), and applying a force resolved for some
118/// other project to this queue would be exactly the leak
119/// `attribution_mode`'s binding-scoping exists to prevent (see
120/// `attribution_mode`'s doc comment for the two-sided bug that motivated
121/// this).
122fn queue_attribution_force(
123    target: &QueueTarget,
124    capture_binding: Option<&crate::session_state::ProjectBinding>,
125) -> crate::commands::stream::AttributionForce {
126    let speaks_for_this_queue = match target {
127        QueueTarget::Repo(_) => capture_binding,
128        QueueTarget::Project(pid) => {
129            capture_binding.filter(|b| crate::resolution::capture_project_id(b) == Some(*pid))
130        }
131    };
132    crate::commands::stream::attribution_force(speaks_for_this_queue)
133}
134
135/// What happened to one queued event on its way back to the server.
136#[derive(Debug)]
137pub(crate) enum QueuedSend {
138    Sent,
139    /// 413 even after truncation — dropped, never retried.
140    TooLarge,
141    /// Transient (5xx, network, 401, ...) — re-enqueue and retry later.
142    Failed(String),
143    /// The server deterministically refused the declared capture project
144    /// (400/403/404/409 on the project-scoped send). The rest of the queue
145    /// cannot succeed against the same binding, and sending the event
146    /// anywhere else would re-attribute it, so the caller stops draining.
147    Refused {
148        pid: uuid::Uuid,
149        kind: crate::commands::stream::ClientErrorKind,
150    },
151}
152
153/// The capture BINDING a queue's events are sent under, resolved exactly as
154/// the stream hook resolves it: the session's state (`session_state::load`,
155/// keyed by the session directory's name) plus the worktree toplevel the hook
156/// recorded in the session dir's `origin` marker (see `run_stream`).
157///
158/// Resolved the same way for BOTH queue kinds: nothing here needs the target.
159/// The whole chain runs off `session_dir` alone — the session id is its file
160/// name, the worktree override its `origin` marker, and
161/// `commands::stream::capture_binding` takes no repo at all. Which endpoint
162/// the queue then drains to is [`send_queued_event`]'s decision, and what the
163/// binding is allowed to say about a repo-less queue is
164/// [`queue_attribution_force`]'s.
165///
166/// Without this, `flush` would drain a repo queue to the repo-scoped endpoint
167/// and let the server deduce a project, re-attributing the very events the
168/// hook queued because the server REFUSED the declared project.
169///
170/// The whole binding, not just its id: its `forced_until` is what
171/// [`queue_attribution_force`] reads, so a flushed event declares the same
172/// attribution mode the live send would have (see
173/// `commands::stream::attribution_mode` for why the force must come from the
174/// binding that actually won, and no other).
175fn queue_capture_binding(session_dir: &Path) -> Option<crate::session_state::ProjectBinding> {
176    let session_id = session_dir.file_name()?.to_str()?;
177    let session = crate::session_state::load(session_id);
178    // Trimmed like the other `origin` readers (`check`, `verification_phase`):
179    // the hook writes no trailing newline today, but a hand-edited marker
180    // must not silently miss the subagent worktree override.
181    let worktree = fs::read_to_string(session_dir.join("origin"))
182        .ok()
183        .map(|s| s.trim().to_string());
184    crate::commands::stream::capture_binding(&session, worktree.as_deref())
185}
186
187/// Send one queued event to the endpoint its queue and the session's capture
188/// project select: a repo queue with a capture project goes to the
189/// project-scoped endpoint carrying the repo id, one without goes to the
190/// repo-scoped endpoint (the server deduces). A refused project-scoped send
191/// is reported as [`QueuedSend::Refused`] and is never retried at the
192/// repo-scoped endpoint — that would be the silent re-attribution VIS-316
193/// removes. A repo-less queue drains to the project endpoint with no repo id,
194/// the same shape the stream hook buffered it as, and keeps its old rules.
195///
196/// `force` is the queue's attribution force ([`queue_attribution_force`]);
197/// its mode goes on every project-scoped send as the
198/// `x-tracevault-project-attribution` header, so a flushed event declares
199/// exactly what the live send would have.
200pub(crate) async fn send_queued_event(
201    client: &ApiClient,
202    target: &QueueTarget,
203    capture_pid: Option<uuid::Uuid>,
204    force: crate::commands::stream::AttributionForce,
205    event: &StreamEventRequest,
206) -> QueuedSend {
207    let (sent, refusable_pid) = match (target, capture_pid) {
208        (QueueTarget::Repo(repo_id), None) => (client.stream_event(repo_id, event).await, None),
209        (QueueTarget::Repo(repo_id), Some(pid)) => (
210            client
211                .stream_event_for_project(pid, Some(repo_id), force.mode(), event)
212                .await,
213            Some(pid),
214        ),
215        (QueueTarget::Project(pid), _) => (
216            client
217                .stream_event_for_project(*pid, None, force.mode(), event)
218                .await,
219            None,
220        ),
221    };
222    let e = match sent {
223        Ok(_) => return QueuedSend::Sent,
224        Err(e) => e,
225    };
226    // Refusal is checked BEFORE the 413 rule: that rule is a bare substring
227    // match, and a refusal's body can name a UUID that contains "413".
228    if let Some(pid) = refusable_pid {
229        if let Some(kind) = crate::commands::stream::deterministic_client_error_kind(e.as_ref()) {
230            return QueuedSend::Refused { pid, kind };
231        }
232    }
233    let err_str = e.to_string();
234    if err_str.contains("413") {
235        QueuedSend::TooLarge
236    } else {
237        QueuedSend::Failed(err_str)
238    }
239}
240
241/// Drain one queue file: send each event, re-enqueue whatever must be
242/// retried (in order, to the SAME file), and return `(sent, failed)`. A
243/// refusal stops the drain: its line is printed once, and the refused event
244/// plus every event not yet attempted are re-enqueued and counted failed.
245async fn drain_queue(
246    client: &ApiClient,
247    pending_path: &Path,
248    target: &QueueTarget,
249    capture_pid: Option<uuid::Uuid>,
250    force: crate::commands::stream::AttributionForce,
251) -> Result<(u64, u64), Box<dyn std::error::Error>> {
252    let events = drain_pending(pending_path)?;
253    if events.is_empty() {
254        return Ok((0, 0));
255    }
256
257    let event_total = events.len();
258    let mut sent = 0u64;
259    let mut failed = 0u64;
260    let mut failed_events: Vec<StreamEventRequest> = Vec::new();
261
262    // Label the progress and warning lines with the session directory the
263    // queue lives in. It is the same id the hook stamped on every event here
264    // (`run_stream` writes the queue under `.tracevault/sessions/<id>/`), but
265    // taken from the path rather than the payload: the label is a directory
266    // name, not data read out of the event.
267    let queue_dir_name = pending_path
268        .parent()
269        .and_then(|d| d.file_name())
270        .and_then(|n| n.to_str())
271        .unwrap_or("?");
272
273    let mut events = events.into_iter().enumerate();
274    while let Some((i, mut event)) = events.next() {
275        eprint!(
276            "\r  Session {} — event {}/{} ...",
277            display_prefix(queue_dir_name),
278            i + 1,
279            event_total
280        );
281        event.truncate_large_fields();
282        match send_queued_event(client, target, capture_pid, force, &event).await {
283            QueuedSend::Sent => sent += 1,
284            QueuedSend::TooLarge => {
285                // Payload too large even after truncation — drop it.
286                eprintln!();
287                eprintln!(
288                    "  Warning: dropped event (session {queue_dir_name}) — still too large after truncation"
289                );
290                failed += 1;
291            }
292            QueuedSend::Failed(e) => {
293                eprintln!();
294                eprintln!("  Warning: failed to send event (session {queue_dir_name}): {e}");
295                failed_events.push(event);
296                failed += 1;
297            }
298            QueuedSend::Refused { pid, kind } => {
299                eprintln!();
300                eprintln!(
301                    "{}",
302                    crate::commands::stream::refused_error(pid, &kind, force)
303                );
304                failed_events.push(event);
305                failed_events.extend(events.by_ref().map(|(_, e)| e));
306                // Everything not sent is failed: earlier failures, the refused
307                // event, and the untried rest.
308                failed = event_total as u64 - sent;
309                break;
310            }
311        }
312    }
313    eprintln!();
314
315    // Re-enqueue retryable events (not 413s) to the SAME per-target file.
316    if !failed_events.is_empty() {
317        append_pending(pending_path, &failed_events)?;
318    }
319    Ok((sent, failed))
320}
321
322pub async fn run_flush(project_root: &Path) -> Result<(), Box<dyn std::error::Error>> {
323    let (server_url, credential) = resolve_credentials(project_root)?;
324    let server_url = server_url.ok_or("server_url not configured")?;
325    let client = ApiClient::with_credential(&server_url, credential);
326
327    // Lenient config load: used only to attribute the legacy `pending.jsonl`
328    // (written by releases before per-repo queue files existed) to the bound
329    // repo id, if any. Best-effort — a missing/malformed config just means
330    // any legacy queue can't be attributed and is left in place.
331    let bound_repo_id = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.repo_id);
332
333    let sessions_dir = project_root.join(".tracevault").join("sessions");
334    if !sessions_dir.exists() {
335        println!("No sessions directory found. Nothing to flush.");
336        return Ok(());
337    }
338
339    let mut total_sent = 0u64;
340    let mut total_failed = 0u64;
341
342    let session_entries: Vec<_> = fs::read_dir(&sessions_dir)?
343        .filter_map(|e| e.ok())
344        .filter(|e| e.path().is_dir())
345        .collect();
346
347    for session_entry in session_entries {
348        let session_dir = session_entry.path();
349        // Collect (path, QueueTarget) pairs for every pending queue in this
350        // session directory before draining, to keep the borrow/async loop
351        // below simple.
352        let pending_queues = pending_queues_in(&session_dir, bound_repo_id.as_deref())?;
353
354        for (pending_path, target) in pending_queues {
355            // Resolved once per queue, not per event — the force read costs
356            // an env read and an RFC3339 parse.
357            let capture_binding = queue_capture_binding(&session_dir);
358            let capture_pid = capture_binding
359                .as_ref()
360                .and_then(crate::resolution::capture_project_id);
361            let force = queue_attribution_force(&target, capture_binding.as_ref());
362            let (sent, failed) =
363                drain_queue(&client, &pending_path, &target, capture_pid, force).await?;
364            total_sent += sent;
365            total_failed += failed;
366        }
367    }
368
369    println!("Flush complete: {total_sent} sent, {total_failed} failed");
370    Ok(())
371}
372
373/// Read and remove all events from a pending.jsonl file.
374fn drain_pending(path: &Path) -> Result<Vec<StreamEventRequest>, Box<dyn std::error::Error>> {
375    let file = fs::File::open(path)?;
376    let reader = BufReader::new(file);
377    let mut events = Vec::new();
378
379    for line in reader.lines() {
380        let line = line?;
381        let trimmed = line.trim();
382        if trimmed.is_empty() {
383            continue;
384        }
385        match serde_json::from_str::<StreamEventRequest>(trimmed) {
386            Ok(event) => events.push(event),
387            Err(e) => {
388                eprintln!("Warning: skipping malformed pending event: {e}");
389            }
390        }
391    }
392
393    // Truncate the file after reading
394    fs::write(path, "")?;
395
396    Ok(events)
397}
398
399/// Append events back to a pending.jsonl file (for re-enqueuing failures).
400fn append_pending(
401    path: &Path,
402    events: &[StreamEventRequest],
403) -> Result<(), Box<dyn std::error::Error>> {
404    let mut file = fs::OpenOptions::new()
405        .create(true)
406        .append(true)
407        .open(path)?;
408
409    for event in events {
410        let json = serde_json::to_string(event)?;
411        writeln!(file, "{json}")?;
412    }
413
414    Ok(())
415}
416
417// ---------------------------------------------------------------------------
418// Tests
419// ---------------------------------------------------------------------------
420
421#[cfg(test)]
422mod tests {
423    use super::{display_prefix, pending_queues_in, repo_id_from_pending_filename, QueueTarget};
424    use crate::paths::resolve_project_root;
425    use crate::test_helpers::{add_worktree, init_git_repo};
426    use std::fs;
427
428    #[test]
429    fn repo_id_from_pending_filename_extracts_id() {
430        assert_eq!(
431            repo_id_from_pending_filename("pending-abc.jsonl"),
432            Some("abc")
433        );
434    }
435
436    #[test]
437    fn repo_id_from_pending_filename_none_for_legacy_name() {
438        assert_eq!(repo_id_from_pending_filename("pending.jsonl"), None);
439    }
440
441    #[test]
442    fn repo_id_from_pending_filename_none_for_unrelated_name() {
443        assert_eq!(repo_id_from_pending_filename("events.jsonl"), None);
444        assert_eq!(repo_id_from_pending_filename("pending-abc.txt"), None);
445    }
446
447    #[test]
448    fn repo_id_from_pending_filename_none_for_empty_id() {
449        assert_eq!(repo_id_from_pending_filename("pending-.jsonl"), None);
450    }
451
452    /// From a sibling worktree the resolved project root must point at the
453    /// PRIMARY checkout, so `flush` looks for sessions under
454    /// `<primary>/.tracevault/sessions/` rather than a non-existent sibling dir.
455    ///
456    /// This test asserts only the resolution layer — draining the queue requires
457    /// a live server, so the full end-to-end drain path is not exercised here.
458    #[test]
459    fn sessions_dir_from_sibling_worktree_is_under_primary() {
460        let tmp = tempfile::tempdir().unwrap();
461        let repo = tmp.path().join("repo");
462        let wt = tmp.path().join("sibling-wt");
463
464        fs::create_dir_all(&repo).unwrap();
465        init_git_repo(&repo);
466        add_worktree(&repo, &wt);
467
468        // Place a pending.jsonl in the primary sessions dir.
469        let session_id = "aabbccdd-0000-0000-0000-000000000001";
470        let sessions_dir = repo.join(".tracevault").join("sessions").join(session_id);
471        fs::create_dir_all(&sessions_dir).unwrap();
472        fs::write(sessions_dir.join("pending.jsonl"), "").unwrap();
473
474        // Simulate what main.rs now does: resolve from the SIBLING worktree cwd.
475        let resolved_root = resolve_project_root(&wt).root;
476        let expected_sessions = repo
477            .canonicalize()
478            .unwrap()
479            .join(".tracevault")
480            .join("sessions");
481        let got_sessions = resolved_root
482            .canonicalize()
483            .unwrap()
484            .join(".tracevault")
485            .join("sessions");
486
487        assert_eq!(
488            got_sessions, expected_sessions,
489            "flush must look for sessions under the PRIMARY repo, not the sibling worktree dir"
490        );
491    }
492
493    // ── pending_queues_in: per-session pending-queue enumeration ─────────────
494
495    fn setup_session_dir_with_pending_files() -> tempfile::TempDir {
496        let dir = tempfile::tempdir().unwrap();
497        fs::write(
498            dir.path()
499                .join("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl"),
500            "",
501        )
502        .unwrap();
503        fs::write(
504            dir.path()
505                .join("pending-550e8400-e29b-41d4-a716-446655440000.jsonl"),
506            "",
507        )
508        .unwrap();
509        fs::write(dir.path().join("pending.jsonl"), "").unwrap();
510        fs::write(dir.path().join("notes.txt"), "").unwrap();
511        fs::write(dir.path().join("pending-.jsonl"), "").unwrap();
512        fs::write(dir.path().join("pending-not-a-uuid.jsonl"), "").unwrap();
513        // A repo-less session's queue, written by the stream hook when only a
514        // project binding resolved.
515        fs::write(
516            dir.path()
517                .join("pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"),
518            "",
519        )
520        .unwrap();
521        dir
522    }
523
524    /// Render a classified target as a sortable label so the assertions below
525    /// can compare whole queue sets, and so a repo queue and a project queue
526    /// that happened to share an id would still be distinguishable.
527    fn label(t: &QueueTarget) -> String {
528        match t {
529            QueueTarget::Repo(id) => id.clone(),
530            QueueTarget::Project(id) => format!("project:{id}"),
531        }
532    }
533
534    fn sorted_labels(got: &[(std::path::PathBuf, QueueTarget)]) -> Vec<String> {
535        let mut v: Vec<String> = got.iter().map(|(_, t)| label(t)).collect();
536        v.sort();
537        v
538    }
539
540    #[test]
541    fn pending_queues_in_with_bound_repo_includes_legacy() {
542        let dir = setup_session_dir_with_pending_files();
543        let got =
544            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
545        assert_eq!(
546            sorted_labels(&got),
547            vec![
548                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
549                "550e8400-e29b-41d4-a716-446655440000",
550                "550e8400-e29b-41d4-a716-446655440001",
551                "project:018f0000-0000-7000-8000-000000000abc",
552            ]
553        );
554
555        let legacy = got
556            .iter()
557            .find(|(_, t)| matches!(t, QueueTarget::Repo(id) if id == "550e8400-e29b-41d4-a716-446655440001"))
558            .unwrap();
559        assert_eq!(legacy.0, dir.path().join("pending.jsonl"));
560    }
561
562    #[test]
563    fn pending_queues_in_without_bound_repo_skips_legacy() {
564        let dir = setup_session_dir_with_pending_files();
565        let got = pending_queues_in(dir.path(), None).unwrap();
566        assert_eq!(
567            sorted_labels(&got),
568            vec![
569                "0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b",
570                "550e8400-e29b-41d4-a716-446655440000",
571                "project:018f0000-0000-7000-8000-000000000abc",
572            ]
573        );
574    }
575
576    #[test]
577    fn pending_queues_in_ignores_unrelated_and_malformed_names() {
578        let dir = setup_session_dir_with_pending_files();
579        let got =
580            pending_queues_in(dir.path(), Some("550e8400-e29b-41d4-a716-446655440001")).unwrap();
581
582        assert!(!got.iter().any(|(p, _)| p.ends_with("notes.txt")));
583        assert!(!got.iter().any(|(p, _)| p.ends_with("pending-.jsonl")));
584        // Non-UUID repo_ids are silently skipped (guards against corrupted files)
585        assert!(!got
586            .iter()
587            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
588    }
589
590    #[test]
591    fn pending_queues_in_validates_uuid_in_per_repo_files() {
592        let dir = setup_session_dir_with_pending_files();
593        let got = pending_queues_in(dir.path(), None).unwrap();
594
595        // Valid UUIDs are included
596        assert!(got
597            .iter()
598            .any(|(p, _)| p.ends_with("pending-0190a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a5b.jsonl")));
599        assert!(got
600            .iter()
601            .any(|(p, _)| p.ends_with("pending-550e8400-e29b-41d4-a716-446655440000.jsonl")));
602        // Non-UUID files are NOT included
603        assert!(!got
604            .iter()
605            .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
606    }
607
608    // ── display_prefix: display-only truncation, no panic on short ids ─────
609
610    #[test]
611    fn display_prefix_truncates_long_id() {
612        assert_eq!(
613            display_prefix("0190a1b2-cccc-dddd-eeee-ffffffffffff"),
614            "0190a1b2"
615        );
616    }
617
618    #[test]
619    fn display_prefix_returns_whole_string_when_shorter_than_8() {
620        assert_eq!(display_prefix("x"), "x");
621    }
622
623    #[test]
624    fn display_prefix_handles_empty_string() {
625        assert_eq!(display_prefix(""), "");
626    }
627}
628
629#[cfg(test)]
630mod queue_target_tests {
631    use super::*;
632
633    /// A repo-less queue must classify as a PROJECT target. The repo pattern
634    /// also matches this filename (yielding `project-<uuid>`), so ordering
635    /// inside `queue_target_from_filename` is what makes this pass.
636    #[test]
637    fn project_queue_classifies_as_project_not_repo() {
638        let pid = uuid::Uuid::new_v4();
639        assert_eq!(
640            queue_target_from_filename(&format!("pending-project-{pid}.jsonl")),
641            Some(QueueTarget::Project(pid))
642        );
643    }
644
645    #[test]
646    fn repo_queue_still_classifies_as_repo() {
647        let repo = uuid::Uuid::new_v4();
648        assert_eq!(
649            queue_target_from_filename(&format!("pending-{repo}.jsonl")),
650            Some(QueueTarget::Repo(repo.to_string()))
651        );
652    }
653
654    /// The writer (`Attribution::pending_file_name`, in `commands::stream`)
655    /// and the reader (`queue_target_from_filename`, here) are the two halves
656    /// of one format that live in different modules. Nothing else fails if
657    /// they diverge — an unparsable name is silently skipped, stranding the
658    /// queue while `status` still counts it — so pin the round trip.
659    #[test]
660    fn every_attribution_round_trips_through_its_queue_filename() {
661        use crate::commands::stream::Attribution;
662
663        let repo = uuid::Uuid::new_v4();
664        assert_eq!(
665            queue_target_from_filename(
666                &Attribution::Repo {
667                    repo_id: repo.to_string(),
668                    project: Some(uuid::Uuid::new_v4()),
669                }
670                .pending_file_name()
671            ),
672            Some(QueueTarget::Repo(repo.to_string())),
673            "a repo queue must classify back to the same repo"
674        );
675
676        let pid = uuid::Uuid::new_v4();
677        assert_eq!(
678            queue_target_from_filename(
679                &Attribution::ProjectOnly { project_id: pid }.pending_file_name()
680            ),
681            Some(QueueTarget::Project(pid)),
682            "a repo-less queue must classify back to the same project, NOT to a repo"
683        );
684    }
685
686    /// Traversal-shaped names are rejected by the UUID parse on both arms.
687    /// `pending_queues_in` builds its paths from `fs::read_dir`, which never
688    /// yields `.` or `..` as entries, so a traversal component cannot reach
689    /// here in the first place — this pins the second line of defence, the
690    /// one that would still hold if the source of the names ever changed.
691    #[test]
692    fn traversal_shaped_names_are_rejected() {
693        for name in [
694            "pending-../../etc/passwd.jsonl",
695            "pending-project-../../etc/passwd.jsonl",
696            "pending-..%2f..%2fetc.jsonl",
697            "pending-/etc/passwd.jsonl",
698        ] {
699            assert_eq!(queue_target_from_filename(name), None, "accepted: {name}");
700        }
701    }
702
703    /// Non-UUID ids are rejected on both arms — these names can only come
704    /// from a corrupted or hand-created file.
705    #[test]
706    fn non_uuid_ids_are_rejected() {
707        assert_eq!(queue_target_from_filename("pending-nope.jsonl"), None);
708        assert_eq!(
709            queue_target_from_filename("pending-project-nope.jsonl"),
710            None
711        );
712        assert_eq!(queue_target_from_filename("pending-.jsonl"), None);
713        assert_eq!(queue_target_from_filename("pending.jsonl"), None);
714    }
715}
716
717/// VIS-316: `flush` must drain a repo queue under the session's capture
718/// project, never re-attributing a refused event via the repo-scoped endpoint.
719#[cfg(test)]
720mod send_tests {
721    use super::*;
722    use crate::api_client::AttributionMode;
723    use crate::commands::stream::AttributionForce;
724    use crate::test_helpers::{http_json, lock_env_mutation, spawn_seq, EnvVarGuard, RECV_TIMEOUT};
725    use std::path::PathBuf;
726    use std::time::Duration;
727    use tracevault_protocol::streaming::StreamEventType;
728
729    const REPO: &str = "11111111-1111-1111-1111-111111111111";
730
731    fn event(n: u128) -> StreamEventRequest {
732        StreamEventRequest {
733            protocol_version: 1,
734            tool: Some("claude-code".to_string()),
735            event_type: StreamEventType::ToolUse,
736            session_id: "sess-flush".into(),
737            timestamp: chrono::Utc::now(),
738            hook_event_name: Some("PostToolUse".into()),
739            tool_name: None,
740            tool_use_id: None,
741            tool_input: None,
742            tool_response: None,
743            tool_is_error: None,
744            event_index: None,
745            event_uuid: Some(uuid::Uuid::from_u128(n)),
746            transcript_lines: None,
747            transcript_offset: None,
748            model: None,
749            cwd: None,
750            final_stats: None,
751            flow_id: None,
752            labels: None,
753            params: None,
754        }
755    }
756
757    fn ok() -> String {
758        let body = serde_json::to_string(&tracevault_protocol::streaming::StreamEventResponse {
759            session_db_id: uuid::Uuid::nil(),
760            event_db_id: Some(uuid::Uuid::nil()),
761            status: "accepted".to_string(),
762        })
763        .unwrap();
764        http_json("200 OK", &body)
765    }
766
767    fn bad_request() -> String {
768        http_json(
769            "400 Bad Request",
770            r#"{"error":"repo is not a member of project"}"#,
771        )
772    }
773
774    /// The request line of a captured request (`spawn_seq` renders
775    /// `"<request line> | <headers> | <body>"`).
776    fn request_line(captured: &str) -> &str {
777        captured.split(" | ").next().unwrap_or_default()
778    }
779
780    /// Event uuids held by a queue file, in order; every line must parse.
781    fn queued_uuids(path: &Path) -> Vec<uuid::Uuid> {
782        fs::read_to_string(path)
783            .unwrap()
784            .lines()
785            .filter(|l| !l.trim().is_empty())
786            .map(|l| {
787                serde_json::from_str::<StreamEventRequest>(l)
788                    .expect("every queued line parses")
789                    .event_uuid
790                    .unwrap()
791            })
792            .collect()
793    }
794
795    #[tokio::test]
796    async fn repo_queue_with_capture_project_goes_to_the_project_endpoint() {
797        let (base, rx) = spawn_seq(vec![ok()]);
798        let client = ApiClient::new(&base, Some("tok"));
799        let pid = uuid::Uuid::from_u128(0xA);
800
801        let got = send_queued_event(
802            &client,
803            &QueueTarget::Repo(REPO.into()),
804            Some(pid),
805            AttributionForce::default(),
806            &event(1),
807        )
808        .await;
809        assert!(matches!(got, QueuedSend::Sent), "{got:?}");
810
811        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
812        assert!(
813            request_line(&captured).starts_with(&format!(
814                "POST /api/v1/projects/{pid}/stream?repo_id={REPO} "
815            )),
816            "got: {captured}"
817        );
818    }
819
820    /// VIS-305: a flushed event declares the SAME attribution mode the live
821    /// send would have. `queue_attribution_force` reads it off the capture
822    /// binding that decided the repo queue's project — so a live
823    /// `forced_until` on that binding must reach the wire as `explicit`, and
824    /// an unforced one as `derived`. Without this, a queued event would
825    /// silently downgrade to membership-checked attribution on drain.
826    #[tokio::test]
827    async fn repo_queue_declares_the_capture_bindings_attribution_mode() {
828        let _env_lock = lock_env_mutation().await;
829        let mut guard = EnvVarGuard::new();
830        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
831
832        let pid = uuid::Uuid::from_u128(0xF);
833        let forced = crate::session_state::ProjectBinding {
834            project_id: pid.to_string(),
835            project_name: "p".into(),
836            updated_at: String::new(),
837            forced_until: Some((chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()),
838        };
839        let unforced = crate::session_state::ProjectBinding {
840            forced_until: None,
841            ..forced.clone()
842        };
843        let target = QueueTarget::Repo(REPO.into());
844
845        for (binding, expected) in [
846            (&forced, AttributionMode::Explicit),
847            (&unforced, AttributionMode::Derived),
848        ] {
849            let force = queue_attribution_force(&target, Some(binding));
850            assert_eq!(force.mode(), expected, "mode for {binding:?}");
851
852            let (base, rx) = spawn_seq(vec![ok()]);
853            let client = ApiClient::new(&base, Some("tok"));
854            let got = send_queued_event(&client, &target, Some(pid), force, &event(1)).await;
855            assert!(matches!(got, QueuedSend::Sent), "{got:?}");
856
857            let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
858            assert!(
859                captured
860                    .to_lowercase()
861                    .contains(&format!("x-tracevault-project-attribution: {expected}")),
862                "got: {captured}"
863            );
864        }
865    }
866
867    /// Seed a session whose `active_project` is `pid`, forced until `forced`,
868    /// and hand back the session directory `flush` would resolve it from.
869    /// The directory is deliberately EMPTY apart from its name: that name is
870    /// the session id, and it is the only input `queue_capture_binding` needs.
871    fn seed_forced_session(
872        state_root: &Path,
873        session_id: &str,
874        pid: uuid::Uuid,
875        forced: Option<String>,
876    ) -> PathBuf {
877        crate::session_state::save(
878            session_id,
879            &crate::session_state::SessionState {
880                active_project: Some(crate::session_state::ProjectBinding {
881                    project_id: pid.to_string(),
882                    project_name: "p".into(),
883                    updated_at: String::new(),
884                    forced_until: forced,
885                }),
886                ..Default::default()
887            },
888        )
889        .unwrap();
890        let session_dir = state_root.join("sessions").join(session_id);
891        fs::create_dir_all(&session_dir).unwrap();
892        session_dir
893    }
894
895    fn in_four_hours() -> String {
896        (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339()
897    }
898
899    /// VIS-305: a repo-LESS queue resolves the SAME capture binding a repo
900    /// queue does, so a SESSION-scoped force reaches the wire when that queue
901    /// is drained.
902    ///
903    /// `queue_capture_binding` derives everything from the session directory
904    /// — the session id is its name, the worktree override its `origin`
905    /// marker, and `commands::stream::capture_binding` takes no repo at all
906    /// — so nothing about a project queue makes the binding unrecoverable.
907    /// An earlier version early-returned `None` for a non-repo target and
908    /// consulted only the user-level default, which made a session-scoped
909    /// force (the ordinary case whenever a session id is set) invisible: the
910    /// header silently downgraded to `derived` on drain.
911    #[tokio::test]
912    async fn project_queue_honours_a_session_scoped_force() {
913        let _env_lock = lock_env_mutation().await;
914        let tmp = tempfile::tempdir().unwrap();
915        let mut guard = EnvVarGuard::new();
916        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
917        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
918        guard.set("HOME", tmp.path());
919        // Both are read ABOVE the session binding this test pins (and the
920        // second would decide the header outright).
921        guard.remove("TRACEVAULT_PROJECT");
922        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
923
924        let pid = uuid::Uuid::from_u128(0xA1);
925        let session_dir = seed_forced_session(
926            &tmp.path().join("state"),
927            "flush-project-force",
928            pid,
929            Some(in_four_hours()),
930        );
931
932        let binding = queue_capture_binding(&session_dir);
933        let want = pid.to_string();
934        assert_eq!(
935            binding.as_ref().map(|b| b.project_id.as_str()),
936            Some(want.as_str()),
937            "a project queue's binding is recoverable from the session dir alone"
938        );
939
940        let target = QueueTarget::Project(pid);
941        let force = queue_attribution_force(&target, binding.as_ref());
942        assert_eq!(
943            force.mode(),
944            AttributionMode::Explicit,
945            "a live session force must not be dropped"
946        );
947
948        let (base, rx) = spawn_seq(vec![ok()]);
949        let client = ApiClient::new(&base, Some("tok"));
950        let got = send_queued_event(&client, &target, None, force, &event(1)).await;
951        assert!(matches!(got, QueuedSend::Sent), "{got:?}");
952        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
953        assert!(
954            captured
955                .to_lowercase()
956                .contains("x-tracevault-project-attribution: explicit"),
957            "got: {captured}"
958        );
959    }
960
961    /// The flush-path echo of the "does a force leak onto a different
962    /// project" bug, now over the WHOLE precedence chain rather than the
963    /// user default alone: a live force on the binding that currently
964    /// resolves (project A) must NOT apply to a queue keyed by a DIFFERENT
965    /// project B — e.g. the user switched projects since B's events were
966    /// buffered.
967    #[tokio::test]
968    async fn project_queue_does_not_take_a_force_resolved_for_another_project() {
969        let _env_lock = lock_env_mutation().await;
970        let tmp = tempfile::tempdir().unwrap();
971        let mut guard = EnvVarGuard::new();
972        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
973        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
974        guard.set("HOME", tmp.path());
975        guard.remove("TRACEVAULT_PROJECT");
976        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
977
978        let project_a = uuid::Uuid::from_u128(0xA);
979        let project_b = uuid::Uuid::from_u128(0xB);
980        let session_dir = seed_forced_session(
981            &tmp.path().join("state"),
982            "flush-project-leak",
983            project_a,
984            Some(in_four_hours()),
985        );
986
987        let binding = queue_capture_binding(&session_dir);
988        assert_eq!(
989            queue_attribution_force(&QueueTarget::Project(project_a), binding.as_ref()).mode(),
990            AttributionMode::Explicit,
991            "the queue the force was resolved FOR still gets it"
992        );
993        assert_eq!(
994            queue_attribution_force(&QueueTarget::Project(project_b), binding.as_ref()).mode(),
995            AttributionMode::Derived,
996            "a force resolved for a DIFFERENT project must not leak onto this queue"
997        );
998    }
999
1000    /// The user-level default is the lowest tier of that same chain, so a
1001    /// force persisted by `project switch --user` still reaches a repo-less
1002    /// queue keyed by that project — with no session binding in the way.
1003    #[tokio::test]
1004    async fn project_queue_honours_a_user_default_force() {
1005        let _env_lock = lock_env_mutation().await;
1006        let tmp = tempfile::tempdir().unwrap();
1007        let mut guard = EnvVarGuard::new();
1008        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
1009        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
1010        guard.set("HOME", tmp.path());
1011        guard.remove("TRACEVAULT_PROJECT");
1012        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
1013
1014        let pid = uuid::Uuid::from_u128(0xC);
1015        crate::user_project_default::save(&crate::session_state::ProjectBinding {
1016            project_id: pid.to_string(),
1017            project_name: "p".into(),
1018            updated_at: chrono::Utc::now().to_rfc3339(),
1019            forced_until: Some(in_four_hours()),
1020        })
1021        .unwrap();
1022
1023        // No session state at all: the directory's name resolves to nothing,
1024        // so the user default is what the chain lands on.
1025        let session_dir = tmp
1026            .path()
1027            .join("state")
1028            .join("sessions")
1029            .join("flush-no-session");
1030        fs::create_dir_all(&session_dir).unwrap();
1031
1032        let binding = queue_capture_binding(&session_dir);
1033        assert_eq!(
1034            queue_attribution_force(&QueueTarget::Project(pid), binding.as_ref()).mode(),
1035            AttributionMode::Explicit
1036        );
1037        assert_eq!(
1038            queue_attribution_force(
1039                &QueueTarget::Project(uuid::Uuid::from_u128(0xD)),
1040                binding.as_ref()
1041            )
1042            .mode(),
1043            AttributionMode::Derived,
1044            "and still does not leak onto another project's queue"
1045        );
1046    }
1047
1048    #[tokio::test]
1049    async fn repo_queue_without_capture_project_goes_to_the_repo_endpoint() {
1050        let (base, rx) = spawn_seq(vec![ok()]);
1051        let client = ApiClient::new(&base, Some("tok"));
1052
1053        let got = send_queued_event(
1054            &client,
1055            &QueueTarget::Repo(REPO.into()),
1056            None,
1057            AttributionForce::default(),
1058            &event(1),
1059        )
1060        .await;
1061        assert!(matches!(got, QueuedSend::Sent), "{got:?}");
1062
1063        let captured = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1064        assert!(
1065            request_line(&captured).starts_with(&format!("POST /api/v1/repos/{REPO}/stream ")),
1066            "got: {captured}"
1067        );
1068    }
1069
1070    /// A 400 on the project-scoped send is a refusal: exactly one request (a
1071    /// spare 200 is staged so a repo-scoped retry WOULD be captured), and the
1072    /// outcome says so, which is what makes `drain_queue` re-enqueue it.
1073    #[tokio::test]
1074    async fn refused_project_send_makes_one_request_and_is_classified_refused() {
1075        use crate::commands::stream::ClientErrorKind;
1076
1077        let (base, rx) = spawn_seq(vec![bad_request(), ok()]);
1078        let client = ApiClient::new(&base, Some("tok"));
1079        let pid = uuid::Uuid::from_u128(0xB);
1080
1081        let got = send_queued_event(
1082            &client,
1083            &QueueTarget::Repo(REPO.into()),
1084            Some(pid),
1085            AttributionForce::default(),
1086            &event(1),
1087        )
1088        .await;
1089        assert!(
1090            matches!(
1091                got,
1092                QueuedSend::Refused { pid: p, kind: ClientErrorKind::Scoping } if p == pid
1093            ),
1094            "{got:?}"
1095        );
1096
1097        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1098        assert!(
1099            request_line(&first).contains(&format!("/projects/{pid}/stream?repo_id={REPO}")),
1100            "got: {first}"
1101        );
1102        assert!(
1103            rx.recv_timeout(Duration::from_millis(500)).is_err(),
1104            "a refused event must not be re-sent to the repo-scoped endpoint"
1105        );
1106    }
1107
1108    /// A transient failure keeps today's per-event retry: `Failed`, not
1109    /// `Refused`, so the drain goes on to the next event.
1110    #[tokio::test]
1111    async fn transient_project_send_failure_is_not_a_refusal() {
1112        let (base, _rx) = spawn_seq(vec![http_json("503 Service Unavailable", "{}")]);
1113        let client = ApiClient::new(&base, Some("tok"));
1114
1115        let got = send_queued_event(
1116            &client,
1117            &QueueTarget::Repo(REPO.into()),
1118            Some(uuid::Uuid::from_u128(0xC)),
1119            AttributionForce::default(),
1120            &event(1),
1121        )
1122        .await;
1123        assert!(matches!(got, QueuedSend::Failed(_)), "{got:?}");
1124    }
1125
1126    /// A refusal mid-queue stops the drain: the events already sent stay
1127    /// sent, and the refused event plus every untried one are re-enqueued in
1128    /// their original order and counted failed. The third event is never
1129    /// attempted (the spare response stays unclaimed).
1130    #[tokio::test]
1131    async fn drain_queue_stops_at_a_refusal_and_requeues_the_rest_in_order() {
1132        let (base, rx) = spawn_seq(vec![ok(), bad_request(), ok()]);
1133        let client = ApiClient::new(&base, Some("tok"));
1134        let pid = uuid::Uuid::from_u128(0xD);
1135        let dir = tempfile::tempdir().unwrap();
1136        let path = dir.path().join(format!("pending-{REPO}.jsonl"));
1137        append_pending(&path, &[event(1), event(2), event(3)]).unwrap();
1138
1139        let (sent, failed) = drain_queue(
1140            &client,
1141            &path,
1142            &QueueTarget::Repo(REPO.into()),
1143            Some(pid),
1144            AttributionForce::default(),
1145        )
1146        .await
1147        .unwrap();
1148
1149        assert_eq!((sent, failed), (1, 2));
1150        assert_eq!(
1151            queued_uuids(&path),
1152            vec![uuid::Uuid::from_u128(2), uuid::Uuid::from_u128(3)]
1153        );
1154        for _ in 0..2 {
1155            let captured = rx.recv_timeout(RECV_TIMEOUT).expect("request missing");
1156            assert!(
1157                request_line(&captured).contains(&format!("/projects/{pid}/stream?repo_id=")),
1158                "got: {captured}"
1159            );
1160        }
1161        assert!(
1162            rx.recv_timeout(Duration::from_millis(500)).is_err(),
1163            "no request after the refusal"
1164        );
1165    }
1166
1167    /// End to end through `run_flush`: the capture project comes from the
1168    /// session state the hook reads (`XDG_STATE_HOME`, keyed by the session
1169    /// directory's name), and a refusal leaves every event in the queue.
1170    #[tokio::test]
1171    async fn run_flush_applies_the_session_capture_project_and_keeps_refused_events() {
1172        let _env_lock = lock_env_mutation().await;
1173        let tmp = tempfile::tempdir().unwrap();
1174        let root = tmp.path().join("repo");
1175        let mut guard = EnvVarGuard::new();
1176        guard.set("XDG_STATE_HOME", tmp.path().join("state"));
1177        guard.set("XDG_CONFIG_HOME", tmp.path().join("config"));
1178        guard.set("HOME", tmp.path());
1179        // `queue_capture_binding` runs the capture chain, which reads
1180        // `TRACEVAULT_PROJECT` ABOVE the session-active binding this test
1181        // pins; an ambient export would redirect the drain at another
1182        // project. `TRACEVAULT_PROJECT_ATTRIBUTION` would likewise change
1183        // the header the assertions below do not expect.
1184        guard.remove("TRACEVAULT_PROJECT");
1185        guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
1186
1187        let (base, rx) = spawn_seq(vec![bad_request(), ok()]);
1188        guard.set("TRACEVAULT_SERVER_URL", &base);
1189        guard.set("TRACEVAULT_API_KEY", "tvk_test");
1190
1191        let session_id = "flush-session-1";
1192        let pid = uuid::Uuid::from_u128(0xE);
1193        crate::session_state::save(
1194            session_id,
1195            &crate::session_state::SessionState {
1196                active_project: Some(crate::session_state::ProjectBinding {
1197                    project_id: pid.to_string(),
1198                    project_name: "p".into(),
1199                    updated_at: String::new(),
1200                    forced_until: None,
1201                }),
1202                ..Default::default()
1203            },
1204        )
1205        .unwrap();
1206
1207        let session_dir = root.join(".tracevault").join("sessions").join(session_id);
1208        fs::create_dir_all(&session_dir).unwrap();
1209        fs::write(
1210            session_dir.join("origin"),
1211            root.to_string_lossy().as_bytes(),
1212        )
1213        .unwrap();
1214        let queue = session_dir.join(format!("pending-{REPO}.jsonl"));
1215        append_pending(&queue, &[event(1), event(2)]).unwrap();
1216
1217        run_flush(&root).await.unwrap();
1218
1219        let first = rx.recv_timeout(RECV_TIMEOUT).expect("no request captured");
1220        assert!(
1221            request_line(&first).starts_with(&format!(
1222                "POST /api/v1/projects/{pid}/stream?repo_id={REPO} "
1223            )),
1224            "got: {first}"
1225        );
1226        assert!(
1227            rx.recv_timeout(Duration::from_millis(500)).is_err(),
1228            "exactly one request: no repo-scoped fallback, no second event"
1229        );
1230        assert_eq!(
1231            queued_uuids(&queue),
1232            vec![uuid::Uuid::from_u128(1), uuid::Uuid::from_u128(2)]
1233        );
1234    }
1235}