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(
414 project_flag: Option<ProjectBinding>,
415 env_project: Option<ProjectBinding>,
416 session: &SessionState,
417 worktree: Option<&str>,
418 user_default: Option<ProjectBinding>,
419) -> (Option<(ProjectBinding, ProjectSource)>, Option<String>) {
420 match capture_project_binding(&CaptureProjectInputs {
421 project_flag,
422 env_project,
423 session,
424 worktree_path: worktree,
425 user_default,
426 }) {
427 Some((binding, source)) if capture_project_id(&binding).is_none() => {
428 let warning = invalid_capture_id_warning(&binding, source);
429 (None, Some(warning))
430 }
431 other => (other, None),
432 }
433}
434
435fn enrich_project_name(
448 effective: Option<(ProjectBinding, ProjectSource)>,
449 items: Option<&[ProjectListItem]>,
450) -> Option<(ProjectBinding, ProjectSource)> {
451 effective.map(|(mut binding, source)| {
452 if binding.project_name.is_empty() {
453 if let Some(items) = items {
454 if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
455 if let Some(matched) = items.iter().find(|p| p.id == id) {
456 binding.project_name = matched.name.clone();
457 }
458 }
459 }
460 }
461 (binding, source)
462 })
463}
464
465fn env_name_form_warning(raw: &str) -> String {
474 format!(
475 "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>`"
476 )
477}
478
479fn binding_label(b: &ProjectBinding) -> &str {
481 if b.project_name.is_empty() {
482 &b.project_id
483 } else {
484 &b.project_name
485 }
486}
487
488fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
493 match effective {
494 Some((b, source)) => format!("project: {} via {source}", binding_label(b)),
495 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(),
496 }
497}
498
499fn invalid_capture_id_warning(binding: &ProjectBinding, source: ProjectSource) -> String {
504 format!(
505 "warning: project {} — {source}, but the saved project_id is not a valid id and is dropped at capture time; run `tracevault project switch <name>` to rewrite it",
506 binding_label(binding)
507 )
508}
509
510fn config_default_warning(name: &str) -> String {
515 format!(
516 "warning: .tracevault/config.toml default_project '{name}' is not used for attribution at capture time; bind explicitly with `tracevault project switch <name>`"
517 )
518}
519
520fn offline_project_flag_warning(name: &str) -> String {
523 format!(
524 "warning: --project '{name}' cannot be resolved without server credentials; ignoring the override"
525 )
526}
527
528fn deduced_project_name(pid: uuid::Uuid, items: Option<&[ProjectListItem]>) -> Option<&str> {
532 items?.iter().find(|p| p.id == pid).map(|p| p.name.as_str())
533}
534
535fn format_deduction(
542 effective_is_bound: bool,
543 outcome: Result<ResolveProjectOutcome, String>,
544 resolved_name: Option<&str>,
545) -> String {
546 const PREFIX: &str = "server deduction for this repo:";
547 match outcome {
548 Ok(ResolveProjectOutcome::Resolved(pid)) => {
549 let pid = pid.to_string();
550 let label = resolved_name.unwrap_or(&pid);
551 if effective_is_bound {
552 format!("{PREFIX} {label} (not used: the local binding above wins)")
553 } else {
554 format!("{PREFIX} {label} (events will land here if a repo is bound)")
555 }
556 }
557 Ok(ResolveProjectOutcome::Ambiguous) => {
558 if effective_is_bound {
559 format!(
560 "{PREFIX} ambiguous (multiple projects) — not used, the local binding above wins"
561 )
562 } else {
563 format!(
564 "{PREFIX} ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
565 )
566 }
567 }
568 Ok(ResolveProjectOutcome::None) => format!("{PREFIX} none"),
569 Err(msg) => format!("{PREFIX} unavailable ({msg})"),
570 }
571}
572
573#[derive(Debug, Default)]
577struct StatusReport {
578 warnings: Vec<String>,
579 lines: Vec<String>,
580}
581
582async fn status(
585 session_id: Option<&str>,
586 project_flag_name: Option<&str>,
587 project_root: &Path,
588 cwd: &Path,
589) -> Result<(), Box<dyn std::error::Error>> {
590 let report = status_report(session_id, project_flag_name, project_root, cwd).await;
591 for warning in &report.warnings {
592 eprintln!("{warning}");
593 }
594 for line in &report.lines {
595 println!("{line}");
596 }
597 Ok(())
598}
599
600async fn status_report(
605 session_id: Option<&str>,
606 project_flag_name: Option<&str>,
607 project_root: &Path,
608 cwd: &Path,
609) -> StatusReport {
610 let mut report = StatusReport::default();
611 let session = match crate::commands::repo::resolve_session_id(session_id) {
614 Ok(id) => session_state::load(&id),
615 Err(_) => {
616 report.warnings.push(
617 "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
618 showing binding without session context"
619 .to_string(),
620 );
621 SessionState::default()
622 }
623 };
624 let worktree = crate::paths::worktree_toplevel(cwd);
625 let config_default_name =
626 crate::config::TracevaultConfig::load(project_root).and_then(|c| c.default_project);
627 let user_default = crate::user_project_default::load();
628 let git_url = git_remote_url(cwd);
629
630 let env_project = crate::commands::stream::env_project_binding();
635 let env_raw = std::env::var("TRACEVAULT_PROJECT")
636 .ok()
637 .map(|raw| raw.trim().to_string())
638 .filter(|raw| !raw.is_empty());
639 if env_project.is_none() {
640 if let Some(raw) = env_raw.as_deref() {
641 report.warnings.push(env_name_form_warning(raw));
642 }
643 }
644
645 let client = match resolve_client(project_root) {
649 Ok(client) => Some(client),
650 Err(e) => {
651 report.warnings.push(format!(
652 "warning: could not resolve credentials ({e}); server deduction not shown"
653 ));
654 None
655 }
656 };
657
658 let mut items: Option<Vec<ProjectListItem>> = None;
659 let project_flag = match (project_flag_name, client.as_ref()) {
660 (Some(name), Some(client)) => {
661 items = client.list_projects().await.ok();
662 let flag = items
663 .as_deref()
664 .and_then(|items| resolve_project_name(items, name).ok())
665 .map(|matched| ProjectBinding {
666 project_id: matched.id.to_string(),
667 project_name: matched.name.clone(),
668 updated_at: chrono::Utc::now().to_rfc3339(),
669 forced_until: None,
670 });
671 if flag.is_none() {
672 report.warnings.push(format!(
673 "warning: --project '{name}' could not be resolved; ignoring the override"
674 ));
675 }
676 flag
677 }
678 (Some(name), None) => {
679 report.warnings.push(offline_project_flag_warning(name));
680 None
681 }
682 (None, _) => None,
683 };
684
685 if items.is_none() && env_project.is_some() {
690 if let Some(client) = client.as_ref() {
691 items = client.list_projects().await.ok();
692 }
693 }
694
695 let (effective, invalid_id_warning) = status_effective(
696 project_flag,
697 env_project,
698 &session,
699 Some(&worktree),
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(name) = config_default_name.as_deref() {
706 report.warnings.push(config_default_warning(name));
707 }
708
709 report
710 .lines
711 .push(format_status(effective.as_ref().map(|(b, s)| (b, *s))));
712 if let Some((b, _)) = effective.as_ref() {
716 report.lines.extend(attribution_report(b));
717 }
718
719 if let (Some(client), Some(url)) = (client.as_ref(), git_url.as_deref()) {
720 let outcome = client.resolve_project(url).await.map_err(|e| e.to_string());
723 let name = match &outcome {
724 Ok(ResolveProjectOutcome::Resolved(pid)) => {
725 deduced_project_name(*pid, items.as_deref())
726 }
727 _ => None,
728 };
729 report
730 .lines
731 .push(format_deduction(effective.is_some(), outcome, name));
732 }
733 report
734}
735
736#[cfg(test)]
737mod tests {
738 use super::*;
739 use std::io::{BufRead, BufReader, Write};
740 use std::net::TcpListener;
741 use std::thread;
742
743 #[test]
744 fn resolve_project_name_exact_match_and_miss() {
745 let items = vec![
746 ProjectListItem {
747 id: uuid::Uuid::nil(),
748 name: "payments".into(),
749 },
750 ProjectListItem {
751 id: uuid::Uuid::from_u128(2),
752 name: "web".into(),
753 },
754 ];
755 let ok = resolve_project_name(&items, "web").unwrap();
756 assert_eq!(ok.id, uuid::Uuid::from_u128(2));
757 let err = resolve_project_name(&items, "Web").unwrap_err(); assert!(err.contains("payments") && err.contains("web")); }
760
761 #[test]
762 fn switch_destination_user_flag_forces_user_default() {
763 assert!(matches!(
764 switch_destination(true, Some("sess-1".to_string())),
765 SwitchDest::UserDefault
766 ));
767 assert!(matches!(
768 switch_destination(true, None),
769 SwitchDest::UserDefault
770 ));
771 }
772
773 #[test]
774 fn switch_destination_session_when_present_and_no_user_flag() {
775 assert!(matches!(
776 switch_destination(false, Some("sess-1".to_string())),
777 SwitchDest::Session(id) if id == "sess-1"
778 ));
779 }
780
781 #[test]
782 fn switch_destination_user_default_when_no_session() {
783 assert!(matches!(
784 switch_destination(false, None),
785 SwitchDest::UserDefault
786 ));
787 }
788
789 #[test]
790 fn switching_with_explicit_stamps_a_lapse_time() {
791 let before = chrono::Utc::now();
792 let binding = apply_force(
793 ProjectBinding {
794 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
795 project_name: "p".into(),
796 updated_at: before.to_rfc3339(),
797 forced_until: None,
798 },
799 true,
800 );
801 let until = chrono::DateTime::parse_from_rfc3339(
802 binding.forced_until.as_deref().expect("force is stamped"),
803 )
804 .unwrap();
805 let expected = before
806 + chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS);
807 assert!((until.timestamp() - expected.timestamp()).abs() < 5);
808 }
809
810 #[test]
811 fn switching_without_explicit_stamps_no_lapse_time() {
812 let binding = apply_force(
813 ProjectBinding {
814 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
815 project_name: "p".into(),
816 updated_at: chrono::Utc::now().to_rfc3339(),
817 forced_until: Some("2020-01-01T00:00:00Z".into()),
818 },
819 false,
820 );
821 assert_eq!(
822 binding.forced_until, None,
823 "switching without --project-attribution explicit must CLEAR a stale force"
824 );
825 }
826
827 #[test]
831 fn format_force_line_distinguishes_a_live_force_from_a_lapsed_one() {
832 let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
833 let live = format_force_line(&future);
834 assert!(live.contains("active until"), "got: {live}");
835 assert!(live.contains(&future), "got: {live}");
836
837 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
838 let lapsed = format_force_line(&past);
839 assert!(lapsed.contains("lapsed"), "got: {lapsed}");
840 assert!(lapsed.contains(&past), "got: {lapsed}");
841
842 for line in [&live, &lapsed] {
846 assert!(!line.contains("derived"), "got: {line}");
847 assert!(!line.contains("explicit"), "got: {line}");
848 assert!(!line.contains("membership"), "got: {line}");
849 }
850 }
851
852 #[test]
856 fn status_names_a_lapsed_force_as_lapsed_not_active() {
857 let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
858 let line = format_force_line(&past);
859 assert!(line.contains("lapsed"), "got: {line}");
860 assert!(!line.contains("active until"), "got: {line}");
861 }
862
863 #[test]
874 fn status_names_unparseable_forced_until_as_not_in_force() {
875 let line = format_force_line("not-a-timestamp");
876 assert!(line.contains("not in force"), "got: {line}");
877 assert!(!line.contains("active until"), "got: {line}");
878
879 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
880 let mut _guard = crate::test_helpers::EnvVarGuard::new();
881 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
882 let b = ProjectBinding {
883 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
884 project_name: "payments".into(),
885 updated_at: "".into(),
886 forced_until: Some("not-a-timestamp".into()),
887 };
888 assert_eq!(
889 crate::commands::stream::attribution_mode(Some(&b)),
890 crate::api_client::AttributionMode::Derived,
891 "the reported state and the header must agree on an unreadable force"
892 );
893 }
894
895 #[test]
905 fn attribution_report_omits_the_lapse_line_when_there_is_no_persisted_force() {
906 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
907 let mut _guard = crate::test_helpers::EnvVarGuard::new();
908 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
909
910 let b = ProjectBinding {
911 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
912 project_name: "payments".into(),
913 updated_at: "".into(),
914 forced_until: None,
915 };
916 let lines = attribution_report(&b);
917 assert_eq!(
918 lines.len(),
919 1,
920 "an env-only force has no lapse to report, and must not be \
921 contradicted by a `derived` line: {lines:?}"
922 );
923 assert!(
924 lines[0].starts_with("attribution mode: explicit"),
925 "got: {lines:?}"
926 );
927 assert!(
928 !lines.iter().any(|l| l.contains("derived")),
929 "got: {lines:?}"
930 );
931 }
932
933 #[test]
937 fn attribution_report_keeps_the_lapse_line_for_a_persisted_force() {
938 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
939 let mut _guard = crate::test_helpers::EnvVarGuard::new();
940 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
941
942 let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
943 let b = ProjectBinding {
944 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
945 project_name: "payments".into(),
946 updated_at: "".into(),
947 forced_until: Some(until.clone()),
948 };
949 let lines = attribution_report(&b);
950 assert_eq!(lines.len(), 2, "got: {lines:?}");
951 assert!(
952 lines[0].starts_with("attribution mode: explicit"),
953 "got: {}",
954 lines[0]
955 );
956 assert!(lines[1].contains("active until"), "got: {}", lines[1]);
957 assert!(lines[1].contains(&until), "got: {}", lines[1]);
958 }
959
960 #[test]
966 fn attribution_report_reports_a_lapsed_persisted_force_as_derived() {
967 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
968 let mut _guard = crate::test_helpers::EnvVarGuard::new();
969 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
970
971 let b = ProjectBinding {
972 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
973 project_name: "payments".into(),
974 updated_at: "".into(),
975 forced_until: Some((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()),
976 };
977 let lines = attribution_report(&b);
978 assert_eq!(lines.len(), 2, "got: {lines:?}");
979 assert!(
980 lines[0].starts_with("attribution mode: derived"),
981 "got: {}",
982 lines[0]
983 );
984 assert!(
985 lines[1].starts_with("persisted force: lapsed"),
986 "got: {}",
987 lines[1]
988 );
989 }
990
991 #[test]
1008 fn a_lapsed_persisted_force_never_contradicts_an_env_force() {
1009 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1010 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1011 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1012
1013 let lapsed = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
1014 for forced_until in [lapsed.as_str(), "not-a-timestamp"] {
1015 let b = ProjectBinding {
1016 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1017 project_name: "payments".into(),
1018 updated_at: "".into(),
1019 forced_until: Some(forced_until.to_string()),
1020 };
1021 let lines = attribution_report(&b);
1022 assert_eq!(lines.len(), 2, "{forced_until}: got {lines:?}");
1023 assert!(
1024 lines[0].starts_with("attribution mode: explicit"),
1025 "{forced_until}: the env force decides the mode: {lines:?}"
1026 );
1027 assert!(
1031 !lines[1].contains("derived"),
1032 "{forced_until}: the detail line must not render a competing \
1033 verdict while the env force makes this send explicit: {lines:?}"
1034 );
1035 assert!(
1036 !lines[1].contains("membership is checked"),
1037 "{forced_until}: membership is NOT being checked here: {lines:?}"
1038 );
1039 }
1040 }
1041
1042 #[test]
1050 fn switch_report_names_the_env_force_and_never_claims_derived() {
1051 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1052 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1053 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
1054
1055 let b = ProjectBinding {
1056 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1057 project_name: "payments".into(),
1058 updated_at: "".into(),
1059 forced_until: None,
1060 };
1061
1062 for dest in [
1063 SwitchDest::Session("sess-1".to_string()),
1064 SwitchDest::UserDefault,
1065 ] {
1066 let lines = switch_report(&dest, &b, None);
1067 assert!(
1068 lines[0].contains("payments"),
1069 "the first line still says what was bound: {lines:?}"
1070 );
1071 assert!(
1072 lines
1073 .iter()
1074 .any(|l| l.starts_with("attribution mode: explicit")),
1075 "a `switch` in an explicit shell must say so: {lines:?}"
1076 );
1077 assert!(
1078 !lines.iter().any(|l| l.contains("derived")),
1079 "{dest:?}: `switch` must not claim membership is checked while \
1080 every hook in this shell sends `explicit`: {lines:?}"
1081 );
1082 }
1083 }
1084
1085 #[test]
1089 fn switch_report_names_the_lapse_it_just_stamped() {
1090 let _env_lock = crate::test_helpers::lock_env_mutation_sync();
1091 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1092 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
1093
1094 let b = apply_force(
1095 ProjectBinding {
1096 project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
1097 project_name: "payments".into(),
1098 updated_at: "".into(),
1099 forced_until: None,
1100 },
1101 true,
1102 );
1103 let lines = switch_report(&SwitchDest::Session("sess-1".to_string()), &b, None);
1104 assert_eq!(lines.len(), 3, "got: {lines:?}");
1105 assert!(
1106 lines[1].starts_with("attribution mode: explicit"),
1107 "got: {}",
1108 lines[1]
1109 );
1110 assert!(
1111 lines[2].starts_with("persisted force: active until"),
1112 "got: {}",
1113 lines[2]
1114 );
1115 }
1116
1117 fn pb(name: &str) -> ProjectBinding {
1118 ProjectBinding {
1119 project_id: format!("id-{name}"),
1120 project_name: name.into(),
1121 updated_at: "t".into(),
1122 forced_until: None,
1123 }
1124 }
1125
1126 #[test]
1127 fn format_status_unbound() {
1128 assert_eq!(
1129 format_status(None),
1130 "no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo"
1131 );
1132 }
1133
1134 #[test]
1135 fn format_status_project_flag() {
1136 let b = pb("web");
1137 assert_eq!(
1138 format_status(Some((&b, ProjectSource::ProjectFlag))),
1139 "project: web via --project override"
1140 );
1141 }
1142
1143 #[test]
1144 fn format_status_session_active() {
1145 let b = pb("payments");
1146 assert_eq!(
1147 format_status(Some((&b, ProjectSource::SessionActive))),
1148 "project: payments via session (project switch)"
1149 );
1150 }
1151
1152 #[test]
1153 fn format_status_falls_back_to_id_when_name_empty() {
1154 let b = ProjectBinding {
1157 project_id: "some-id".into(),
1158 project_name: String::new(),
1159 updated_at: "".into(),
1160 forced_until: None,
1161 };
1162 assert_eq!(
1163 format_status(Some((&b, ProjectSource::UserDefault))),
1164 "project: some-id via user default (project switch --user)"
1165 );
1166 }
1167
1168 #[test]
1169 fn format_status_env() {
1170 let b = pb("payments");
1171 assert_eq!(
1172 format_status(Some((&b, ProjectSource::Env))),
1173 "project: payments via TRACEVAULT_PROJECT (environment)"
1174 );
1175 }
1176
1177 #[test]
1178 fn invalid_capture_id_warning_names_tier_and_rewrite_command() {
1179 let b = ProjectBinding {
1180 project_id: "not-a-uuid".into(),
1181 project_name: "payments".into(),
1182 updated_at: "".into(),
1183 forced_until: None,
1184 };
1185 assert_eq!(
1186 invalid_capture_id_warning(&b, ProjectSource::UserDefault),
1187 "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 <name>` to rewrite it"
1188 );
1189 }
1190
1191 #[test]
1194 fn status_effective_drops_a_non_uuid_binding_with_a_warning_naming_the_tier() {
1195 let session = SessionState {
1196 active_project: Some(ProjectBinding {
1197 project_id: "not-a-uuid".into(),
1198 project_name: "payments".into(),
1199 updated_at: "".into(),
1200 forced_until: None,
1201 }),
1202 ..Default::default()
1203 };
1204 let (effective, warning) = status_effective(None, None, &session, None, None);
1205 assert!(effective.is_none(), "{effective:?}");
1206 let warning = warning.expect("a dropped binding must be explained");
1207 assert!(
1208 warning.contains("session (project switch)"),
1209 "must name the tier: {warning}"
1210 );
1211 assert!(warning.contains("payments"), "{warning}");
1212
1213 let pid = uuid::Uuid::from_u128(5);
1215 let valid = SessionState {
1216 active_project: Some(ProjectBinding {
1217 project_id: pid.to_string(),
1218 project_name: "web".into(),
1219 updated_at: "".into(),
1220 forced_until: None,
1221 }),
1222 ..Default::default()
1223 };
1224 let (effective, warning) = status_effective(None, None, &valid, None, None);
1225 assert_eq!(
1226 effective.map(|(b, s)| (b.project_id, s)),
1227 Some((pid.to_string(), ProjectSource::SessionActive))
1228 );
1229 assert_eq!(warning, None);
1230 }
1231
1232 #[test]
1237 fn status_effective_places_env_at_rung_three() {
1238 let u = uuid::Uuid::from_u128;
1239 let bind = |id: uuid::Uuid, name: &str| ProjectBinding {
1240 project_id: id.to_string(),
1241 project_name: name.into(),
1242 updated_at: "".into(),
1243 forced_until: None,
1244 };
1245 let session = SessionState {
1246 active_project: Some(bind(u(2), "session")),
1247 ..Default::default()
1248 };
1249
1250 let (effective, _) = status_effective(
1252 None,
1253 Some(bind(u(9), "env")),
1254 &session,
1255 None,
1256 Some(bind(u(3), "user")),
1257 );
1258 assert_eq!(
1259 effective.map(|(b, s)| (b.project_id, s)),
1260 Some((u(9).to_string(), ProjectSource::Env))
1261 );
1262
1263 let (effective, _) = status_effective(
1265 Some(bind(u(1), "flag")),
1266 Some(bind(u(9), "env")),
1267 &session,
1268 None,
1269 Some(bind(u(3), "user")),
1270 );
1271 assert_eq!(
1272 effective.map(|(b, s)| (b.project_id, s)),
1273 Some((u(1).to_string(), ProjectSource::ProjectFlag))
1274 );
1275 }
1276
1277 #[test]
1278 fn offline_project_flag_warning_says_the_override_is_ignored() {
1279 assert_eq!(
1280 offline_project_flag_warning("web"),
1281 "warning: --project 'web' cannot be resolved without server credentials; ignoring the override"
1282 );
1283 }
1284
1285 #[test]
1289 fn env_name_form_warning_says_only_the_uuid_form_is_used() {
1290 let warning = env_name_form_warning("payments");
1291 assert!(warning.contains("payments"), "{warning}");
1292 assert!(warning.contains("UUID form"), "{warning}");
1293 assert!(
1294 warning.contains("not used") || warning.contains("ignored"),
1295 "{warning}"
1296 );
1297 }
1298
1299 #[test]
1300 fn config_default_warning_says_it_is_not_used_at_capture_time() {
1301 assert_eq!(
1302 config_default_warning("web"),
1303 "warning: .tracevault/config.toml default_project 'web' is not used for attribution at capture time; bind explicitly with `tracevault project switch <name>`"
1304 );
1305 }
1306
1307 const DEDUCED: uuid::Uuid = uuid::Uuid::from_u128(2);
1308
1309 #[test]
1310 fn format_deduction_resolved_bound() {
1311 assert_eq!(
1312 format_deduction(true, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1313 format!(
1314 "server deduction for this repo: {DEDUCED} (not used: the local binding above wins)"
1315 )
1316 );
1317 }
1318
1319 #[test]
1320 fn format_deduction_resolved_unbound() {
1321 assert_eq!(
1322 format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
1323 format!("server deduction for this repo: {DEDUCED} (events will land here if a repo is bound)")
1324 );
1325 }
1326
1327 #[test]
1328 fn format_deduction_resolved_uses_name_when_known() {
1329 let items = items();
1330 let name = deduced_project_name(DEDUCED, Some(&items));
1331 assert_eq!(name, Some("web"));
1332 assert_eq!(
1333 format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), name),
1334 "server deduction for this repo: web (events will land here if a repo is bound)"
1335 );
1336 }
1337
1338 #[test]
1339 fn deduced_project_name_none_without_list_or_match() {
1340 assert_eq!(deduced_project_name(DEDUCED, None), None);
1341 assert_eq!(
1342 deduced_project_name(uuid::Uuid::from_u128(999), Some(&items())),
1343 None
1344 );
1345 }
1346
1347 #[test]
1348 fn format_deduction_ambiguous_bound() {
1349 assert_eq!(
1350 format_deduction(true, Ok(ResolveProjectOutcome::Ambiguous), None),
1351 "server deduction for this repo: ambiguous (multiple projects) — not used, the local binding above wins"
1352 );
1353 }
1354
1355 #[test]
1356 fn format_deduction_ambiguous_unbound() {
1357 assert_eq!(
1358 format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
1359 "server deduction for this repo: ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
1360 );
1361 }
1362
1363 #[test]
1364 fn format_deduction_none() {
1365 for bound in [true, false] {
1366 assert_eq!(
1367 format_deduction(bound, Ok(ResolveProjectOutcome::None), None),
1368 "server deduction for this repo: none"
1369 );
1370 }
1371 }
1372
1373 #[test]
1374 fn format_deduction_err() {
1375 for bound in [true, false] {
1376 assert_eq!(
1377 format_deduction(bound, Err("connection refused".into()), None),
1378 "server deduction for this repo: unavailable (connection refused)"
1379 );
1380 }
1381 }
1382
1383 #[test]
1384 fn format_status_user_default() {
1385 let b = pb("payments");
1386 assert_eq!(
1387 format_status(Some((&b, ProjectSource::UserDefault))),
1388 "project: payments via user default (project switch --user)"
1389 );
1390 }
1391
1392 fn spawn_once(response: String) -> String {
1395 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1396 let addr = listener.local_addr().unwrap();
1397 let response: &'static str = Box::leak(response.into_boxed_str());
1398 thread::spawn(move || {
1399 if let Ok((stream, _)) = listener.accept() {
1400 let mut reader = BufReader::new(stream);
1401 let mut request_line = String::new();
1402 let _ = reader.read_line(&mut request_line);
1403 let mut stream = reader.into_inner();
1404 let _ = stream.write_all(response.as_bytes());
1405 let _ = stream.flush();
1406 }
1407 });
1408 format!("http://{addr}")
1409 }
1410
1411 fn spawn_n(responses: Vec<String>) -> String {
1415 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1416 let addr = listener.local_addr().unwrap();
1417 thread::spawn(move || {
1418 for response in responses {
1419 let response: &'static str = Box::leak(response.into_boxed_str());
1420 if let Ok((stream, _)) = listener.accept() {
1421 let mut reader = BufReader::new(stream);
1422 let mut request_line = String::new();
1423 let _ = reader.read_line(&mut request_line);
1424 let mut stream = reader.into_inner();
1425 let _ = stream.write_all(response.as_bytes());
1426 let _ = stream.flush();
1427 }
1428 }
1429 });
1430 format!("http://{addr}")
1431 }
1432
1433 fn http_200(body: &str) -> String {
1434 format!(
1435 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1436 body.len(),
1437 body
1438 )
1439 }
1440
1441 #[tokio::test]
1448 async fn project_switch_happy_path_writes_active_project_to_session_file() {
1449 let tmp = tempfile::tempdir().unwrap();
1450 crate::test_helpers::init_git_repo(tmp.path()); let _env_lock = crate::test_helpers::lock_env_mutation().await;
1461 let state_tmp = tempfile::tempdir().unwrap();
1462 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1463 _guard.set("XDG_STATE_HOME", state_tmp.path());
1464
1465 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
1466 let base = spawn_once(http_200(list));
1467 let client = ApiClient::new(&base, Some("tok"));
1468
1469 let (binding, note) =
1470 resolve_switch_project("web", &client, CodebaseCheck::Enforce, tmp.path())
1471 .await
1472 .expect("expected Ok binding");
1473 assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
1474 assert_eq!(binding.project_name, "web");
1475 assert_eq!(note, None, "no remote to check against, so nothing to note");
1476
1477 let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
1478 let mut state = session_state::load(&session_id);
1479 state.active_project = Some(binding.clone());
1480 session_state::save(&session_id, &state).expect("save must succeed");
1481
1482 let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
1483 assert!(sessions_dir.starts_with(state_tmp.path()));
1484 let loaded = session_state::load_from(&sessions_dir, &session_id);
1485 assert_eq!(loaded.active_project, Some(binding));
1486 }
1487
1488 #[tokio::test]
1489 async fn project_switch_errors_when_name_not_found() {
1490 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
1491 let base = spawn_once(http_200(list));
1492 let client = ApiClient::new(&base, Some("tok"));
1493
1494 let err = resolve_switch_project(
1495 "web",
1496 &client,
1497 CodebaseCheck::Skip,
1498 Path::new("/nonexistent"),
1499 )
1500 .await
1501 .expect_err("expected Err for an unknown project name");
1502 let msg = err.to_string();
1503 assert!(msg.contains("not found"), "got: {msg}");
1504 assert!(msg.contains("payments"), "got: {msg}");
1505 }
1506
1507 #[tokio::test]
1508 async fn project_switch_errors_when_project_does_not_contain_codebase() {
1509 let tmp = tempfile::tempdir().unwrap();
1510 crate::test_helpers::init_git_repo(tmp.path());
1511 let ok = std::process::Command::new("git")
1512 .args([
1513 "-C",
1514 &tmp.path().to_string_lossy(),
1515 "remote",
1516 "add",
1517 "origin",
1518 "git@github.com:org/repo.git",
1519 ])
1520 .status()
1521 .expect("git remote add failed")
1522 .success();
1523 assert!(ok, "git remote add must succeed");
1524
1525 let list =
1526 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1527 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1528 let remote = format!(
1529 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1530 );
1531 let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1532 let detail = format!(
1533 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"}}]}}"#
1534 );
1535 let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1536 let base = spawn_n(vec![
1537 http_200(&list),
1538 http_200(&remote),
1539 http_200(&detail),
1540 http_200(project_detail),
1541 ]);
1542 let client = ApiClient::new(&base, Some("tok"));
1543
1544 let err = resolve_switch_project("payments", &client, CodebaseCheck::Enforce, tmp.path())
1545 .await
1546 .expect_err("expected Err: project doesn't contain the current codebase");
1547 assert!(
1548 err.to_string()
1549 .contains("does not contain the current codebase"),
1550 "got: {err}"
1551 );
1552 }
1553
1554 #[tokio::test]
1569 async fn explicit_attribution_binds_a_non_member_project_and_says_so() {
1570 let tmp = tempfile::tempdir().unwrap();
1571 crate::test_helpers::init_git_repo(tmp.path());
1572 let ok = std::process::Command::new("git")
1573 .args([
1574 "-C",
1575 &tmp.path().to_string_lossy(),
1576 "remote",
1577 "add",
1578 "origin",
1579 "git@github.com:org/repo.git",
1580 ])
1581 .status()
1582 .expect("git remote add failed")
1583 .success();
1584 assert!(ok, "git remote add must succeed");
1585
1586 let list =
1587 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1588 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1589 let remote = format!(
1590 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1591 );
1592 let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
1593 let detail = format!(
1594 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"}}]}}"#
1595 );
1596 let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
1597 let base = spawn_n(vec![
1598 http_200(&list),
1599 http_200(&remote),
1600 http_200(&detail),
1601 http_200(project_detail),
1602 ]);
1603 let client = ApiClient::new(&base, Some("tok"));
1604
1605 let (binding, note) =
1606 resolve_switch_project("payments", &client, CodebaseCheck::Report, tmp.path())
1607 .await
1608 .expect("a forced switch must not be blocked by the containment check");
1609 assert_eq!(binding.project_id, "11111111-1111-4111-8111-111111111111");
1610
1611 let note = note.expect("the user must still be told the project is not a member");
1612 assert!(
1613 note.contains("does not contain the current codebase"),
1614 "the fact must be stated: {note}"
1615 );
1616 assert!(
1617 note.contains("--project-attribution explicit"),
1618 "must say what made it deliberate: {note}"
1619 );
1620 assert!(
1621 note.contains("Operator") && note.contains("ingest"),
1622 "must say where the requirement is actually enforced: {note}"
1623 );
1624
1625 assert!(
1627 !note.starts_with("error"),
1628 "this is informational, not a failure: {note}"
1629 );
1630 }
1631
1632 #[test]
1639 fn only_an_explicit_session_switch_downgrades_the_containment_check() {
1640 let session = SwitchDest::Session("s".into());
1641 assert_eq!(
1642 codebase_check_for(&session, true),
1643 CodebaseCheck::Report,
1644 "--project-attribution explicit must not be blocked"
1645 );
1646 assert_eq!(
1647 codebase_check_for(&session, false),
1648 CodebaseCheck::Enforce,
1649 "an ordinary session switch keeps erroring"
1650 );
1651 assert_eq!(
1653 codebase_check_for(&SwitchDest::UserDefault, true),
1654 CodebaseCheck::Skip
1655 );
1656 assert_eq!(
1657 codebase_check_for(&SwitchDest::UserDefault, false),
1658 CodebaseCheck::Skip
1659 );
1660 }
1661
1662 #[tokio::test]
1696 async fn switch_without_session_or_user_flag_skips_codebase_check() {
1697 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1698 let tmp = tempfile::tempdir().unwrap();
1699 crate::test_helpers::init_git_repo(tmp.path());
1700 let ok = std::process::Command::new("git")
1701 .args([
1702 "-C",
1703 &tmp.path().to_string_lossy(),
1704 "remote",
1705 "add",
1706 "origin",
1707 "git@github.com:org/repo.git",
1708 ])
1709 .status()
1710 .expect("git remote add failed")
1711 .success();
1712 assert!(ok, "git remote add must succeed");
1713
1714 let list =
1715 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
1716 let base = spawn_once(http_200(&list));
1717
1718 let config_dir = tmp.path().join(".tracevault");
1719 std::fs::create_dir_all(&config_dir).unwrap();
1720 std::fs::write(
1721 config_dir.join("config.toml"),
1722 format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\n"),
1723 )
1724 .unwrap();
1725
1726 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1741 _guard.remove("TRACEVAULT_SESSION_ID");
1742 _guard.set("XDG_CONFIG_HOME", tmp.path());
1743 _guard.set("TRACEVAULT_SERVER_URL", &base);
1744 _guard.set("TRACEVAULT_API_KEY", "tok");
1745
1746 let result = switch("payments", false, None, "derived", tmp.path(), tmp.path()).await;
1747 assert!(
1748 result.is_ok(),
1749 "expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
1750 );
1751
1752 let saved = crate::user_project_default::load();
1753 assert_eq!(
1754 saved.map(|b| b.project_name),
1755 Some("payments".to_string()),
1756 "no-session switch must fall back to the user-level default binding"
1757 );
1758 }
1759
1760 fn items() -> Vec<ProjectListItem> {
1761 vec![
1762 ProjectListItem {
1763 id: uuid::Uuid::from_u128(1),
1764 name: "payments".into(),
1765 },
1766 ProjectListItem {
1767 id: uuid::Uuid::from_u128(2),
1768 name: "web".into(),
1769 },
1770 ]
1771 }
1772
1773 fn nameless(id: uuid::Uuid, source: ProjectSource) -> (ProjectBinding, ProjectSource) {
1779 (
1780 ProjectBinding {
1781 project_id: id.to_string(),
1782 project_name: String::new(),
1783 updated_at: "".into(),
1784 forced_until: None,
1785 },
1786 source,
1787 )
1788 }
1789
1790 #[test]
1794 fn enrich_project_name_fills_in_name_when_id_found_in_list() {
1795 let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1796 let (b, source) = enrich_project_name(effective, Some(&items())).unwrap();
1797 assert_eq!(b.project_name, "web");
1798 assert_eq!(source, ProjectSource::Env);
1799 }
1800
1801 #[test]
1802 fn enrich_project_name_leaves_empty_when_no_list_available() {
1803 let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
1804 let (b, _source) = enrich_project_name(effective, None).unwrap();
1805 assert_eq!(b.project_name, "");
1806 }
1807
1808 #[test]
1809 fn enrich_project_name_leaves_empty_when_id_not_in_list() {
1810 let effective = Some(nameless(uuid::Uuid::from_u128(999), ProjectSource::Env));
1811 let (b, _source) = enrich_project_name(effective, Some(&items())).unwrap();
1812 assert_eq!(b.project_name, "");
1813 }
1814
1815 #[test]
1816 fn enrich_project_name_leaves_a_populated_name_untouched() {
1817 let b = pb("payments");
1821 let effective = Some((b.clone(), ProjectSource::SessionActive));
1822 let (out, source) = enrich_project_name(effective, Some(&items())).unwrap();
1823 assert_eq!(out, b);
1824 assert_eq!(source, ProjectSource::SessionActive);
1825 }
1826
1827 #[test]
1828 fn enrich_project_name_passes_through_none() {
1829 assert!(enrich_project_name(None, Some(&items())).is_none());
1830 }
1831
1832 #[tokio::test]
1842 async fn project_status_effective_project_matches_capture_project() {
1843 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1844 let tmp = tempfile::tempdir().unwrap();
1845 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1846 _guard.set("XDG_CONFIG_HOME", tmp.path());
1847 _guard.set("HOME", tmp.path());
1848
1849 let u = uuid::Uuid::from_u128;
1850 let bind = |id: String| ProjectBinding {
1851 project_id: id,
1852 project_name: "n".into(),
1853 updated_at: "".into(),
1854 forced_until: None,
1855 };
1856 let worktree = "/wt";
1857 let subagent_session = {
1858 let mut s = SessionState {
1859 active_project: Some(bind(u(2).to_string())),
1860 ..Default::default()
1861 };
1862 s.subagent_projects
1863 .insert(worktree.into(), bind(u(1).to_string()));
1864 s
1865 };
1866 let active_session = SessionState {
1867 active_project: Some(bind(u(2).to_string())),
1868 ..Default::default()
1869 };
1870 let bad_active_session = SessionState {
1871 active_project: Some(bind("not-a-uuid".into())),
1872 ..Default::default()
1873 };
1874
1875 type Case = (
1878 &'static str,
1879 SessionState,
1880 Option<String>,
1881 Option<String>,
1882 Option<uuid::Uuid>,
1883 );
1884 let cases: Vec<Case> = vec![
1885 (
1886 "(a) subagent override + session active + user default",
1887 subagent_session,
1888 Some(u(3).to_string()),
1889 None,
1890 Some(u(1)),
1891 ),
1892 (
1893 "(b) session active + user default",
1894 active_session.clone(),
1895 Some(u(3).to_string()),
1896 None,
1897 Some(u(2)),
1898 ),
1899 (
1900 "(c) user default only",
1901 SessionState::default(),
1902 Some(u(3).to_string()),
1903 None,
1904 Some(u(3)),
1905 ),
1906 ("(d) nothing", SessionState::default(), None, None, None),
1907 (
1908 "(e) user default with a non-UUID project_id",
1909 SessionState::default(),
1910 Some("not-a-uuid".into()),
1911 None,
1912 None,
1913 ),
1914 (
1915 "(f) non-UUID session active shadows a valid user default",
1916 bad_active_session,
1917 Some(u(3).to_string()),
1918 None,
1919 None,
1920 ),
1921 (
1924 "(g) TRACEVAULT_PROJECT (UUID) outranks session active and the user default",
1925 active_session.clone(),
1926 Some(u(3).to_string()),
1927 Some(u(4).to_string()),
1928 Some(u(4)),
1929 ),
1930 (
1933 "(h) TRACEVAULT_PROJECT (NAME) is ignored by both",
1934 active_session,
1935 Some(u(3).to_string()),
1936 Some("payments".into()),
1937 Some(u(2)),
1938 ),
1939 ];
1940
1941 for (label, session, user_default, env_project, expected) in cases {
1942 match &user_default {
1943 Some(id) => crate::user_project_default::save(&bind(id.clone())).unwrap(),
1944 None => crate::user_project_default::clear().unwrap(),
1945 }
1946 match &env_project {
1947 Some(v) => _guard.set("TRACEVAULT_PROJECT", v),
1948 None => _guard.remove("TRACEVAULT_PROJECT"),
1949 }
1950 let status_pid = status_effective(
1951 None,
1952 crate::commands::stream::env_project_binding(),
1953 &session,
1954 Some(worktree),
1955 crate::user_project_default::load(),
1956 )
1957 .0
1958 .and_then(|(b, _)| capture_project_id(&b));
1959 let ingest_pid = crate::commands::stream::capture_project(&session, Some(worktree));
1960 assert_eq!(
1961 status_pid, ingest_pid,
1962 "{label}: status and ingest disagree"
1963 );
1964 assert_eq!(status_pid, expected, "{label}");
1965 }
1966 crate::user_project_default::clear().unwrap();
1967 }
1968
1969 #[tokio::test]
1972 async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
1973 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1974 let tmp = tempfile::tempdir().unwrap();
1975 crate::test_helpers::init_git_repo(tmp.path());
1976 let ok = std::process::Command::new("git")
1977 .args([
1978 "-C",
1979 &tmp.path().to_string_lossy(),
1980 "remote",
1981 "add",
1982 "origin",
1983 "git@github.com:org/repo.git",
1984 ])
1985 .status()
1986 .expect("git remote add failed")
1987 .success();
1988 assert!(ok, "git remote add must succeed");
1989
1990 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\"}";
1992 let base = spawn_n(vec![conflict.to_string(), conflict.to_string()]);
1993
1994 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1998 _guard.set("TRACEVAULT_SERVER_URL", &base);
1999 _guard.set("TRACEVAULT_API_KEY", "tok");
2000 _guard.set("XDG_CONFIG_HOME", tmp.path());
2001 _guard.set("HOME", tmp.path());
2002 _guard.remove("TRACEVAULT_SESSION_ID");
2003 _guard.remove("TRACEVAULT_PROJECT");
2009 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2010
2011 let result = status(None, None, tmp.path(), tmp.path()).await;
2012 assert!(
2013 result.is_ok(),
2014 "status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
2015 );
2016
2017 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2018 assert_eq!(
2019 report.lines,
2020 vec![
2021 format_status(None),
2022 format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
2023 ],
2024 "the ambiguous deduction is reported on its own line"
2025 );
2026 }
2027
2028 #[tokio::test]
2034 async fn status_in_the_orchestrator_configuration_names_the_user_default() {
2035 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2036 let tmp = tempfile::tempdir().unwrap();
2037 let repo = tmp.path().join("repo");
2038 std::fs::create_dir_all(&repo).unwrap();
2039 crate::test_helpers::init_git_repo(&repo);
2040 let ok = std::process::Command::new("git")
2041 .args([
2042 "-C",
2043 &repo.to_string_lossy(),
2044 "remote",
2045 "add",
2046 "origin",
2047 "git@github.com:org/repo.git",
2048 ])
2049 .status()
2050 .expect("git remote add failed")
2051 .success();
2052 assert!(ok, "git remote add must succeed");
2053
2054 let deduced_a = uuid::Uuid::from_u128(0xA);
2055 let base = spawn_once(http_200(&format!(r#"{{"project_id":"{deduced_a}"}}"#)));
2056
2057 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2058 _guard.set("TRACEVAULT_SERVER_URL", &base);
2059 _guard.set("TRACEVAULT_API_KEY", "tok");
2060 _guard.set("XDG_CONFIG_HOME", tmp.path());
2061 _guard.set("HOME", tmp.path());
2062 _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2063 _guard.remove("TRACEVAULT_SESSION_ID");
2064 _guard.remove("TRACEVAULT_PROJECT");
2068 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2069
2070 let default_b = ProjectBinding {
2071 project_id: uuid::Uuid::from_u128(0xB).to_string(),
2072 project_name: "project-b".into(),
2073 updated_at: "".into(),
2074 forced_until: None,
2075 };
2076 crate::user_project_default::save(&default_b).unwrap();
2077
2078 let report = status_report(None, None, &repo, &repo).await;
2079
2080 assert_eq!(
2081 report.lines,
2082 vec![
2083 "project: project-b via user default (project switch --user)".to_string(),
2084 "attribution mode: derived (TraceVault checks repo/project membership)"
2085 .to_string(),
2086 format!(
2087 "server deduction for this repo: {deduced_a} (not used: the local binding above wins)"
2088 ),
2089 ]
2090 );
2091 }
2092
2093 #[tokio::test]
2101 async fn status_reports_env_uuid_as_the_effective_tier_with_its_name() {
2102 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2103 let tmp = tempfile::tempdir().unwrap();
2104
2105 let uuid = "11111111-1111-4111-8111-111111111111";
2106 let list = format!(r#"[{{"id":"{uuid}","name":"payments"}}]"#);
2107 let base = spawn_once(http_200(&list));
2108
2109 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2110 _guard.set("XDG_CONFIG_HOME", tmp.path());
2111 _guard.set("HOME", tmp.path());
2112 _guard.set("TRACEVAULT_SERVER_URL", &base);
2113 _guard.set("TRACEVAULT_API_KEY", "tok");
2114 _guard.set("TRACEVAULT_PROJECT", uuid);
2115 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2116 _guard.remove("TRACEVAULT_SESSION_ID");
2117
2118 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2119 assert_eq!(
2120 report.lines[0], "project: payments via TRACEVAULT_PROJECT (environment)",
2121 "got: {:?}",
2122 report.lines
2123 );
2124 assert!(
2125 report
2126 .warnings
2127 .iter()
2128 .all(|w| !w.contains("TRACEVAULT_PROJECT")),
2129 "the UUID form is honoured at capture time and needs no caveat: {:?}",
2130 report.warnings
2131 );
2132 }
2133
2134 #[tokio::test]
2142 async fn status_warns_that_an_env_name_is_not_used_and_falls_through() {
2143 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2144 let tmp = tempfile::tempdir().unwrap();
2145
2146 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2147 _guard.set("XDG_CONFIG_HOME", tmp.path());
2148 _guard.set("HOME", tmp.path());
2149 _guard.set("XDG_STATE_HOME", tmp.path().join("state"));
2150 _guard.remove("TRACEVAULT_SERVER_URL");
2151 _guard.remove("TRACEVAULT_API_KEY");
2152 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2153 _guard.set("TRACEVAULT_PROJECT", "payments");
2154
2155 let session_id = "vis305-env-name-form";
2156 let pid = uuid::Uuid::from_u128(0x5E);
2157 crate::session_state::save(
2158 session_id,
2159 &SessionState {
2160 active_project: Some(ProjectBinding {
2161 project_id: pid.to_string(),
2162 project_name: "session-project".into(),
2163 updated_at: "".into(),
2164 forced_until: None,
2165 }),
2166 ..Default::default()
2167 },
2168 )
2169 .unwrap();
2170
2171 let report = status_report(Some(session_id), None, tmp.path(), tmp.path()).await;
2172 assert_eq!(
2173 report.lines[0], "project: session-project via session (project switch)",
2174 "a NAME must not become the effective tier: {:?}",
2175 report.lines
2176 );
2177 assert!(
2178 report
2179 .warnings
2180 .iter()
2181 .any(|w| w.contains("TRACEVAULT_PROJECT") && w.contains("UUID form")),
2182 "the ignored NAME must be explained: {:?}",
2183 report.warnings
2184 );
2185 }
2186
2187 #[tokio::test]
2192 async fn status_reports_env_uuid_even_without_a_client() {
2193 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2194 let tmp = tempfile::tempdir().unwrap();
2195
2196 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2197 _guard.set("XDG_CONFIG_HOME", tmp.path());
2198 _guard.set("HOME", tmp.path());
2199 _guard.remove("TRACEVAULT_SERVER_URL");
2200 _guard.remove("TRACEVAULT_API_KEY");
2201 _guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
2202 let uuid = "33333333-3333-4333-8333-333333333333";
2203 _guard.set("TRACEVAULT_PROJECT", uuid);
2204
2205 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2206 assert_eq!(
2207 report.lines[0],
2208 format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2209 "got: {:?}",
2210 report.lines
2211 );
2212 }
2213
2214 #[tokio::test]
2222 async fn status_reports_explicit_via_env_even_when_the_binding_itself_is_not_forced() {
2223 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2224 let tmp = tempfile::tempdir().unwrap();
2225
2226 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2227 _guard.set("XDG_CONFIG_HOME", tmp.path());
2228 _guard.set("HOME", tmp.path());
2229 _guard.remove("TRACEVAULT_SERVER_URL");
2230 _guard.remove("TRACEVAULT_API_KEY");
2231 let uuid = "44444444-4444-4444-8444-444444444444";
2232 _guard.set("TRACEVAULT_PROJECT", uuid);
2233 _guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
2234
2235 let report = status_report(None, None, tmp.path(), tmp.path()).await;
2236 assert_eq!(
2237 report.lines,
2238 vec![
2239 format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
2240 "attribution mode: explicit (this caller owns attribution; membership is not checked)".to_string(),
2241 ],
2242 "the EFFECTIVE mode must reflect TRACEVAULT_PROJECT_ATTRIBUTION even when \
2243 the winning binding has no force of its own, and the lapse line must NOT \
2244 appear (there is no persisted force to lapse)"
2245 );
2246 }
2247}