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