Skip to main content

tracevault_cli/commands/
flush.rs

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