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