1use std::collections::HashSet;
6use std::path::Path;
7
8use crate::api_client::{resolve_client, ApiClient, ProjectListItem, ResolveProjectOutcome};
9use crate::resolution::{
10 capture_project_binding, capture_project_id, git_remote_url, CaptureProjectInputs,
11 ProjectSource,
12};
13use crate::session_state::{self, ProjectBinding, SessionState};
14
15#[derive(clap::Subcommand)]
17pub enum ProjectCmd {
18 Switch {
21 name: String,
23 #[arg(long)]
28 user: bool,
29 #[arg(long)]
31 session_id: Option<String>,
32 #[arg(long, value_parser = ["derived", "explicit"], default_value = "derived")]
42 project_attribution: String,
43 },
44 Status {
46 #[arg(long)]
48 session_id: Option<String>,
49 #[arg(long)]
54 project: Option<String>,
55 },
56}
57
58pub async fn run(
59 cmd: ProjectCmd,
60 project_root: &Path,
61 cwd: &Path,
62) -> Result<(), Box<dyn std::error::Error>> {
63 match cmd {
64 ProjectCmd::Switch {
65 name,
66 user,
67 session_id,
68 project_attribution,
69 } => {
70 switch(
71 &name,
72 user,
73 session_id.as_deref(),
74 &project_attribution,
75 project_root,
76 cwd,
77 )
78 .await
79 }
80 ProjectCmd::Status {
81 session_id,
82 project,
83 } => status(session_id.as_deref(), project.as_deref(), project_root, cwd).await,
84 }
85}
86
87fn resolve_project_name<'a>(
89 items: &'a [ProjectListItem],
90 name: &str,
91) -> Result<&'a ProjectListItem, String> {
92 items.iter().find(|p| p.name == name).ok_or_else(|| {
93 let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
94 names.sort_unstable();
95 format!(
96 "project '{name}' not found. Available: {}",
97 names.join(", ")
98 )
99 })
100}
101
102#[derive(Debug, Clone, Copy, PartialEq, Eq)]
105enum CodebaseCheck {
106 Skip,
109 Enforce,
112 Report,
121}
122
123fn codebase_check_for(dest: &SwitchDest, explicit: bool) -> CodebaseCheck {
127 match (dest, explicit) {
128 (SwitchDest::UserDefault, _) => CodebaseCheck::Skip,
130 (SwitchDest::Session(_), true) => CodebaseCheck::Report,
131 (SwitchDest::Session(_), false) => CodebaseCheck::Enforce,
132 }
133}
134
135async fn resolve_switch_project(
146 name: &str,
147 client: &ApiClient,
148 check: CodebaseCheck,
149 cwd: &Path,
150) -> Result<(ProjectBinding, Option<String>), Box<dyn std::error::Error>> {
151 let items = client.list_projects().await?;
152 let matched = resolve_project_name(&items, name)
153 .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
154 let project_id = matched.id;
155 let project_name = matched.name.clone();
156 let mut note = None;
157
158 if check != CodebaseCheck::Skip {
159 if let Some(git_url) = git_remote_url(cwd) {
160 if let Some(remote) = client.resolve_remote(&git_url).await? {
161 let codebase_repo_ids: HashSet<uuid::Uuid> = client
162 .get_remote_repos(remote.remote_id)
163 .await?
164 .into_iter()
165 .map(|r| r.id)
166 .collect();
167 let project_repo_ids: HashSet<uuid::Uuid> = client
168 .get_project(project_id)
169 .await?
170 .repos
171 .into_iter()
172 .map(|r| r.id)
173 .collect();
174 if codebase_repo_ids.is_disjoint(&project_repo_ids) {
175 match check {
176 CodebaseCheck::Enforce => {
177 return Err(format!(
178 "project '{name}' does not contain the current codebase"
179 )
180 .into())
181 }
182 CodebaseCheck::Report => note = Some(forced_non_member_note(name)),
185 CodebaseCheck::Skip => unreachable!("guarded above"),
186 }
187 }
188 }
189 }
193 }
196
197 Ok((
198 ProjectBinding {
199 project_id: project_id.to_string(),
200 project_name,
201 updated_at: chrono::Utc::now().to_rfc3339(),
202 forced_until: None,
203 },
204 note,
205 ))
206}
207
208fn forced_non_member_note(name: &str) -> String {
214 format!(
215 "note: project '{name}' does not contain the current codebase — binding it anyway \
216 because --project-attribution explicit says this caller owns attribution. The \
217 server enforces that claim at ingest (Operator on the project, and a Control Plane \
218 identity — never a `tvk_` API key) and refuses it with a 403 otherwise."
219 )
220}
221
222#[derive(Debug)]
226enum SwitchDest {
227 Session(String),
228 UserDefault,
229}
230
231fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
232 if user {
233 return SwitchDest::UserDefault;
234 }
235 match session_id {
236 Some(id) => SwitchDest::Session(id),
237 None => SwitchDest::UserDefault,
238 }
239}
240
241fn apply_force(mut binding: ProjectBinding, explicit: bool) -> ProjectBinding {
248 binding.forced_until = explicit.then(|| {
249 (chrono::Utc::now()
250 + chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS))
251 .to_rfc3339()
252 });
253 binding
254}
255
256fn format_force_line(forced_until: &str) -> String {
282 match crate::session_state::force_status(forced_until) {
283 crate::session_state::ForceStatus::Live(until) => {
284 format!("persisted force: active until {}", until.to_rfc3339())
285 }
286 crate::session_state::ForceStatus::Lapsed(until) => {
287 format!("persisted force: lapsed {}", until.to_rfc3339())
288 }
289 crate::session_state::ForceStatus::Unreadable => format!(
290 "persisted force: unreadable timestamp ('{forced_until}'), treated as not in force"
291 ),
292 }
293}
294
295fn attribution_report(b: &ProjectBinding) -> Vec<String> {
323 let mode = crate::commands::stream::attribution_mode(Some(b));
324 let gloss = match mode {
328 crate::api_client::AttributionMode::Explicit => {
329 "this caller owns attribution; membership is not checked"
330 }
331 crate::api_client::AttributionMode::Derived => "TraceVault checks repo/project membership",
332 };
333 let mut lines = vec![format!("attribution mode: {mode} ({gloss})")];
334 if let Some(forced_until) = b.forced_until.as_deref() {
335 lines.push(format_force_line(forced_until));
336 }
337 lines
338}
339
340fn switch_report(
350 dest: &SwitchDest,
351 b: &ProjectBinding,
352 codebase_note: Option<&str>,
353) -> Vec<String> {
354 let mut lines = match dest {
355 SwitchDest::Session(id) => {
356 vec![format!("bound session {id} to project {}", b.project_name)]
357 }
358 SwitchDest::UserDefault => vec![format!(
359 "set user-level default project {}; applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
360 b.project_name
361 )],
362 };
363 lines.extend(codebase_note.map(str::to_string));
364 lines.extend(attribution_report(b));
365 lines
366}
367
368async fn switch(
369 name: &str,
370 user: bool,
371 session_id: Option<&str>,
372 project_attribution: &str,
373 project_root: &Path,
374 cwd: &Path,
375) -> Result<(), Box<dyn std::error::Error>> {
376 let client = resolve_client(project_root)?;
377 let session = crate::commands::repo::resolve_session_id(session_id).ok();
378 let dest = switch_destination(user, session);
379 let explicit = project_attribution == "explicit";
380 let check = codebase_check_for(&dest, explicit);
381 let (binding, codebase_note) = resolve_switch_project(name, &client, check, cwd).await?;
382 let binding = apply_force(binding, explicit);
383
384 match &dest {
385 SwitchDest::Session(id) => {
386 let mut state = session_state::load(id);
387 state.active_project = Some(binding.clone());
388 session_state::save(id, &state)?;
389 }
390 SwitchDest::UserDefault => {
391 crate::user_project_default::save(&binding)?;
392 }
393 }
394 for line in switch_report(&dest, &binding, codebase_note.as_deref()) {
395 println!("{line}");
396 }
397 Ok(())
398}
399
400fn status_effective(
415 project_flag: Option<ProjectBinding>,
416 env_project: Option<ProjectBinding>,
417 session: &SessionState,
418 worktree: Option<&str>,
419 config_project: Option<ProjectBinding>,
420 user_default: Option<ProjectBinding>,
421) -> (Option<(ProjectBinding, ProjectSource)>, Option<String>) {
422 match capture_project_binding(&CaptureProjectInputs {
423 project_flag,
424 env_project,
425 session,
426 worktree_path: worktree,
427 config_project,
428 user_default,
429 }) {
430 Some((binding, source)) if capture_project_id(&binding).is_none() => {
431 let warning = invalid_capture_id_warning(&binding, source);
432 (None, Some(warning))
433 }
434 other => (other, None),
435 }
436}
437
438fn enrich_project_name(
451 effective: Option<(ProjectBinding, ProjectSource)>,
452 items: Option<&[ProjectListItem]>,
453) -> Option<(ProjectBinding, ProjectSource)> {
454 effective.map(|(mut binding, source)| {
455 if binding.project_name.is_empty() {
456 if let Some(items) = items {
457 if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
458 if let Some(matched) = items.iter().find(|p| p.id == id) {
459 binding.project_name = matched.name.clone();
460 }
461 }
462 }
463 }
464 (binding, source)
465 })
466}
467
468fn env_name_form_warning(raw: &str) -> String {
477 format!(
478 "warning: TRACEVAULT_PROJECT '{raw}' is a NAME; only the UUID form is used for attribution at capture time, so this value is ignored — export the project's id instead, or bind it with `tracevault project switch <name>`"
479 )
480}
481
482fn binding_label(b: &ProjectBinding) -> &str {
484 if b.project_name.is_empty() {
485 &b.project_id
486 } else {
487 &b.project_name
488 }
489}
490
491fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
496 match effective {
497 Some((b, source)) => format!("project: {} via {source}", binding_label(b)),
498 None => "no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo".to_string(),
499 }
500}
501
502fn invalid_capture_id_warning(binding: &ProjectBinding, source: ProjectSource) -> String {
507 format!(
508 "warning: project {} — {source}, but the saved project_id is not a valid id and is dropped at capture time; run `{}` to rewrite it",
509 binding_label(binding),
510 source.rewrite_command()
511 )
512}
513
514fn offline_project_flag_warning(name: &str) -> String {
517 format!(
518 "warning: --project '{name}' cannot be resolved without server credentials; ignoring the override"
519 )
520}
521
522fn deduced_project_name(pid: uuid::Uuid, items: Option<&[ProjectListItem]>) -> Option<&str> {
526 items?.iter().find(|p| p.id == pid).map(|p| p.name.as_str())
527}
528
529fn format_deduction(
536 effective_is_bound: bool,
537 outcome: Result<ResolveProjectOutcome, String>,
538 resolved_name: Option<&str>,
539) -> String {
540 const PREFIX: &str = "server deduction for this repo:";
541 match outcome {
542 Ok(ResolveProjectOutcome::Resolved(pid)) => {
543 let pid = pid.to_string();
544 let label = resolved_name.unwrap_or(&pid);
545 if effective_is_bound {
546 format!("{PREFIX} {label} (not used: the local binding above wins)")
547 } else {
548 format!("{PREFIX} {label} (events will land here if a repo is bound)")
549 }
550 }
551 Ok(ResolveProjectOutcome::Ambiguous) => {
552 if effective_is_bound {
553 format!(
554 "{PREFIX} ambiguous (multiple projects) — not used, the local binding above wins"
555 )
556 } else {
557 format!(
558 "{PREFIX} ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
559 )
560 }
561 }
562 Ok(ResolveProjectOutcome::None) => format!("{PREFIX} none"),
563 Err(msg) => format!("{PREFIX} unavailable ({msg})"),
564 }
565}
566
567#[derive(Debug, Default)]
571struct StatusReport {
572 warnings: Vec<String>,
573 lines: Vec<String>,
574}
575
576async fn status(
579 session_id: Option<&str>,
580 project_flag_name: Option<&str>,
581 project_root: &Path,
582 cwd: &Path,
583) -> Result<(), Box<dyn std::error::Error>> {
584 let report = status_report(session_id, project_flag_name, project_root, cwd).await;
585 for warning in &report.warnings {
586 eprintln!("{warning}");
587 }
588 for line in &report.lines {
589 println!("{line}");
590 }
591 Ok(())
592}
593
594async fn status_report(
599 session_id: Option<&str>,
600 project_flag_name: Option<&str>,
601 project_root: &Path,
602 cwd: &Path,
603) -> StatusReport {
604 let mut report = StatusReport::default();
605 let session = match crate::commands::repo::resolve_session_id(session_id) {
608 Ok(id) => session_state::load(&id),
609 Err(_) => {
610 report.warnings.push(
611 "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
612 showing binding without session context"
613 .to_string(),
614 );
615 SessionState::default()
616 }
617 };
618 let worktree = crate::paths::worktree_toplevel(cwd);
619 let config = crate::config::TracevaultConfig::load(project_root);
623 let config_project = config
624 .as_ref()
625 .and_then(crate::resolution::project_from_config);
626 let user_default = crate::user_project_default::load();
627 let git_url = git_remote_url(cwd);
628
629 let env_project = crate::commands::stream::env_project_binding();
634 let env_raw = std::env::var("TRACEVAULT_PROJECT")
635 .ok()
636 .map(|raw| raw.trim().to_string())
637 .filter(|raw| !raw.is_empty());
638 if env_project.is_none() {
639 if let Some(raw) = env_raw.as_deref() {
640 report.warnings.push(env_name_form_warning(raw));
641 }
642 }
643
644 let client = match resolve_client(project_root) {
648 Ok(client) => Some(client),
649 Err(e) => {
650 report.warnings.push(format!(
651 "warning: could not resolve credentials ({e}); server deduction not shown"
652 ));
653 None
654 }
655 };
656
657 let mut items: Option<Vec<ProjectListItem>> = None;
658 let project_flag = match (project_flag_name, client.as_ref()) {
659 (Some(name), Some(client)) => {
660 items = client.list_projects().await.ok();
661 let flag = items
662 .as_deref()
663 .and_then(|items| resolve_project_name(items, name).ok())
664 .map(|matched| ProjectBinding {
665 project_id: matched.id.to_string(),
666 project_name: matched.name.clone(),
667 updated_at: chrono::Utc::now().to_rfc3339(),
668 forced_until: None,
669 });
670 if flag.is_none() {
671 report.warnings.push(format!(
672 "warning: --project '{name}' could not be resolved; ignoring the override"
673 ));
674 }
675 flag
676 }
677 (Some(name), None) => {
678 report.warnings.push(offline_project_flag_warning(name));
679 None
680 }
681 (None, _) => None,
682 };
683
684 if items.is_none() && env_project.is_some() {
689 if let Some(client) = client.as_ref() {
690 items = client.list_projects().await.ok();
691 }
692 }
693
694 let (effective, invalid_id_warning) = status_effective(
695 project_flag,
696 env_project,
697 &session,
698 Some(&worktree),
699 config_project.clone(),
700 user_default,
701 );
702 report.warnings.extend(invalid_id_warning);
703 let effective = enrich_project_name(effective, items.as_deref());
704
705 if let Some(notice) = config
706 .as_ref()
707 .and_then(crate::commands::migrate::legacy_default_project_notice)
708 {
709 report.warnings.push(format!("warning: {notice}"));
710 }
711
712 report
713 .lines
714 .push(format_status(effective.as_ref().map(|(b, s)| (b, *s))));
715 if let Some((b, _)) = effective.as_ref() {
719 report.lines.extend(attribution_report(b));
720 }
721 let bound_repo = config
726 .as_ref()
727 .and_then(crate::resolution::binding_from_config);
728 report
729 .lines
730 .push(crate::commands::stream::recording_line_for(
731 &crate::commands::stream::recording_attribution_for(
732 &session,
733 &worktree,
734 bound_repo,
735 crate::user_default::load(),
736 config_project,
737 ),
738 ));
739
740 if let (Some(client), Some(url)) = (client.as_ref(), git_url.as_deref()) {
741 let outcome = client.resolve_project(url).await.map_err(|e| e.to_string());
744 let name = match &outcome {
745 Ok(ResolveProjectOutcome::Resolved(pid)) => {
746 deduced_project_name(*pid, items.as_deref())
747 }
748 _ => None,
749 };
750 report
751 .lines
752 .push(format_deduction(effective.is_some(), outcome, name));
753 }
754 report
755}
756
757#[cfg(test)]
758mod tests {
759 use super::*;
760 use std::io::{BufRead, BufReader, Write};
761 use std::net::TcpListener;
762 use std::thread;
763
764 #[test]
765 fn resolve_project_name_exact_match_and_miss() {
766 let items = vec![
767 ProjectListItem {
768 id: uuid::Uuid::nil(),
769 name: "payments".into(),
770 },
771 ProjectListItem {
772 id: uuid::Uuid::from_u128(2),
773 name: "web".into(),
774 },
775 ];
776 let ok = resolve_project_name(&items, "web").unwrap();
777 assert_eq!(ok.id, uuid::Uuid::from_u128(2));
778 let err = resolve_project_name(&items, "Web").unwrap_err(); assert!(err.contains("payments") && err.contains("web")); }
781
782 #[test]
783 fn switch_destination_user_flag_forces_user_default() {
784 assert!(matches!(
785 switch_destination(true, Some("sess-1".to_string())),
786 SwitchDest::UserDefault
787 ));
788 assert!(matches!(
789 switch_destination(true, None),
790 SwitchDest::UserDefault
791 ));
792 }
793
794 #[test]
795 fn switch_destination_session_when_present_and_no_user_flag() {
796 assert!(matches!(
797 switch_destination(false, Some("sess-1".to_string())),
798 SwitchDest::Session(id) if id == "sess-1"
799 ));
800 }
801
802 #[test]
803 fn switch_destination_user_default_when_no_session() {
804 assert!(matches!(
805 switch_destination(false, None),
806 SwitchDest::UserDefault
807 ));
808 }
809
810 #[test]
811 fn switching_with_explicit_stamps_a_lapse_time() {
812 let before = chrono::Utc::now();
813 let binding = apply_force(
814 ProjectBinding {
815 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
816 project_name: "p".into(),
817 updated_at: before.to_rfc3339(),
818 forced_until: None,
819 },
820 true,
821 );
822 let until = chrono::DateTime::parse_from_rfc3339(
823 binding.forced_until.as_deref().expect("force is stamped"),
824 )
825 .unwrap();
826 let expected = before
827 + chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS);
828 assert!((until.timestamp() - expected.timestamp()).abs() < 5);
829 }
830
831 #[test]
832 fn switching_without_explicit_stamps_no_lapse_time() {
833 let binding = apply_force(
834 ProjectBinding {
835 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
836 project_name: "p".into(),
837 updated_at: chrono::Utc::now().to_rfc3339(),
838 forced_until: Some("2020-01-01T00:00:00Z".into()),
839 },
840 false,
841 );
842 assert_eq!(
843 binding.forced_until, None,
844 "switching without --project-attribution explicit must CLEAR a stale force"
845 );
846 }
847
848 #[test]
852 fn format_force_line_distinguishes_a_live_force_from_a_lapsed_one() {
853 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
854 let live = format_force_line(&future);
855 assert!(live.contains("active until"), "got: {live}");
856 assert!(live.contains(&future), "got: {live}");
857
858 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
859 let lapsed = format_force_line(&past);
860 assert!(lapsed.contains("lapsed"), "got: {lapsed}");
861 assert!(lapsed.contains(&past), "got: {lapsed}");
862
863 for line in [&live, &lapsed] {
867 assert!(!line.contains("derived"), "got: {line}");
868 assert!(!line.contains("explicit"), "got: {line}");
869 assert!(!line.contains("membership"), "got: {line}");
870 }
871 }
872
873 #[test]
877 fn status_names_a_lapsed_force_as_lapsed_not_active() {
878 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
879 let line = format_force_line(&past);
880 assert!(line.contains("lapsed"), "got: {line}");
881 assert!(!line.contains("active until"), "got: {line}");
882 }
883
884 #[test]
895 fn status_names_unparseable_forced_until_as_not_in_force() {
896 let line = format_force_line("not-a-timestamp");
897 assert!(line.contains("not in force"), "got: {line}");
898 assert!(!line.contains("active until"), "got: {line}");
899
900 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
901 let mut _guard = crate::test_helpers::EnvVarGuard::new();
902 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
903 let b = ProjectBinding {
904 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
905 project_name: "payments".into(),
906 updated_at: "".into(),
907 forced_until: Some("not-a-timestamp".into()),
908 };
909 assert_eq!(
910 crate::commands::stream::attribution_mode(Some(&b)),
911 crate::api_client::AttributionMode::Derived,
912 "the reported state and the header must agree on an unreadable force"
913 );
914 }
915
916 #[test]
926 fn attribution_report_omits_the_lapse_line_when_there_is_no_persisted_force() {
927 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
928 let mut _guard = crate::test_helpers::EnvVarGuard::new();
929 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
930
931 let b = ProjectBinding {
932 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
933 project_name: "payments".into(),
934 updated_at: "".into(),
935 forced_until: None,
936 };
937 let lines = attribution_report(&b);
938 assert_eq!(
939 lines.len(),
940 1,
941 "an env-only force has no lapse to report, and must not be \
942 contradicted by a `derived` line: {lines:?}"
943 );
944 assert!(
945 lines[0].starts_with("attribution mode: explicit"),
946 "got: {lines:?}"
947 );
948 assert!(
949 !lines.iter().any(|l| l.contains("derived")),
950 "got: {lines:?}"
951 );
952 }
953
954 #[test]
958 fn attribution_report_keeps_the_lapse_line_for_a_persisted_force() {
959 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
960 let mut _guard = crate::test_helpers::EnvVarGuard::new();
961 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
962
963 let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
964 let b = ProjectBinding {
965 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
966 project_name: "payments".into(),
967 updated_at: "".into(),
968 forced_until: Some(until.clone()),
969 };
970 let lines = attribution_report(&b);
971 assert_eq!(lines.len(), 2, "got: {lines:?}");
972 assert!(
973 lines[0].starts_with("attribution mode: explicit"),
974 "got: {}",
975 lines[0]
976 );
977 assert!(lines[1].contains("active until"), "got: {}", lines[1]);
978 assert!(lines[1].contains(&until), "got: {}", lines[1]);
979 }
980
981 #[test]
987 fn attribution_report_reports_a_lapsed_persisted_force_as_derived() {
988 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
989 let mut _guard = crate::test_helpers::EnvVarGuard::new();
990 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
991
992 let b = ProjectBinding {
993 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
994 project_name: "payments".into(),
995 updated_at: "".into(),
996 forced_until: Some((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()),
997 };
998 let lines = attribution_report(&b);
999 assert_eq!(lines.len(), 2, "got: {lines:?}");
1000 assert!(
1001 lines[0].starts_with("attribution mode: derived"),
1002 "got: {}",
1003 lines[0]
1004 );
1005 assert!(
1006 lines[1].starts_with("persisted force: lapsed"),
1007 "got: {}",
1008 lines[1]
1009 );
1010 }
1011
1012 #[test]
1029 fn a_lapsed_persisted_force_never_contradicts_an_env_force() {
1030 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1031 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1032 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1033
1034 let lapsed = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
1035 for forced_until in [lapsed.as_str(), "not-a-timestamp"] {
1036 let b = ProjectBinding {
1037 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1038 project_name: "payments".into(),
1039 updated_at: "".into(),
1040 forced_until: Some(forced_until.to_string()),
1041 };
1042 let lines = attribution_report(&b);
1043 assert_eq!(lines.len(), 2, "{forced_until}: got {lines:?}");
1044 assert!(
1045 lines[0].starts_with("attribution mode: explicit"),
1046 "{forced_until}: the env force decides the mode: {lines:?}"
1047 );
1048 assert!(
1052 !lines[1].contains("derived"),
1053 "{forced_until}: the detail line must not render a competing \
1054 verdict while the env force makes this send explicit: {lines:?}"
1055 );
1056 assert!(
1057 !lines[1].contains("membership is checked"),
1058 "{forced_until}: membership is NOT being checked here: {lines:?}"
1059 );
1060 }
1061 }
1062
1063 #[test]
1071 fn switch_report_names_the_env_force_and_never_claims_derived() {
1072 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1073 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1074 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1075
1076 let b = ProjectBinding {
1077 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1078 project_name: "payments".into(),
1079 updated_at: "".into(),
1080 forced_until: None,
1081 };
1082
1083 for dest in [
1084 SwitchDest::Session("sess-1".to_string()),
1085 SwitchDest::UserDefault,
1086 ] {
1087 let lines = switch_report(&dest, &b, None);
1088 assert!(
1089 lines[0].contains("payments"),
1090 "the first line still says what was bound: {lines:?}"
1091 );
1092 assert!(
1093 lines
1094 .iter()
1095 .any(|l| l.starts_with("attribution mode: explicit")),
1096 "a `switch` in an explicit shell must say so: {lines:?}"
1097 );
1098 assert!(
1099 !lines.iter().any(|l| l.contains("derived")),
1100 "{dest:?}: `switch` must not claim membership is checked while \
1101 every hook in this shell sends `explicit`: {lines:?}"
1102 );
1103 }
1104 }
1105
1106 #[test]
1110 fn switch_report_names_the_lapse_it_just_stamped() {
1111 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1112 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1113 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
1114
1115 let b = apply_force(
1116 ProjectBinding {
1117 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1118 project_name: "payments".into(),
1119 updated_at: "".into(),
1120 forced_until: None,
1121 },
1122 true,
1123 );
1124 let lines = switch_report(&SwitchDest::Session("sess-1".to_string()), &b, None);
1125 assert_eq!(lines.len(), 3, "got: {lines:?}");
1126 assert!(
1127 lines[1].starts_with("attribution mode: explicit"),
1128 "got: {}",
1129 lines[1]
1130 );
1131 assert!(
1132 lines[2].starts_with("persisted force: active until"),
1133 "got: {}",
1134 lines[2]
1135 );
1136 }
1137
1138 fn pb(name: &str) -> ProjectBinding {
1139 ProjectBinding {
1140 project_id: format!("id-{name}"),
1141 project_name: name.into(),
1142 updated_at: "t".into(),
1143 forced_until: None,
1144 }
1145 }
1146
1147 #[test]
1148 fn format_status_unbound() {
1149 assert_eq!(
1150 format_status(None),
1151 "no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo"
1152 );
1153 }
1154
1155 #[test]
1156 fn format_status_project_flag() {
1157 let b = pb("web");
1158 assert_eq!(
1159 format_status(Some((&b, ProjectSource::ProjectFlag))),
1160 "project: web via --project override"
1161 );
1162 }
1163
1164 #[test]
1165 fn format_status_session_active() {
1166 let b = pb("payments");
1167 assert_eq!(
1168 format_status(Some((&b, ProjectSource::SessionActive))),
1169 "project: payments via session (project switch)"
1170 );
1171 }
1172
1173 #[test]
1174 fn format_status_falls_back_to_id_when_name_empty() {
1175 let b = ProjectBinding {
1178 project_id: "some-id".into(),
1179 project_name: String::new(),
1180 updated_at: "".into(),
1181 forced_until: None,
1182 };
1183 assert_eq!(
1184 format_status(Some((&b, ProjectSource::UserDefault))),
1185 "project: some-id via user default (project switch --user)"
1186 );
1187 }
1188
1189 #[test]
1190 fn format_status_env() {
1191 let b = pb("payments");
1192 assert_eq!(
1193 format_status(Some((&b, ProjectSource::Env))),
1194 "project: payments via TRACEVAULT_PROJECT (environment)"
1195 );
1196 }
1197
1198 #[test]
1199 fn invalid_capture_id_warning_names_tier_and_rewrite_command() {
1200 let b = ProjectBinding {
1201 project_id: "not-a-uuid".into(),
1202 project_name: "payments".into(),
1203 updated_at: "".into(),
1204 forced_until: None,
1205 };
1206 assert_eq!(
1207 invalid_capture_id_warning(&b, ProjectSource::UserDefault),
1208 "warning: project payments — user default (project switch --user), but the saved project_id is not a valid id and is dropped at capture time; run `tracevault project switch --user <name>` to rewrite it"
1209 );
1210 assert_eq!(
1211 invalid_capture_id_warning(&b, ProjectSource::Workspace),
1212 "warning: project payments — workspace .tracevault/config.toml, but the saved project_id is not a valid id and is dropped at capture time; run `tracevault init --workspace --project <name>` to rewrite it"
1213 );
1214 }
1215
1216 #[test]
1219 fn status_effective_drops_a_non_uuid_binding_with_a_warning_naming_the_tier() {
1220 let session = SessionState {
1221 active_project: Some(ProjectBinding {
1222 project_id: "not-a-uuid".into(),
1223 project_name: "payments".into(),
1224 updated_at: "".into(),
1225 forced_until: None,
1226 }),
1227 ..Default::default()
1228 };
1229 let (effective, warning) = status_effective(None, None, &session, None, None, None);
1230 assert!(effective.is_none(), "{effective:?}");
1231 let warning = warning.expect("a dropped binding must be explained");
1232 assert!(
1233 warning.contains("session (project switch)"),
1234 "must name the tier: {warning}"
1235 );
1236 assert!(warning.contains("payments"), "{warning}");
1237
1238 let pid = uuid::Uuid::from_u128(5);
1240 let valid = SessionState {
1241 active_project: Some(ProjectBinding {
1242 project_id: pid.to_string(),
1243 project_name: "web".into(),
1244 updated_at: "".into(),
1245 forced_until: None,
1246 }),
1247 ..Default::default()
1248 };
1249 let (effective, warning) = status_effective(None, None, &valid, None, None, None);
1250 assert_eq!(
1251 effective.map(|(b, s)| (b.project_id, s)),
1252 Some((pid.to_string(), ProjectSource::SessionActive))
1253 );
1254 assert_eq!(warning, None);
1255 }
1256
1257 #[test]
1262 fn status_effective_places_env_at_rung_three() {
1263 let u = uuid::Uuid::from_u128;
1264 let bind = |id: uuid::Uuid, name: &str| ProjectBinding {
1265 project_id: id.to_string(),
1266 project_name: name.into(),
1267 updated_at: "".into(),
1268 forced_until: None,
1269 };
1270 let session = SessionState {
1271 active_project: Some(bind(u(2), "session")),
1272 ..Default::default()
1273 };
1274
1275 let (effective, _) = status_effective(
1277 None,
1278 Some(bind(u(9), "env")),
1279 &session,
1280 None,
1281 None,
1282 Some(bind(u(3), "user")),
1283 );
1284 assert_eq!(
1285 effective.map(|(b, s)| (b.project_id, s)),
1286 Some((u(9).to_string(), ProjectSource::Env))
1287 );
1288
1289 let (effective, _) = status_effective(
1291 Some(bind(u(1), "flag")),
1292 Some(bind(u(9), "env")),
1293 &session,
1294 None,
1295 None,
1296 Some(bind(u(3), "user")),
1297 );
1298 assert_eq!(
1299 effective.map(|(b, s)| (b.project_id, s)),
1300 Some((u(1).to_string(), ProjectSource::ProjectFlag))
1301 );
1302 }
1303
1304 #[test]
1305 fn offline_project_flag_warning_says_the_override_is_ignored() {
1306 assert_eq!(
1307 offline_project_flag_warning("web"),
1308 "warning: --project 'web' cannot be resolved without server credentials; ignoring the override"
1309 );
1310 }
1311
1312 #[test]
1316 fn env_name_form_warning_says_only_the_uuid_form_is_used() {
1317 let warning = env_name_form_warning("payments");
1318 assert!(warning.contains("payments"), "{warning}");
1319 assert!(warning.contains("UUID form"), "{warning}");
1320 assert!(
1321 warning.contains("not used") || warning.contains("ignored"),
1322 "{warning}"
1323 );
1324 }
1325
1326 const DEDUCED: uuid::Uuid = uuid::Uuid::from_u128(2);
1327
1328 #[test]
1329 fn format_deduction_resolved_bound() {
1330 assert_eq!(
1331 format_deduction(true, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1332 format!(
1333 "server deduction for this repo: {DEDUCED} (not used: the local binding above wins)"
1334 )
1335 );
1336 }
1337
1338 #[test]
1339 fn format_deduction_resolved_unbound() {
1340 assert_eq!(
1341 format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1342 format!("server deduction for this repo: {DEDUCED} (events will land here if a repo is bound)")
1343 );
1344 }
1345
1346 #[test]
1347 fn format_deduction_resolved_uses_name_when_known() {
1348 let items = items();
1349 let name = deduced_project_name(DEDUCED, Some(&items));
1350 assert_eq!(name, Some("web"));
1351 assert_eq!(
1352 format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), name),
1353 "server deduction for this repo: web (events will land here if a repo is bound)"
1354 );
1355 }
1356
1357 #[test]
1358 fn deduced_project_name_none_without_list_or_match() {
1359 assert_eq!(deduced_project_name(DEDUCED, None), None);
1360 assert_eq!(
1361 deduced_project_name(uuid::Uuid::from_u128(999), Some(&items())),
1362 None
1363 );
1364 }
1365
1366 #[test]
1367 fn format_deduction_ambiguous_bound() {
1368 assert_eq!(
1369 format_deduction(true, Ok(ResolveProjectOutcome::Ambiguous), None),
1370 "server deduction for this repo: ambiguous (multiple projects) — not used, the local binding above wins"
1371 );
1372 }
1373
1374 #[test]
1375 fn format_deduction_ambiguous_unbound() {
1376 assert_eq!(
1377 format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
1378 "server deduction for this repo: ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
1379 );
1380 }
1381
1382 #[test]
1383 fn format_deduction_none() {
1384 for bound in [true, false] {
1385 assert_eq!(
1386 format_deduction(bound, Ok(ResolveProjectOutcome::None), None),
1387 "server deduction for this repo: none"
1388 );
1389 }
1390 }
1391
1392 #[test]
1393 fn format_deduction_err() {
1394 for bound in [true, false] {
1395 assert_eq!(
1396 format_deduction(bound, Err("connection refused".into()), None),
1397 "server deduction for this repo: unavailable (connection refused)"
1398 );
1399 }
1400 }
1401
1402 #[test]
1403 fn format_status_user_default() {
1404 let b = pb("payments");
1405 assert_eq!(
1406 format_status(Some((&b, ProjectSource::UserDefault))),
1407 "project: payments via user default (project switch --user)"
1408 );
1409 }
1410
1411 fn spawn_once(response: String) -> String {
1414 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1415 let addr = listener.local_addr().unwrap();
1416 let response: &'static str = Box::leak(response.into_boxed_str());
1417 thread::spawn(move || {
1418 if let Ok((stream, _)) = listener.accept() {
1419 let mut reader = BufReader::new(stream);
1420 let mut request_line = String::new();
1421 let _ = reader.read_line(&mut request_line);
1422 let mut stream = reader.into_inner();
1423 let _ = stream.write_all(response.as_bytes());
1424 let _ = stream.flush();
1425 }
1426 });
1427 format!("http://{addr}")
1428 }
1429
1430 fn spawn_n(responses: Vec<String>) -> String {
1434 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1435 let addr = listener.local_addr().unwrap();
1436 thread::spawn(move || {
1437 for response in responses {
1438 let response: &'static str = Box::leak(response.into_boxed_str());
1439 if let Ok((stream, _)) = listener.accept() {
1440 let mut reader = BufReader::new(stream);
1441 let mut request_line = String::new();
1442 let _ = reader.read_line(&mut request_line);
1443 let mut stream = reader.into_inner();
1444 let _ = stream.write_all(response.as_bytes());
1445 let _ = stream.flush();
1446 }
1447 }
1448 });
1449 format!("http://{addr}")
1450 }
1451
1452 fn http_200(body: &str) -> String {
1453 format!(
1454 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1455 body.len(),
1456 body
1457 )
1458 }
1459
1460 #[tokio::test]
1467 async fn project_switch_happy_path_writes_active_project_to_session_file() {
1468 let tmp = tempfile::tempdir().unwrap();
1469 crate::test_helpers::init_git_repo(tmp.path()); let _env_lock = crate::test_helpers::lock_env_mutation().await;
1480 let state_tmp = tempfile::tempdir().unwrap();
1481 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1482 _guard.set("XDG_STATE_HOME", state_tmp.path());
1483
1484 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
1485 let base = spawn_once(http_200(list));
1486 let client = ApiClient::new(&base, Some("tok"));
1487
1488 let (binding, note) =
1489 resolve_switch_project("web", &client, CodebaseCheck::Enforce, tmp.path())
1490 .await
1491 .expect("expected Ok binding");
1492 assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
1493 assert_eq!(binding.project_name, "web");
1494 assert_eq!(note, None, "no remote to check against, so nothing to note");
1495
1496 let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
1497 let mut state = session_state::load(&session_id);
1498 state.active_project = Some(binding.clone());
1499 session_state::save(&session_id, &state).expect("save must succeed");
1500
1501 let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
1502 assert!(sessions_dir.starts_with(state_tmp.path()));
1503 let loaded = session_state::load_from(&sessions_dir, &session_id);
1504 assert_eq!(loaded.active_project, Some(binding));
1505 }
1506
1507 #[tokio::test]
1508 async fn project_switch_errors_when_name_not_found() {
1509 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
1510 let base = spawn_once(http_200(list));
1511 let client = ApiClient::new(&base, Some("tok"));
1512
1513 let err = resolve_switch_project(
1514 "web",
1515 &client,
1516 CodebaseCheck::Skip,
1517 Path::new("/nonexistent"),
1518 )
1519 .await
1520 .expect_err("expected Err for an unknown project name");
1521 let msg = err.to_string();
1522 assert!(msg.contains("not found"), "got: {msg}");
1523 assert!(msg.contains("payments"), "got: {msg}");
1524 }
1525
1526 #[tokio::test]
1527 async fn project_switch_errors_when_project_does_not_contain_codebase() {
1528 let tmp = tempfile::tempdir().unwrap();
1529 crate::test_helpers::init_git_repo(tmp.path());
1530 let ok = std::process::Command::new("git")
1531 .args([
1532 "-C",
1533 &tmp.path().to_string_lossy(),
1534 "remote",
1535 "add",
1536 "origin",
1537 "git@github.com:org/repo.git",
1538 ])
1539 .status()
1540 .expect("git remote add failed")
1541 .success();
1542 assert!(ok, "git remote add must succeed");
1543
1544 let list =
1545 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1546 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1547 let remote = format!(
1548 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1549 );
1550 let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1551 let detail = format!(
1552 r#"{{"id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_url":"https://github.com/org/repo.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{{"id":"{codebase_repo_id}","name":"repo"}}]}}"#
1553 );
1554 let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1555 let base = spawn_n(vec![
1556 http_200(&list),
1557 http_200(&remote),
1558 http_200(&detail),
1559 http_200(project_detail),
1560 ]);
1561 let client = ApiClient::new(&base, Some("tok"));
1562
1563 let err = resolve_switch_project("payments", &client, CodebaseCheck::Enforce, tmp.path())
1564 .await
1565 .expect_err("expected Err: project doesn't contain the current codebase");
1566 assert!(
1567 err.to_string()
1568 .contains("does not contain the current codebase"),
1569 "got: {err}"
1570 );
1571 }
1572
1573 #[tokio::test]
1588 async fn explicit_attribution_binds_a_non_member_project_and_says_so() {
1589 let tmp = tempfile::tempdir().unwrap();
1590 crate::test_helpers::init_git_repo(tmp.path());
1591 let ok = std::process::Command::new("git")
1592 .args([
1593 "-C",
1594 &tmp.path().to_string_lossy(),
1595 "remote",
1596 "add",
1597 "origin",
1598 "git@github.com:org/repo.git",
1599 ])
1600 .status()
1601 .expect("git remote add failed")
1602 .success();
1603 assert!(ok, "git remote add must succeed");
1604
1605 let list =
1606 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1607 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1608 let remote = format!(
1609 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1610 );
1611 let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1612 let detail = format!(
1613 r#"{{"id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_url":"https://github.com/org/repo.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{{"id":"{codebase_repo_id}","name":"repo"}}]}}"#
1614 );
1615 let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1616 let base = spawn_n(vec![
1617 http_200(&list),
1618 http_200(&remote),
1619 http_200(&detail),
1620 http_200(project_detail),
1621 ]);
1622 let client = ApiClient::new(&base, Some("tok"));
1623
1624 let (binding, note) =
1625 resolve_switch_project("payments", &client, CodebaseCheck::Report, tmp.path())
1626 .await
1627 .expect("a forced switch must not be blocked by the containment check");
1628 assert_eq!(binding.project_id, "11111111-1111-4111-8111-111111111111");
1629
1630 let note = note.expect("the user must still be told the project is not a member");
1631 assert!(
1632 note.contains("does not contain the current codebase"),
1633 "the fact must be stated: {note}"
1634 );
1635 assert!(
1636 note.contains("--project-attribution explicit"),
1637 "must say what made it deliberate: {note}"
1638 );
1639 assert!(
1640 note.contains("Operator") && note.contains("ingest"),
1641 "must say where the requirement is actually enforced: {note}"
1642 );
1643
1644 assert!(
1646 !note.starts_with("error"),
1647 "this is informational, not a failure: {note}"
1648 );
1649 }
1650
1651 #[test]
1658 fn only_an_explicit_session_switch_downgrades_the_containment_check() {
1659 let session = SwitchDest::Session("s".into());
1660 assert_eq!(
1661 codebase_check_for(&session, true),
1662 CodebaseCheck::Report,
1663 "--project-attribution explicit must not be blocked"
1664 );
1665 assert_eq!(
1666 codebase_check_for(&session, false),
1667 CodebaseCheck::Enforce,
1668 "an ordinary session switch keeps erroring"
1669 );
1670 assert_eq!(
1672 codebase_check_for(&SwitchDest::UserDefault, true),
1673 CodebaseCheck::Skip
1674 );
1675 assert_eq!(
1676 codebase_check_for(&SwitchDest::UserDefault, false),
1677 CodebaseCheck::Skip
1678 );
1679 }
1680
1681 #[tokio::test]
1715 async fn switch_without_session_or_user_flag_skips_codebase_check() {
1716 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1717 let tmp = tempfile::tempdir().unwrap();
1718 crate::test_helpers::init_git_repo(tmp.path());
1719 let ok = std::process::Command::new("git")
1720 .args([
1721 "-C",
1722 &tmp.path().to_string_lossy(),
1723 "remote",
1724 "add",
1725 "origin",
1726 "git@github.com:org/repo.git",
1727 ])
1728 .status()
1729 .expect("git remote add failed")
1730 .success();
1731 assert!(ok, "git remote add must succeed");
1732
1733 let list =
1734 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1735 let base = spawn_once(http_200(&list));
1736
1737 let config_dir = tmp.path().join(".tracevault");
1738 std::fs::create_dir_all(&config_dir).unwrap();
1739 std::fs::write(
1740 config_dir.join("config.toml"),
1741 format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\n"),
1742 )
1743 .unwrap();
1744
1745 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1760 _guard.remove("TRACEVAULT_SESSION_ID");
1761 _guard.remove("AMP_CURRENT_THREAD_ID");
1762 _guard.set("XDG_CONFIG_HOME", tmp.path());
1763 _guard.set("TRACEVAULT_SERVER_URL", &base);
1764 _guard.set("TRACEVAULT_API_KEY", "tok");
1765
1766 let result = switch("payments", false, None, "derived", tmp.path(), tmp.path()).await;
1767 assert!(
1768 result.is_ok(),
1769 "expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
1770 );
1771
1772 let saved = crate::user_project_default::load();
1773 assert_eq!(
1774 saved.map(|b| b.project_name),
1775 Some("payments".to_string()),
1776 "no-session switch must fall back to the user-level default binding"
1777 );
1778 }
1779
1780 fn items() -> Vec<ProjectListItem> {
1781 vec![
1782 ProjectListItem {
1783 id: uuid::Uuid::from_u128(1),
1784 name: "payments".into(),
1785 },
1786 ProjectListItem {
1787 id: uuid::Uuid::from_u128(2),
1788 name: "web".into(),
1789 },
1790 ]
1791 }
1792
1793 fn nameless(id: uuid::Uuid, source: ProjectSource) -> (ProjectBinding, ProjectSource) {
1799 (
1800 ProjectBinding {
1801 project_id: id.to_string(),
1802 project_name: String::new(),
1803 updated_at: "".into(),
1804 forced_until: None,
1805 },
1806 source,
1807 )
1808 }
1809
1810 #[test]
1814 fn enrich_project_name_fills_in_name_when_id_found_in_list() {
1815 let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1816 let (b, source) = enrich_project_name(effective, Some(&items())).unwrap();
1817 assert_eq!(b.project_name, "web");
1818 assert_eq!(source, ProjectSource::Env);
1819 }
1820
1821 #[test]
1822 fn enrich_project_name_leaves_empty_when_no_list_available() {
1823 let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1824 let (b, _source) = enrich_project_name(effective, None).unwrap();
1825 assert_eq!(b.project_name, "");
1826 }
1827
1828 #[test]
1829 fn enrich_project_name_leaves_empty_when_id_not_in_list() {
1830 let effective = Some(nameless(uuid::Uuid::from_u128(999), ProjectSource::Env));
1831 let (b, _source) = enrich_project_name(effective, Some(&items())).unwrap();
1832 assert_eq!(b.project_name, "");
1833 }
1834
1835 #[test]
1836 fn enrich_project_name_leaves_a_populated_name_untouched() {
1837 let b = pb("payments");
1841 let effective = Some((b.clone(), ProjectSource::SessionActive));
1842 let (out, source) = enrich_project_name(effective, Some(&items())).unwrap();
1843 assert_eq!(out, b);
1844 assert_eq!(source, ProjectSource::SessionActive);
1845 }
1846
1847 #[test]
1848 fn enrich_project_name_passes_through_none() {
1849 assert!(enrich_project_name(None, Some(&items())).is_none());
1850 }
1851
1852 #[tokio::test]
1862 async fn project_status_effective_project_matches_capture_project() {
1863 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1864 let tmp = tempfile::tempdir().unwrap();
1865 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1866 _guard.set("XDG_CONFIG_HOME", tmp.path());
1867 _guard.set("HOME", tmp.path());
1868
1869 let u = uuid::Uuid::from_u128;
1870 let bind = |id: String| ProjectBinding {
1871 project_id: id,
1872 project_name: "n".into(),
1873 updated_at: "".into(),
1874 forced_until: None,
1875 };
1876 let worktree = "/wt";
1877 let subagent_session = {
1878 let mut s = SessionState {
1879 active_project: Some(bind(u(2).to_string())),
1880 ..Default::default()
1881 };
1882 s.subagent_projects
1883 .insert(worktree.into(), bind(u(1).to_string()));
1884 s
1885 };
1886 let active_session = SessionState {
1887 active_project: Some(bind(u(2).to_string())),
1888 ..Default::default()
1889 };
1890 let bad_active_session = SessionState {
1891 active_project: Some(bind("not-a-uuid".into())),
1892 ..Default::default()
1893 };
1894
1895 type Case = (
1898 &'static str,
1899 SessionState,
1900 Option<String>,
1901 Option<String>,
1902 Option<uuid::Uuid>,
1903 );
1904 let cases: Vec<Case> = vec![
1905 (
1906 "(a) subagent override + session active + user default",
1907 subagent_session,
1908 Some(u(3).to_string()),
1909 None,
1910 Some(u(1)),
1911 ),
1912 (
1913 "(b) session active + user default",
1914 active_session.clone(),
1915 Some(u(3).to_string()),
1916 None,
1917 Some(u(2)),
1918 ),
1919 (
1920 "(c) user default only",
1921 SessionState::default(),
1922 Some(u(3).to_string()),
1923 None,
1924 Some(u(3)),
1925 ),
1926 ("(d) nothing", SessionState::default(), None, None, None),
1927 (
1928 "(e) user default with a non-UUID project_id",
1929 SessionState::default(),
1930 Some("not-a-uuid".into()),
1931 None,
1932 None,
1933 ),
1934 (
1935 "(f) non-UUID session active shadows a valid user default",
1936 bad_active_session,
1937 Some(u(3).to_string()),
1938 None,
1939 None,
1940 ),
1941 (
1944 "(g) TRACEVAULT_PROJECT (UUID) outranks session active and the user default",
1945 active_session.clone(),
1946 Some(u(3).to_string()),
1947 Some(u(4).to_string()),
1948 Some(u(4)),
1949 ),
1950 (
1953 "(h) TRACEVAULT_PROJECT (NAME) is ignored by both",
1954 active_session,
1955 Some(u(3).to_string()),
1956 Some("payments".into()),
1957 Some(u(2)),
1958 ),
1959 ];
1960 let session_active = || SessionState {
1964 active_project: Some(bind(u(2).to_string())),
1965 ..Default::default()
1966 };
1967 type WorkspaceCase = (
1970 &'static str,
1971 SessionState,
1972 Option<String>,
1973 Option<String>,
1974 Option<String>,
1975 Option<uuid::Uuid>,
1976 );
1977 let workspace_cases: Vec<WorkspaceCase> = vec![
1978 (
1979 "(i) workspace config outranks the user default",
1980 SessionState::default(),
1981 Some(u(3).to_string()),
1982 None,
1983 Some(u(5).to_string()),
1984 Some(u(5)),
1985 ),
1986 (
1987 "(j) session active (project switch) outranks the workspace config",
1988 session_active(),
1989 Some(u(3).to_string()),
1990 None,
1991 Some(u(5).to_string()),
1992 Some(u(2)),
1993 ),
1994 (
1995 "(k) TRACEVAULT_PROJECT (UUID) outranks the workspace config",
1996 SessionState::default(),
1997 None,
1998 Some(u(4).to_string()),
1999 Some(u(5).to_string()),
2000 Some(u(4)),
2001 ),
2002 (
2003 "(l) a non-UUID workspace project_id is dropped by both, shadowing the user default",
2004 SessionState::default(),
2005 Some(u(3).to_string()),
2006 None,
2007 Some("not-a-uuid".into()),
2008 None,
2009 ),
2010 ];
2011 let cases = cases
2012 .into_iter()
2013 .map(|(label, session, user, env, expected)| {
2014 (label, session, user, env, None, expected)
2015 })
2016 .chain(workspace_cases);
2017
2018 for (label, session, user_default, env_project, config_project, expected) in cases {
2019 match &user_default {
2020 Some(id) => crate::user_project_default::save(&bind(id.clone())).unwrap(),
2021 None => crate::user_project_default::clear().unwrap(),
2022 }
2023 match &env_project {
2024 Some(v) => _guard.set("TRACEVAULT_PROJECT", v),
2025 None => _guard.remove("TRACEVAULT_PROJECT"),
2026 }
2027 let config_project = config_project.and_then(|id| {
2029 crate::resolution::project_from_config(&crate::config::TracevaultConfig {
2030 project_id: Some(id),
2031 ..Default::default()
2032 })
2033 });
2034 let status_pid = status_effective(
2035 None,
2036 crate::commands::stream::env_project_binding(),
2037 &session,
2038 Some(worktree),
2039 config_project.clone(),
2040 crate::user_project_default::load(),
2041 )
2042 .0
2043 .and_then(|(b, _)| capture_project_id(&b));
2044 let ingest_pid =
2045 crate::commands::stream::capture_project(&session, Some(worktree), config_project);
2046 assert_eq!(
2047 status_pid, ingest_pid,
2048 "{label}: status and ingest disagree"
2049 );
2050 assert_eq!(status_pid, expected, "{label}");
2051 }
2052 crate::user_project_default::clear().unwrap();
2053 }
2054
2055 #[tokio::test]
2058 async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
2059 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2060 let tmp = tempfile::tempdir().unwrap();
2061 crate::test_helpers::init_git_repo(tmp.path());
2062 let ok = std::process::Command::new("git")
2063 .args([
2064 "-C",
2065 &tmp.path().to_string_lossy(),
2066 "remote",
2067 "add",
2068 "origin",
2069 "git@github.com:org/repo.git",
2070 ])
2071 .status()
2072 .expect("git remote add failed")
2073 .success();
2074 assert!(ok, "git remote add must succeed");
2075
2076 let conflict = "HTTP/1.1 409 Conflict\r\nContent-Type: application/json\r\nContent-Length: 20\r\nConnection: close\r\n\r\n{\"error\":\"multiple\"}";
2078 let base = spawn_n(vec![conflict.to_string(), conflict.to_string()]);
2079
2080 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2084 _guard.set("TRACEVAULT_SERVER_URL", &base);
2085 _guard.set("TRACEVAULT_API_KEY", "tok");
2086 _guard.set("XDG_CONFIG_HOME", tmp.path());
2087 _guard.set("HOME", tmp.path());
2088 _guard.remove("TRACEVAULT_SESSION_ID");
2089 _guard.remove("AMP_CURRENT_THREAD_ID");
2090 _guard.remove("TRACEVAULT_PROJECT");
2096 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2097
2098 let result = status(None, None, tmp.path(), tmp.path()).await;
2099 assert!(
2100 result.is_ok(),
2101 "status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
2102 );
2103
2104 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2105 assert_eq!(
2106 report.lines,
2107 vec![
2108 format_status(None),
2109 crate::commands::stream::recording_line(None),
2110 format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
2111 ],
2112 "the ambiguous deduction is reported on its own line"
2113 );
2114 }
2115
2116 #[tokio::test]
2122 async fn status_in_the_orchestrator_configuration_names_the_user_default() {
2123 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2124 let tmp = tempfile::tempdir().unwrap();
2125 let repo = tmp.path().join("repo");
2126 std::fs::create_dir_all(&repo).unwrap();
2127 crate::test_helpers::init_git_repo(&repo);
2128 let ok = std::process::Command::new("git")
2129 .args([
2130 "-C",
2131 &repo.to_string_lossy(),
2132 "remote",
2133 "add",
2134 "origin",
2135 "git@github.com:org/repo.git",
2136 ])
2137 .status()
2138 .expect("git remote add failed")
2139 .success();
2140 assert!(ok, "git remote add must succeed");
2141
2142 let deduced_a = uuid::Uuid::from_u128(0xA);
2143 let base = spawn_once(http_200(&format!(r#"{{"project_id":"{deduced_a}"}}"#)));
2144
2145 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2146 _guard.set("TRACEVAULT_SERVER_URL", &base);
2147 _guard.set("TRACEVAULT_API_KEY", "tok");
2148 _guard.set("XDG_CONFIG_HOME", tmp.path());
2149 _guard.set("HOME", tmp.path());
2150 _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2151 _guard.remove("TRACEVAULT_SESSION_ID");
2152 _guard.remove("AMP_CURRENT_THREAD_ID");
2153 _guard.remove("TRACEVAULT_PROJECT");
2157 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2158
2159 let default_b = ProjectBinding {
2160 project_id: uuid::Uuid::from_u128(0xB).to_string(),
2161 project_name: "project-b".into(),
2162 updated_at: "".into(),
2163 forced_until: None,
2164 };
2165 crate::user_project_default::save(&default_b).unwrap();
2166
2167 let report = status_report(None, None, &repo, &repo).await;
2168
2169 assert_eq!(
2170 report.lines,
2171 vec![
2172 "project: project-b via user default (project switch --user)".to_string(),
2173 "attribution mode: derived (TraceVault checks repo/project membership)"
2174 .to_string(),
2175 crate::commands::stream::recording_line(Some(
2178 &crate::commands::stream::Attribution::ProjectOnly {
2179 project_id: uuid::Uuid::from_u128(0xB),
2180 }
2181 )),
2182 format!(
2183 "server deduction for this repo: {deduced_a} (not used: the local binding above wins)"
2184 ),
2185 ]
2186 );
2187 }
2188
2189 #[tokio::test]
2197 async fn status_reports_env_uuid_as_the_effective_tier_with_its_name() {
2198 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2199 let tmp = tempfile::tempdir().unwrap();
2200
2201 let uuid = "11111111-1111-4111-8111-111111111111";
2202 let list = format!(r#"[{{"id":"{uuid}","name":"payments"}}]"#);
2203 let base = spawn_once(http_200(&list));
2204
2205 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2206 _guard.set("XDG_CONFIG_HOME", tmp.path());
2207 _guard.set("HOME", tmp.path());
2208 _guard.set("TRACEVAULT_SERVER_URL", &base);
2209 _guard.set("TRACEVAULT_API_KEY", "tok");
2210 _guard.set("TRACEVAULT_PROJECT", uuid);
2211 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2212 _guard.remove("TRACEVAULT_SESSION_ID");
2213 _guard.remove("AMP_CURRENT_THREAD_ID");
2214
2215 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2216 assert_eq!(
2217 report.lines[0], "project: payments via TRACEVAULT_PROJECT (environment)",
2218 "got: {:?}",
2219 report.lines
2220 );
2221 assert!(
2222 report
2223 .warnings
2224 .iter()
2225 .all(|w| !w.contains("TRACEVAULT_PROJECT")),
2226 "the UUID form is honoured at capture time and needs no caveat: {:?}",
2227 report.warnings
2228 );
2229 }
2230
2231 #[tokio::test]
2239 async fn status_warns_that_an_env_name_is_not_used_and_falls_through() {
2240 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2241 let tmp = tempfile::tempdir().unwrap();
2242
2243 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2244 _guard.set("XDG_CONFIG_HOME", tmp.path());
2245 _guard.set("HOME", tmp.path());
2246 _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2247 _guard.remove("TRACEVAULT_SERVER_URL");
2248 _guard.remove("TRACEVAULT_API_KEY");
2249 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2250 _guard.set("TRACEVAULT_PROJECT", "payments");
2251
2252 let session_id = "vis305-env-name-form";
2253 let pid = uuid::Uuid::from_u128(0x5E);
2254 crate::session_state::save(
2255 session_id,
2256 &SessionState {
2257 active_project: Some(ProjectBinding {
2258 project_id: pid.to_string(),
2259 project_name: "session-project".into(),
2260 updated_at: "".into(),
2261 forced_until: None,
2262 }),
2263 ..Default::default()
2264 },
2265 )
2266 .unwrap();
2267
2268 let report = status_report(Some(session_id), None, tmp.path(), tmp.path()).await;
2269 assert_eq!(
2270 report.lines[0], "project: session-project via session (project switch)",
2271 "a NAME must not become the effective tier: {:?}",
2272 report.lines
2273 );
2274 assert!(
2275 report
2276 .warnings
2277 .iter()
2278 .any(|w| w.contains("TRACEVAULT_PROJECT") && w.contains("UUID form")),
2279 "the ignored NAME must be explained: {:?}",
2280 report.warnings
2281 );
2282 }
2283
2284 #[tokio::test]
2289 async fn status_reports_env_uuid_even_without_a_client() {
2290 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2291 let tmp = tempfile::tempdir().unwrap();
2292
2293 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2294 _guard.set("XDG_CONFIG_HOME", tmp.path());
2295 _guard.set("HOME", tmp.path());
2296 _guard.remove("TRACEVAULT_SERVER_URL");
2297 _guard.remove("TRACEVAULT_API_KEY");
2298 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2299 let uuid = "33333333-3333-4333-8333-333333333333";
2300 _guard.set("TRACEVAULT_PROJECT", uuid);
2301
2302 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2303 assert_eq!(
2304 report.lines[0],
2305 format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2306 "got: {:?}",
2307 report.lines
2308 );
2309 }
2310
2311 #[tokio::test]
2319 async fn status_reports_explicit_via_env_even_when_the_binding_itself_is_not_forced() {
2320 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2321 let tmp = tempfile::tempdir().unwrap();
2322
2323 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2324 _guard.set("XDG_CONFIG_HOME", tmp.path());
2325 _guard.set("HOME", tmp.path());
2326 _guard.remove("TRACEVAULT_SERVER_URL");
2327 _guard.remove("TRACEVAULT_API_KEY");
2328 let uuid = "44444444-4444-4444-8444-444444444444";
2329 _guard.set("TRACEVAULT_PROJECT", uuid);
2330 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2331
2332 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2333 assert_eq!(
2334 report.lines,
2335 vec![
2336 format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2337 "attribution mode: explicit (this caller owns attribution; membership is not checked)".to_string(),
2338 crate::commands::stream::recording_line(Some(
2339 &crate::commands::stream::Attribution::ProjectOnly {
2340 project_id: uuid::Uuid::parse_str(uuid).unwrap(),
2341 }
2342 )),
2343 ],
2344 "the EFFECTIVE mode must reflect TRACEVAULT_PROJECT_ATTRIBUTION even when \
2345 the winning binding has no force of its own, and the lapse line must NOT \
2346 appear (there is no persisted force to lapse)"
2347 );
2348 }
2349}