1use crate::api_client::ApiClient;
2use crate::credentials::resolve_credentials;
3use std::fs;
4use std::path::Path;
5use tracevault_protocol::streaming::StreamEventRequest;
6
7pub(crate) const QUEUE_PREFIX: &str = "pending-";
13pub(crate) const PROJECT_QUEUE_PREFIX: &str = "pending-project-";
16pub(crate) const QUEUE_SUFFIX: &str = ".jsonl";
17
18pub(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
32pub(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#[derive(Debug, Clone, PartialEq, Eq)]
43pub(crate) enum QueueTarget {
44 Repo(String),
45 Project(uuid::Uuid),
46}
47
48pub(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 uuid::Uuid::parse_str(repo_id).ok()?;
59 Some(QueueTarget::Repo(repo_id.to_string()))
60}
61
62fn pending_queues_in(
68 session_dir: &Path,
69 bound_repo_id: Option<&str>,
70) -> std::io::Result<Vec<(std::path::PathBuf, QueueTarget)>> {
71 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 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
105fn display_prefix(id: &str) -> &str {
108 id.get(..8).unwrap_or(id)
109}
110
111fn 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
144const REPLAY_BUDGET: std::time::Duration = std::time::Duration::from_secs(300);
147
148#[derive(Debug)]
150pub(crate) enum QueuedSend {
151 Sent,
152 TooLarge,
155 Failed(String),
157 Refused {
162 pid: uuid::Uuid,
163 kind: crate::commands::stream::ClientErrorKind,
164 },
165}
166
167fn 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 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
205fn 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
219fn 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
230pub(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 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
284async 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 if let Some(session_dir) = pending_path.parent() {
299 crate::pending_queue::upgrade(session_dir)?;
300 }
301 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 let mut rest = None;
316
317 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 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 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 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 let pending_queues = pending_queues_in(&session_dir, bound_repo_id.as_deref())?;
424
425 for (pending_path, target) in pending_queues {
426 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 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#[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#[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 #[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 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 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 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 fs::write(
577 dir.path()
578 .join("pending-project-018f0000-0000-7000-8000-000000000abc.jsonl"),
579 "",
580 )
581 .unwrap();
582 dir
583 }
584
585 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 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 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 assert!(!got
665 .iter()
666 .any(|(p, _)| p.ends_with("pending-not-a-uuid.jsonl")));
667 }
668
669 #[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 #[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 #[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 #[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 #[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#[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 fn request_line(captured: &str) -> &str {
839 captured.split(" | ").next().unwrap_or_default()
840 }
841
842 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 #[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 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 #[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 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 #[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 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 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 let notes = root.join("notes");
1088 fs::create_dir_all(¬es).unwrap();
1089 fs::write(
1090 session_dir.join("origin"),
1091 crate::paths::worktree_toplevel(¬es),
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 #[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 #[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 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 #[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 #[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 #[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 #[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 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}