use crate::program::{CLI, ENV};
use std::collections::HashSet;
use std::path::Path;
use crate::api_client::{resolve_client, ApiClient, ProjectListItem, ResolveProjectOutcome};
use crate::resolution::{
capture_project_binding, capture_project_id, git_remote_url, CaptureProjectInputs,
ProjectSource,
};
use crate::session_state::{self, ProjectBinding, SessionState};
#[derive(clap::Subcommand)]
pub enum ProjectCmd {
Switch {
name: String,
#[arg(long)]
user: bool,
#[arg(long)]
session_id: Option<String>,
#[arg(long, value_parser = ["derived", "explicit"], default_value = "derived")]
project_attribution: String,
},
Status {
#[arg(long)]
session_id: Option<String>,
#[arg(long)]
project: Option<String>,
},
}
pub async fn run(
cmd: ProjectCmd,
project_root: &Path,
cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
match cmd {
ProjectCmd::Switch {
name,
user,
session_id,
project_attribution,
} => {
switch(
&name,
user,
session_id.as_deref(),
&project_attribution,
project_root,
cwd,
)
.await
}
ProjectCmd::Status {
session_id,
project,
} => status(session_id.as_deref(), project.as_deref(), project_root, cwd).await,
}
}
fn resolve_project_name<'a>(
items: &'a [ProjectListItem],
name: &str,
) -> Result<&'a ProjectListItem, String> {
items.iter().find(|p| p.name == name).ok_or_else(|| {
let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
names.sort_unstable();
format!(
"project '{name}' not found. Available: {}",
names.join(", ")
)
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CodebaseCheck {
Skip,
Enforce,
Report,
}
fn codebase_check_for(dest: &SwitchDest, explicit: bool) -> CodebaseCheck {
match (dest, explicit) {
(SwitchDest::UserDefault, _) => CodebaseCheck::Skip,
(SwitchDest::Session(_), true) => CodebaseCheck::Report,
(SwitchDest::Session(_), false) => CodebaseCheck::Enforce,
}
}
async fn resolve_switch_project(
name: &str,
client: &ApiClient,
check: CodebaseCheck,
cwd: &Path,
) -> Result<(ProjectBinding, Option<String>), Box<dyn std::error::Error>> {
let items = client.list_projects().await?;
let matched = resolve_project_name(&items, name)
.map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
let project_id = matched.id;
let project_name = matched.name.clone();
let mut note = None;
if check != CodebaseCheck::Skip {
if let Some(git_url) = git_remote_url(cwd) {
if let Some(remote) = client.resolve_remote(&git_url).await? {
let codebase_repo_ids: HashSet<uuid::Uuid> = client
.get_remote_repos(remote.remote_id)
.await?
.into_iter()
.map(|r| r.id)
.collect();
let project_repo_ids: HashSet<uuid::Uuid> = client
.get_project(project_id)
.await?
.repos
.into_iter()
.map(|r| r.id)
.collect();
if codebase_repo_ids.is_disjoint(&project_repo_ids) {
match check {
CodebaseCheck::Enforce => {
return Err(format!(
"project '{name}' does not contain the current codebase"
)
.into())
}
CodebaseCheck::Report => note = Some(forced_non_member_note(name)),
CodebaseCheck::Skip => unreachable!("guarded above"),
}
}
}
}
}
Ok((
ProjectBinding {
project_id: project_id.to_string(),
project_name,
updated_at: chrono::Utc::now().to_rfc3339(),
forced_until: None,
},
note,
))
}
fn forced_non_member_note(name: &str) -> String {
format!(
"note: project '{name}' does not contain the current codebase — binding it anyway \
because --project-attribution explicit says this caller owns attribution. The \
server enforces that claim at ingest (Operator on the project, and a Control Plane \
identity — never a `tvk_` API key) and refuses it with a 403 otherwise."
)
}
#[derive(Debug)]
enum SwitchDest {
Session(String),
UserDefault,
}
fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
if user {
return SwitchDest::UserDefault;
}
match session_id {
Some(id) => SwitchDest::Session(id),
None => SwitchDest::UserDefault,
}
}
fn apply_force(mut binding: ProjectBinding, explicit: bool) -> ProjectBinding {
binding.forced_until = explicit.then(|| {
(chrono::Utc::now()
+ chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS))
.to_rfc3339()
});
binding
}
fn format_force_line(forced_until: &str) -> String {
match crate::session_state::force_status(forced_until) {
crate::session_state::ForceStatus::Live(until) => {
format!("persisted force: active until {}", until.to_rfc3339())
}
crate::session_state::ForceStatus::Lapsed(until) => {
format!("persisted force: lapsed {}", until.to_rfc3339())
}
crate::session_state::ForceStatus::Unreadable => format!(
"persisted force: unreadable timestamp ('{forced_until}'), treated as not in force"
),
}
}
fn attribution_report(b: &ProjectBinding) -> Vec<String> {
let mode = crate::commands::stream::attribution_mode(Some(b));
let gloss = match mode {
crate::api_client::AttributionMode::Explicit => {
"this caller owns attribution; membership is not checked"
}
crate::api_client::AttributionMode::Derived => "Visdom checks repo/project membership",
};
let mut lines = vec![format!("attribution mode: {mode} ({gloss})")];
if let Some(forced_until) = b.forced_until.as_deref() {
lines.push(format_force_line(forced_until));
}
lines
}
fn switch_report(
dest: &SwitchDest,
b: &ProjectBinding,
codebase_note: Option<&str>,
) -> Vec<String> {
let mut lines = match dest {
SwitchDest::Session(id) => {
vec![format!("bound session {id} to project {}", b.project_name)]
}
SwitchDest::UserDefault => vec![format!(
"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)",
b.project_name
)],
};
lines.extend(codebase_note.map(str::to_string));
lines.extend(attribution_report(b));
lines
}
async fn switch(
name: &str,
user: bool,
session_id: Option<&str>,
project_attribution: &str,
project_root: &Path,
cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
let client = resolve_client(project_root)?;
let session = crate::commands::repo::resolve_session_id(session_id).ok();
let dest = switch_destination(user, session);
let explicit = project_attribution == "explicit";
let check = codebase_check_for(&dest, explicit);
let (binding, codebase_note) = resolve_switch_project(name, &client, check, cwd).await?;
let binding = apply_force(binding, explicit);
match &dest {
SwitchDest::Session(id) => {
let mut state = session_state::load(id);
state.active_project = Some(binding.clone());
session_state::save(id, &state)?;
}
SwitchDest::UserDefault => {
crate::user_project_default::save(&binding)?;
}
}
for line in switch_report(&dest, &binding, codebase_note.as_deref()) {
println!("{line}");
}
Ok(())
}
fn status_effective(
project_flag: Option<ProjectBinding>,
env_project: Option<ProjectBinding>,
session: &SessionState,
worktree: Option<&str>,
config_project: Option<ProjectBinding>,
user_default: Option<ProjectBinding>,
) -> (Option<(ProjectBinding, ProjectSource)>, Option<String>) {
match capture_project_binding(&CaptureProjectInputs {
project_flag,
env_project,
session,
worktree_path: worktree,
config_project,
user_default,
}) {
Some((binding, source)) if capture_project_id(&binding).is_none() => {
let warning = invalid_capture_id_warning(&binding, source);
(None, Some(warning))
}
other => (other, None),
}
}
fn enrich_project_name(
effective: Option<(ProjectBinding, ProjectSource)>,
items: Option<&[ProjectListItem]>,
) -> Option<(ProjectBinding, ProjectSource)> {
effective.map(|(mut binding, source)| {
if binding.project_name.is_empty() {
if let Some(items) = items {
if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
if let Some(matched) = items.iter().find(|p| p.id == id) {
binding.project_name = matched.name.clone();
}
}
}
}
(binding, source)
})
}
fn env_name_form_warning(raw: &str) -> String {
format!(
"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>`"
)
}
fn binding_label(b: &ProjectBinding) -> &str {
if b.project_name.is_empty() {
&b.project_id
} else {
&b.project_name
}
}
fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
match effective {
Some((b, source)) => format!("project: {} via {source}", binding_label(b)),
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(),
}
}
fn invalid_capture_id_warning(binding: &ProjectBinding, source: ProjectSource) -> String {
format!(
"warning: project {} — {source}, but the saved project_id is not a valid id and is dropped at capture time; run `{}` to rewrite it",
binding_label(binding),
source.rewrite_command()
)
}
fn offline_project_flag_warning(name: &str) -> String {
format!(
"warning: --project '{name}' cannot be resolved without server credentials; ignoring the override"
)
}
fn deduced_project_name(pid: uuid::Uuid, items: Option<&[ProjectListItem]>) -> Option<&str> {
items?.iter().find(|p| p.id == pid).map(|p| p.name.as_str())
}
fn format_deduction(
effective_is_bound: bool,
outcome: Result<ResolveProjectOutcome, String>,
resolved_name: Option<&str>,
) -> String {
const PREFIX: &str = "server deduction for this repo:";
match outcome {
Ok(ResolveProjectOutcome::Resolved(pid)) => {
let pid = pid.to_string();
let label = resolved_name.unwrap_or(&pid);
if effective_is_bound {
format!("{PREFIX} {label} (not used: the local binding above wins)")
} else {
format!("{PREFIX} {label} (events will land here if a repo is bound)")
}
}
Ok(ResolveProjectOutcome::Ambiguous) => {
if effective_is_bound {
format!(
"{PREFIX} ambiguous (multiple projects) — not used, the local binding above wins"
)
} else {
format!(
"{PREFIX} ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `{CLI} project switch <name>`"
)
}
}
Ok(ResolveProjectOutcome::None) => format!("{PREFIX} none"),
Err(msg) => format!("{PREFIX} unavailable ({msg})"),
}
}
#[derive(Debug, Default)]
struct StatusReport {
warnings: Vec<String>,
lines: Vec<String>,
}
async fn status(
session_id: Option<&str>,
project_flag_name: Option<&str>,
project_root: &Path,
cwd: &Path,
) -> Result<(), Box<dyn std::error::Error>> {
let report = status_report(session_id, project_flag_name, project_root, cwd).await;
for warning in &report.warnings {
eprintln!("{warning}");
}
for line in &report.lines {
println!("{line}");
}
Ok(())
}
async fn status_report(
session_id: Option<&str>,
project_flag_name: Option<&str>,
project_root: &Path,
cwd: &Path,
) -> StatusReport {
let mut report = StatusReport::default();
let session = match crate::commands::repo::resolve_session_id(session_id) {
Ok(id) => session_state::load(&id),
Err(_) => {
report.warnings.push(
crate::program::say(
"warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
showing binding without session context",
)
.to_string(),
);
SessionState::default()
}
};
let worktree = crate::paths::worktree_toplevel(cwd);
let config = crate::config::TracevaultConfig::load(project_root);
let config_project = config
.as_ref()
.and_then(crate::resolution::project_from_config);
let user_default = crate::user_project_default::load();
let git_url = git_remote_url(cwd);
let env_project = crate::commands::stream::env_project_binding();
let env_raw = std::env::var("TRACEVAULT_PROJECT")
.ok()
.map(|raw| raw.trim().to_string())
.filter(|raw| !raw.is_empty());
if env_project.is_none() {
if let Some(raw) = env_raw.as_deref() {
report.warnings.push(env_name_form_warning(raw));
}
}
let client = match resolve_client(project_root) {
Ok(client) => Some(client),
Err(e) => {
report.warnings.push(format!(
"warning: could not resolve credentials ({e}); server deduction not shown"
));
None
}
};
let mut items: Option<Vec<ProjectListItem>> = None;
let project_flag = match (project_flag_name, client.as_ref()) {
(Some(name), Some(client)) => {
items = client.list_projects().await.ok();
let flag = items
.as_deref()
.and_then(|items| resolve_project_name(items, name).ok())
.map(|matched| ProjectBinding {
project_id: matched.id.to_string(),
project_name: matched.name.clone(),
updated_at: chrono::Utc::now().to_rfc3339(),
forced_until: None,
});
if flag.is_none() {
report.warnings.push(format!(
"warning: --project '{name}' could not be resolved; ignoring the override"
));
}
flag
}
(Some(name), None) => {
report.warnings.push(offline_project_flag_warning(name));
None
}
(None, _) => None,
};
if items.is_none() && env_project.is_some() {
if let Some(client) = client.as_ref() {
items = client.list_projects().await.ok();
}
}
let (effective, invalid_id_warning) = status_effective(
project_flag,
env_project,
&session,
Some(&worktree),
config_project.clone(),
user_default,
);
report.warnings.extend(invalid_id_warning);
let effective = enrich_project_name(effective, items.as_deref());
if let Some(notice) = config
.as_ref()
.and_then(crate::commands::migrate::legacy_default_project_notice)
{
report.warnings.push(format!("warning: {notice}"));
}
report
.lines
.push(format_status(effective.as_ref().map(|(b, s)| (b, *s))));
if let Some((b, _)) = effective.as_ref() {
report.lines.extend(attribution_report(b));
}
let bound_repo = config
.as_ref()
.and_then(crate::resolution::binding_from_config);
report
.lines
.push(crate::commands::stream::recording_line_for(
&crate::commands::stream::recording_attribution_for(
&session,
&worktree,
bound_repo,
crate::user_default::load(),
config_project,
),
));
if let (Some(client), Some(url)) = (client.as_ref(), git_url.as_deref()) {
let outcome = client.resolve_project(url).await.map_err(|e| e.to_string());
let name = match &outcome {
Ok(ResolveProjectOutcome::Resolved(pid)) => {
deduced_project_name(*pid, items.as_deref())
}
_ => None,
};
report
.lines
.push(format_deduction(effective.is_some(), outcome, name));
}
report
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::thread;
#[test]
fn resolve_project_name_exact_match_and_miss() {
let items = vec![
ProjectListItem {
id: uuid::Uuid::nil(),
name: "payments".into(),
},
ProjectListItem {
id: uuid::Uuid::from_u128(2),
name: "web".into(),
},
];
let ok = resolve_project_name(&items, "web").unwrap();
assert_eq!(ok.id, uuid::Uuid::from_u128(2));
let err = resolve_project_name(&items, "Web").unwrap_err(); assert!(err.contains("payments") && err.contains("web")); }
#[test]
fn switch_destination_user_flag_forces_user_default() {
assert!(matches!(
switch_destination(true, Some("sess-1".to_string())),
SwitchDest::UserDefault
));
assert!(matches!(
switch_destination(true, None),
SwitchDest::UserDefault
));
}
#[test]
fn switch_destination_session_when_present_and_no_user_flag() {
assert!(matches!(
switch_destination(false, Some("sess-1".to_string())),
SwitchDest::Session(id) if id == "sess-1"
));
}
#[test]
fn switch_destination_user_default_when_no_session() {
assert!(matches!(
switch_destination(false, None),
SwitchDest::UserDefault
));
}
#[test]
fn switching_with_explicit_stamps_a_lapse_time() {
let before = chrono::Utc::now();
let binding = apply_force(
ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "p".into(),
updated_at: before.to_rfc3339(),
forced_until: None,
},
true,
);
let until = chrono::DateTime::parse_from_rfc3339(
binding.forced_until.as_deref().expect("force is stamped"),
)
.unwrap();
let expected = before
+ chrono::Duration::hours(crate::user_project_default::DEFAULT_FORCE_LIFETIME_HOURS);
assert!((until.timestamp() - expected.timestamp()).abs() < 5);
}
#[test]
fn switching_without_explicit_stamps_no_lapse_time() {
let binding = apply_force(
ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "p".into(),
updated_at: chrono::Utc::now().to_rfc3339(),
forced_until: Some("2020-01-01T00:00:00Z".into()),
},
false,
);
assert_eq!(
binding.forced_until, None,
"switching without --project-attribution explicit must CLEAR a stale force"
);
}
#[test]
fn format_force_line_distinguishes_a_live_force_from_a_lapsed_one() {
let future = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
let live = format_force_line(&future);
assert!(live.contains("active until"), "got: {live}");
assert!(live.contains(&future), "got: {live}");
let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
let lapsed = format_force_line(&past);
assert!(lapsed.contains("lapsed"), "got: {lapsed}");
assert!(lapsed.contains(&past), "got: {lapsed}");
for line in [&live, &lapsed] {
assert!(!line.contains("derived"), "got: {line}");
assert!(!line.contains("explicit"), "got: {line}");
assert!(!line.contains("membership"), "got: {line}");
}
}
#[test]
fn status_names_a_lapsed_force_as_lapsed_not_active() {
let past = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
let line = format_force_line(&past);
assert!(line.contains("lapsed"), "got: {line}");
assert!(!line.contains("active until"), "got: {line}");
}
#[test]
fn status_names_unparseable_forced_until_as_not_in_force() {
let line = format_force_line("not-a-timestamp");
assert!(line.contains("not in force"), "got: {line}");
assert!(!line.contains("active until"), "got: {line}");
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: Some("not-a-timestamp".into()),
};
assert_eq!(
crate::commands::stream::attribution_mode(Some(&b)),
crate::api_client::AttributionMode::Derived,
"the reported state and the header must agree on an unreadable force"
);
}
#[test]
fn attribution_report_omits_the_lapse_line_when_there_is_no_persisted_force() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: None,
};
let lines = attribution_report(&b);
assert_eq!(
lines.len(),
1,
"an env-only force has no lapse to report, and must not be \
contradicted by a `derived` line: {lines:?}"
);
assert!(
lines[0].starts_with("attribution mode: explicit"),
"got: {lines:?}"
);
assert!(
!lines.iter().any(|l| l.contains("derived")),
"got: {lines:?}"
);
}
#[test]
fn attribution_report_keeps_the_lapse_line_for_a_persisted_force() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let until = (chrono::Utc::now() + chrono::Duration::hours(4)).to_rfc3339();
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: Some(until.clone()),
};
let lines = attribution_report(&b);
assert_eq!(lines.len(), 2, "got: {lines:?}");
assert!(
lines[0].starts_with("attribution mode: explicit"),
"got: {}",
lines[0]
);
assert!(lines[1].contains("active until"), "got: {}", lines[1]);
assert!(lines[1].contains(&until), "got: {}", lines[1]);
}
#[test]
fn attribution_report_reports_a_lapsed_persisted_force_as_derived() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: Some((chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339()),
};
let lines = attribution_report(&b);
assert_eq!(lines.len(), 2, "got: {lines:?}");
assert!(
lines[0].starts_with("attribution mode: derived"),
"got: {}",
lines[0]
);
assert!(
lines[1].starts_with("persisted force: lapsed"),
"got: {}",
lines[1]
);
}
#[test]
fn a_lapsed_persisted_force_never_contradicts_an_env_force() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let lapsed = (chrono::Utc::now() - chrono::Duration::hours(1)).to_rfc3339();
for forced_until in [lapsed.as_str(), "not-a-timestamp"] {
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: Some(forced_until.to_string()),
};
let lines = attribution_report(&b);
assert_eq!(lines.len(), 2, "{forced_until}: got {lines:?}");
assert!(
lines[0].starts_with("attribution mode: explicit"),
"{forced_until}: the env force decides the mode: {lines:?}"
);
assert!(
!lines[1].contains("derived"),
"{forced_until}: the detail line must not render a competing \
verdict while the env force makes this send explicit: {lines:?}"
);
assert!(
!lines[1].contains("membership is checked"),
"{forced_until}: membership is NOT being checked here: {lines:?}"
);
}
}
#[test]
fn switch_report_names_the_env_force_and_never_claims_derived() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let b = ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: None,
};
for dest in [
SwitchDest::Session("sess-1".to_string()),
SwitchDest::UserDefault,
] {
let lines = switch_report(&dest, &b, None);
assert!(
lines[0].contains("payments"),
"the first line still says what was bound: {lines:?}"
);
assert!(
lines
.iter()
.any(|l| l.starts_with("attribution mode: explicit")),
"a `switch` in an explicit shell must say so: {lines:?}"
);
assert!(
!lines.iter().any(|l| l.contains("derived")),
"{dest:?}: `switch` must not claim membership is checked while \
every hook in this shell sends `explicit`: {lines:?}"
);
}
}
#[test]
fn switch_report_names_the_lapse_it_just_stamped() {
let _env_lock = crate::test_helpers::lock_env_mutation_sync();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let b = apply_force(
ProjectBinding {
project_id: "3f2504e0-4f89-11d3-9a0c-0305e82c3301".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: None,
},
true,
);
let lines = switch_report(&SwitchDest::Session("sess-1".to_string()), &b, None);
assert_eq!(lines.len(), 3, "got: {lines:?}");
assert!(
lines[1].starts_with("attribution mode: explicit"),
"got: {}",
lines[1]
);
assert!(
lines[2].starts_with("persisted force: active until"),
"got: {}",
lines[2]
);
}
fn pb(name: &str) -> ProjectBinding {
ProjectBinding {
project_id: format!("id-{name}"),
project_name: name.into(),
updated_at: "t".into(),
forced_until: None,
}
}
#[test]
fn format_status_unbound() {
assert_eq!(
format_status(None),
"no project bound locally; if a repo is bound, events are sent repo-scoped and the server deduces the project from the repo"
);
}
#[test]
fn format_status_project_flag() {
let b = pb("web");
assert_eq!(
format_status(Some((&b, ProjectSource::ProjectFlag))),
"project: web via --project override"
);
}
#[test]
fn format_status_session_active() {
let b = pb("payments");
assert_eq!(
format_status(Some((&b, ProjectSource::SessionActive))),
"project: payments via session (project switch)"
);
}
#[test]
fn format_status_falls_back_to_id_when_name_empty() {
let b = ProjectBinding {
project_id: "some-id".into(),
project_name: String::new(),
updated_at: "".into(),
forced_until: None,
};
assert_eq!(
format_status(Some((&b, ProjectSource::UserDefault))),
"project: some-id via user default (project switch --user)"
);
}
#[test]
fn format_status_env() {
let b = pb("payments");
assert_eq!(
format_status(Some((&b, ProjectSource::Env))),
"project: payments via TRACEVAULT_PROJECT (environment)"
);
}
#[test]
fn invalid_capture_id_warning_names_tier_and_rewrite_command() {
let b = ProjectBinding {
project_id: "not-a-uuid".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: None,
};
assert_eq!(
invalid_capture_id_warning(&b, ProjectSource::UserDefault),
"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"
);
assert_eq!(
invalid_capture_id_warning(&b, ProjectSource::Workspace),
"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"
);
}
#[test]
fn status_effective_drops_a_non_uuid_binding_with_a_warning_naming_the_tier() {
let session = SessionState {
active_project: Some(ProjectBinding {
project_id: "not-a-uuid".into(),
project_name: "payments".into(),
updated_at: "".into(),
forced_until: None,
}),
..Default::default()
};
let (effective, warning) = status_effective(None, None, &session, None, None, None);
assert!(effective.is_none(), "{effective:?}");
let warning = warning.expect("a dropped binding must be explained");
assert!(
warning.contains("session (project switch)"),
"must name the tier: {warning}"
);
assert!(warning.contains("payments"), "{warning}");
let pid = uuid::Uuid::from_u128(5);
let valid = SessionState {
active_project: Some(ProjectBinding {
project_id: pid.to_string(),
project_name: "web".into(),
updated_at: "".into(),
forced_until: None,
}),
..Default::default()
};
let (effective, warning) = status_effective(None, None, &valid, None, None, None);
assert_eq!(
effective.map(|(b, s)| (b.project_id, s)),
Some((pid.to_string(), ProjectSource::SessionActive))
);
assert_eq!(warning, None);
}
#[test]
fn status_effective_places_env_at_rung_three() {
let u = uuid::Uuid::from_u128;
let bind = |id: uuid::Uuid, name: &str| ProjectBinding {
project_id: id.to_string(),
project_name: name.into(),
updated_at: "".into(),
forced_until: None,
};
let session = SessionState {
active_project: Some(bind(u(2), "session")),
..Default::default()
};
let (effective, _) = status_effective(
None,
Some(bind(u(9), "env")),
&session,
None,
None,
Some(bind(u(3), "user")),
);
assert_eq!(
effective.map(|(b, s)| (b.project_id, s)),
Some((u(9).to_string(), ProjectSource::Env))
);
let (effective, _) = status_effective(
Some(bind(u(1), "flag")),
Some(bind(u(9), "env")),
&session,
None,
None,
Some(bind(u(3), "user")),
);
assert_eq!(
effective.map(|(b, s)| (b.project_id, s)),
Some((u(1).to_string(), ProjectSource::ProjectFlag))
);
}
#[test]
fn offline_project_flag_warning_says_the_override_is_ignored() {
assert_eq!(
offline_project_flag_warning("web"),
"warning: --project 'web' cannot be resolved without server credentials; ignoring the override"
);
}
#[test]
fn env_name_form_warning_says_only_the_uuid_form_is_used() {
let warning = env_name_form_warning("payments");
assert!(warning.contains("payments"), "{warning}");
assert!(warning.contains("UUID form"), "{warning}");
assert!(
warning.contains("not used") || warning.contains("ignored"),
"{warning}"
);
}
const DEDUCED: uuid::Uuid = uuid::Uuid::from_u128(2);
#[test]
fn format_deduction_resolved_bound() {
assert_eq!(
format_deduction(true, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
format!(
"server deduction for this repo: {DEDUCED} (not used: the local binding above wins)"
)
);
}
#[test]
fn format_deduction_resolved_unbound() {
assert_eq!(
format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), None),
format!("server deduction for this repo: {DEDUCED} (events will land here if a repo is bound)")
);
}
#[test]
fn format_deduction_resolved_uses_name_when_known() {
let items = items();
let name = deduced_project_name(DEDUCED, Some(&items));
assert_eq!(name, Some("web"));
assert_eq!(
format_deduction(false, Ok(ResolveProjectOutcome::Resolved(DEDUCED)), name),
"server deduction for this repo: web (events will land here if a repo is bound)"
);
}
#[test]
fn deduced_project_name_none_without_list_or_match() {
assert_eq!(deduced_project_name(DEDUCED, None), None);
assert_eq!(
deduced_project_name(uuid::Uuid::from_u128(999), Some(&items())),
None
);
}
#[test]
fn format_deduction_ambiguous_bound() {
assert_eq!(
format_deduction(true, Ok(ResolveProjectOutcome::Ambiguous), None),
"server deduction for this repo: ambiguous (multiple projects) — not used, the local binding above wins"
);
}
#[test]
fn format_deduction_ambiguous_unbound() {
assert_eq!(
format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
"server deduction for this repo: ambiguous (multiple projects) — if a repo is bound, events will be refused until you run `tracevault project switch <name>`"
);
}
#[test]
fn format_deduction_none() {
for bound in [true, false] {
assert_eq!(
format_deduction(bound, Ok(ResolveProjectOutcome::None), None),
"server deduction for this repo: none"
);
}
}
#[test]
fn format_deduction_err() {
for bound in [true, false] {
assert_eq!(
format_deduction(bound, Err("connection refused".into()), None),
"server deduction for this repo: unavailable (connection refused)"
);
}
}
#[test]
fn format_status_user_default() {
let b = pb("payments");
assert_eq!(
format_status(Some((&b, ProjectSource::UserDefault))),
"project: payments via user default (project switch --user)"
);
}
fn spawn_once(response: String) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let response: &'static str = Box::leak(response.into_boxed_str());
thread::spawn(move || {
if let Ok((stream, _)) = listener.accept() {
let mut reader = BufReader::new(stream);
let mut request_line = String::new();
let _ = reader.read_line(&mut request_line);
let mut stream = reader.into_inner();
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
});
format!("http://{addr}")
}
fn spawn_n(responses: Vec<String>) -> String {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
for response in responses {
let response: &'static str = Box::leak(response.into_boxed_str());
if let Ok((stream, _)) = listener.accept() {
let mut reader = BufReader::new(stream);
let mut request_line = String::new();
let _ = reader.read_line(&mut request_line);
let mut stream = reader.into_inner();
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
}
});
format!("http://{addr}")
}
fn http_200(body: &str) -> String {
format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
)
}
#[tokio::test]
async fn project_switch_happy_path_writes_active_project_to_session_file() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let state_tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_STATE_HOME", state_tmp.path());
let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
let base = spawn_once(http_200(list));
let client = ApiClient::new(&base, Some("tok"));
let (binding, note) =
resolve_switch_project("web", &client, CodebaseCheck::Enforce, tmp.path())
.await
.expect("expected Ok binding");
assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
assert_eq!(binding.project_name, "web");
assert_eq!(note, None, "no remote to check against, so nothing to note");
let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
let mut state = session_state::load(&session_id);
state.active_project = Some(binding.clone());
session_state::save(&session_id, &state).expect("save must succeed");
let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
assert!(sessions_dir.starts_with(state_tmp.path()));
let loaded = session_state::load_from(&sessions_dir, &session_id);
assert_eq!(loaded.active_project, Some(binding));
}
#[tokio::test]
async fn project_switch_errors_when_name_not_found() {
let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
let base = spawn_once(http_200(list));
let client = ApiClient::new(&base, Some("tok"));
let err = resolve_switch_project(
"web",
&client,
CodebaseCheck::Skip,
Path::new("/nonexistent"),
)
.await
.expect_err("expected Err for an unknown project name");
let msg = err.to_string();
assert!(msg.contains("not found"), "got: {msg}");
assert!(msg.contains("payments"), "got: {msg}");
}
#[tokio::test]
async fn project_switch_errors_when_project_does_not_contain_codebase() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let ok = std::process::Command::new("git")
.args([
"-C",
&tmp.path().to_string_lossy(),
"remote",
"add",
"origin",
"git@github.com:org/repo.git",
])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
let list =
r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
let remote = format!(
r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
);
let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
let detail = format!(
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"}}]}}"#
);
let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
let base = spawn_n(vec![
http_200(&list),
http_200(&remote),
http_200(&detail),
http_200(project_detail),
]);
let client = ApiClient::new(&base, Some("tok"));
let err = resolve_switch_project("payments", &client, CodebaseCheck::Enforce, tmp.path())
.await
.expect_err("expected Err: project doesn't contain the current codebase");
assert!(
err.to_string()
.contains("does not contain the current codebase"),
"got: {err}"
);
}
#[tokio::test]
async fn explicit_attribution_binds_a_non_member_project_and_says_so() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let ok = std::process::Command::new("git")
.args([
"-C",
&tmp.path().to_string_lossy(),
"remote",
"add",
"origin",
"git@github.com:org/repo.git",
])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
let list =
r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
let remote = format!(
r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
);
let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
let detail = format!(
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"}}]}}"#
);
let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
let base = spawn_n(vec![
http_200(&list),
http_200(&remote),
http_200(&detail),
http_200(project_detail),
]);
let client = ApiClient::new(&base, Some("tok"));
let (binding, note) =
resolve_switch_project("payments", &client, CodebaseCheck::Report, tmp.path())
.await
.expect("a forced switch must not be blocked by the containment check");
assert_eq!(binding.project_id, "11111111-1111-4111-8111-111111111111");
let note = note.expect("the user must still be told the project is not a member");
assert!(
note.contains("does not contain the current codebase"),
"the fact must be stated: {note}"
);
assert!(
note.contains("--project-attribution explicit"),
"must say what made it deliberate: {note}"
);
assert!(
note.contains("Operator") && note.contains("ingest"),
"must say where the requirement is actually enforced: {note}"
);
assert!(
!note.starts_with("error"),
"this is informational, not a failure: {note}"
);
}
#[test]
fn only_an_explicit_session_switch_downgrades_the_containment_check() {
let session = SwitchDest::Session("s".into());
assert_eq!(
codebase_check_for(&session, true),
CodebaseCheck::Report,
"--project-attribution explicit must not be blocked"
);
assert_eq!(
codebase_check_for(&session, false),
CodebaseCheck::Enforce,
"an ordinary session switch keeps erroring"
);
assert_eq!(
codebase_check_for(&SwitchDest::UserDefault, true),
CodebaseCheck::Skip
);
assert_eq!(
codebase_check_for(&SwitchDest::UserDefault, false),
CodebaseCheck::Skip
);
}
#[tokio::test]
async fn switch_without_session_or_user_flag_skips_codebase_check() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let ok = std::process::Command::new("git")
.args([
"-C",
&tmp.path().to_string_lossy(),
"remote",
"add",
"origin",
"git@github.com:org/repo.git",
])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
let list =
r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
let base = spawn_once(http_200(&list));
let config_dir = tmp.path().join(".visdom");
std::fs::create_dir_all(&config_dir).unwrap();
std::fs::write(
config_dir.join("tracing.toml"),
format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\n"),
)
.unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_SESSION_ID");
_guard.remove("AMP_CURRENT_THREAD_ID");
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_SERVER_URL", &base);
_guard.set("TRACEVAULT_API_KEY", "tok");
let result = switch("payments", false, None, "derived", tmp.path(), tmp.path()).await;
assert!(
result.is_ok(),
"expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
);
let saved = crate::user_project_default::load();
assert_eq!(
saved.map(|b| b.project_name),
Some("payments".to_string()),
"no-session switch must fall back to the user-level default binding"
);
}
fn items() -> Vec<ProjectListItem> {
vec![
ProjectListItem {
id: uuid::Uuid::from_u128(1),
name: "payments".into(),
},
ProjectListItem {
id: uuid::Uuid::from_u128(2),
name: "web".into(),
},
]
}
fn nameless(id: uuid::Uuid, source: ProjectSource) -> (ProjectBinding, ProjectSource) {
(
ProjectBinding {
project_id: id.to_string(),
project_name: String::new(),
updated_at: "".into(),
forced_until: None,
},
source,
)
}
#[test]
fn enrich_project_name_fills_in_name_when_id_found_in_list() {
let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
let (b, source) = enrich_project_name(effective, Some(&items())).unwrap();
assert_eq!(b.project_name, "web");
assert_eq!(source, ProjectSource::Env);
}
#[test]
fn enrich_project_name_leaves_empty_when_no_list_available() {
let effective = Some(nameless(uuid::Uuid::from_u128(2), ProjectSource::Env));
let (b, _source) = enrich_project_name(effective, None).unwrap();
assert_eq!(b.project_name, "");
}
#[test]
fn enrich_project_name_leaves_empty_when_id_not_in_list() {
let effective = Some(nameless(uuid::Uuid::from_u128(999), ProjectSource::Env));
let (b, _source) = enrich_project_name(effective, Some(&items())).unwrap();
assert_eq!(b.project_name, "");
}
#[test]
fn enrich_project_name_leaves_a_populated_name_untouched() {
let b = pb("payments");
let effective = Some((b.clone(), ProjectSource::SessionActive));
let (out, source) = enrich_project_name(effective, Some(&items())).unwrap();
assert_eq!(out, b);
assert_eq!(source, ProjectSource::SessionActive);
}
#[test]
fn enrich_project_name_passes_through_none() {
assert!(enrich_project_name(None, Some(&items())).is_none());
}
#[tokio::test]
async fn project_status_effective_project_matches_capture_project() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
let u = uuid::Uuid::from_u128;
let bind = |id: String| ProjectBinding {
project_id: id,
project_name: "n".into(),
updated_at: "".into(),
forced_until: None,
};
let worktree = "/wt";
let subagent_session = {
let mut s = SessionState {
active_project: Some(bind(u(2).to_string())),
..Default::default()
};
s.subagent_projects
.insert(worktree.into(), bind(u(1).to_string()));
s
};
let active_session = SessionState {
active_project: Some(bind(u(2).to_string())),
..Default::default()
};
let bad_active_session = SessionState {
active_project: Some(bind("not-a-uuid".into())),
..Default::default()
};
type Case = (
&'static str,
SessionState,
Option<String>,
Option<String>,
Option<uuid::Uuid>,
);
let cases: Vec<Case> = vec![
(
"(a) subagent override + session active + user default",
subagent_session,
Some(u(3).to_string()),
None,
Some(u(1)),
),
(
"(b) session active + user default",
active_session.clone(),
Some(u(3).to_string()),
None,
Some(u(2)),
),
(
"(c) user default only",
SessionState::default(),
Some(u(3).to_string()),
None,
Some(u(3)),
),
("(d) nothing", SessionState::default(), None, None, None),
(
"(e) user default with a non-UUID project_id",
SessionState::default(),
Some("not-a-uuid".into()),
None,
None,
),
(
"(f) non-UUID session active shadows a valid user default",
bad_active_session,
Some(u(3).to_string()),
None,
None,
),
(
"(g) TRACEVAULT_PROJECT (UUID) outranks session active and the user default",
active_session.clone(),
Some(u(3).to_string()),
Some(u(4).to_string()),
Some(u(4)),
),
(
"(h) TRACEVAULT_PROJECT (NAME) is ignored by both",
active_session,
Some(u(3).to_string()),
Some("payments".into()),
Some(u(2)),
),
];
let session_active = || SessionState {
active_project: Some(bind(u(2).to_string())),
..Default::default()
};
type WorkspaceCase = (
&'static str,
SessionState,
Option<String>,
Option<String>,
Option<String>,
Option<uuid::Uuid>,
);
let workspace_cases: Vec<WorkspaceCase> = vec![
(
"(i) workspace config outranks the user default",
SessionState::default(),
Some(u(3).to_string()),
None,
Some(u(5).to_string()),
Some(u(5)),
),
(
"(j) session active (project switch) outranks the workspace config",
session_active(),
Some(u(3).to_string()),
None,
Some(u(5).to_string()),
Some(u(2)),
),
(
"(k) TRACEVAULT_PROJECT (UUID) outranks the workspace config",
SessionState::default(),
None,
Some(u(4).to_string()),
Some(u(5).to_string()),
Some(u(4)),
),
(
"(l) a non-UUID workspace project_id is dropped by both, shadowing the user default",
SessionState::default(),
Some(u(3).to_string()),
None,
Some("not-a-uuid".into()),
None,
),
];
let cases = cases
.into_iter()
.map(|(label, session, user, env, expected)| {
(label, session, user, env, None, expected)
})
.chain(workspace_cases);
for (label, session, user_default, env_project, config_project, expected) in cases {
match &user_default {
Some(id) => crate::user_project_default::save(&bind(id.clone())).unwrap(),
None => crate::user_project_default::clear().unwrap(),
}
match &env_project {
Some(v) => _guard.set("TRACEVAULT_PROJECT", v),
None => _guard.remove("TRACEVAULT_PROJECT"),
}
let config_project = config_project.and_then(|id| {
crate::resolution::project_from_config(&crate::config::TracevaultConfig {
project_id: Some(id),
..Default::default()
})
});
let status_pid = status_effective(
None,
crate::commands::stream::env_project_binding(),
&session,
Some(worktree),
config_project.clone(),
crate::user_project_default::load(),
)
.0
.and_then(|(b, _)| capture_project_id(&b));
let ingest_pid =
crate::commands::stream::capture_project(&session, Some(worktree), config_project);
assert_eq!(
status_pid, ingest_pid,
"{label}: status and ingest disagree"
);
assert_eq!(status_pid, expected, "{label}");
}
crate::user_project_default::clear().unwrap();
}
#[tokio::test]
async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let ok = std::process::Command::new("git")
.args([
"-C",
&tmp.path().to_string_lossy(),
"remote",
"add",
"origin",
"git@github.com:org/repo.git",
])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
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\"}";
let base = spawn_n(vec![conflict.to_string(), conflict.to_string()]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_SERVER_URL", &base);
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.remove("TRACEVAULT_SESSION_ID");
_guard.remove("AMP_CURRENT_THREAD_ID");
_guard.remove("TRACEVAULT_PROJECT");
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let result = status(None, None, tmp.path(), tmp.path()).await;
assert!(
result.is_ok(),
"status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
);
let report = status_report(None, None, tmp.path(), tmp.path()).await;
assert_eq!(
report.lines,
vec![
format_status(None),
crate::commands::stream::recording_line(None),
format_deduction(false, Ok(ResolveProjectOutcome::Ambiguous), None),
],
"the ambiguous deduction is reported on its own line"
);
}
#[tokio::test]
async fn status_in_the_orchestrator_configuration_names_the_user_default() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
crate::test_helpers::init_git_repo(&repo);
let ok = std::process::Command::new("git")
.args([
"-C",
&repo.to_string_lossy(),
"remote",
"add",
"origin",
"git@github.com:org/repo.git",
])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
let deduced_a = uuid::Uuid::from_u128(0xA);
let base = spawn_once(http_200(&format!(r#"{{"project_id":"{deduced_a}"}}"#)));
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("TRACEVAULT_SERVER_URL", &base);
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.set("XDG_STATE_HOME", tmp.path().join("state"));
_guard.remove("TRACEVAULT_SESSION_ID");
_guard.remove("AMP_CURRENT_THREAD_ID");
_guard.remove("TRACEVAULT_PROJECT");
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let default_b = ProjectBinding {
project_id: uuid::Uuid::from_u128(0xB).to_string(),
project_name: "project-b".into(),
updated_at: "".into(),
forced_until: None,
};
crate::user_project_default::save(&default_b).unwrap();
let report = status_report(None, None, &repo, &repo).await;
assert_eq!(
report.lines,
vec![
"project: project-b via user default (project switch --user)".to_string(),
"attribution mode: derived (Visdom checks repo/project membership)"
.to_string(),
crate::commands::stream::recording_line(Some(
&crate::commands::stream::Attribution::ProjectOnly {
project_id: uuid::Uuid::from_u128(0xB),
}
)),
format!(
"server deduction for this repo: {deduced_a} (not used: the local binding above wins)"
),
]
);
}
#[tokio::test]
async fn status_reports_env_uuid_as_the_effective_tier_with_its_name() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let uuid = "11111111-1111-4111-8111-111111111111";
let list = format!(r#"[{{"id":"{uuid}","name":"payments"}}]"#);
let base = spawn_once(http_200(&list));
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.set("TRACEVAULT_SERVER_URL", &base);
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.set("TRACEVAULT_PROJECT", uuid);
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
_guard.remove("TRACEVAULT_SESSION_ID");
_guard.remove("AMP_CURRENT_THREAD_ID");
let report = status_report(None, None, tmp.path(), tmp.path()).await;
assert_eq!(
report.lines[0], "project: payments via TRACEVAULT_PROJECT (environment)",
"got: {:?}",
report.lines
);
assert!(
report
.warnings
.iter()
.all(|w| !w.contains("TRACEVAULT_PROJECT")),
"the UUID form is honoured at capture time and needs no caveat: {:?}",
report.warnings
);
}
#[tokio::test]
async fn status_warns_that_an_env_name_is_not_used_and_falls_through() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.set("XDG_STATE_HOME", tmp.path().join("state"));
_guard.remove("TRACEVAULT_SERVER_URL");
_guard.remove("TRACEVAULT_API_KEY");
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
_guard.set("TRACEVAULT_PROJECT", "payments");
let session_id = "vis305-env-name-form";
let pid = uuid::Uuid::from_u128(0x5E);
crate::session_state::save(
session_id,
&SessionState {
active_project: Some(ProjectBinding {
project_id: pid.to_string(),
project_name: "session-project".into(),
updated_at: "".into(),
forced_until: None,
}),
..Default::default()
},
)
.unwrap();
let report = status_report(Some(session_id), None, tmp.path(), tmp.path()).await;
assert_eq!(
report.lines[0], "project: session-project via session (project switch)",
"a NAME must not become the effective tier: {:?}",
report.lines
);
assert!(
report
.warnings
.iter()
.any(|w| w.contains("TRACEVAULT_PROJECT") && w.contains("UUID form")),
"the ignored NAME must be explained: {:?}",
report.warnings
);
}
#[tokio::test]
async fn status_reports_env_uuid_even_without_a_client() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.remove("TRACEVAULT_SERVER_URL");
_guard.remove("TRACEVAULT_API_KEY");
_guard.remove("TRACEVAULT_PROJECT_ATTRIBUTION");
let uuid = "33333333-3333-4333-8333-333333333333";
_guard.set("TRACEVAULT_PROJECT", uuid);
let report = status_report(None, None, tmp.path(), tmp.path()).await;
assert_eq!(
report.lines[0],
format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
"got: {:?}",
report.lines
);
}
#[tokio::test]
async fn status_reports_explicit_via_env_even_when_the_binding_itself_is_not_forced() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("HOME", tmp.path());
_guard.remove("TRACEVAULT_SERVER_URL");
_guard.remove("TRACEVAULT_API_KEY");
let uuid = "44444444-4444-4444-8444-444444444444";
_guard.set("TRACEVAULT_PROJECT", uuid);
_guard.set("TRACEVAULT_PROJECT_ATTRIBUTION", "explicit");
let report = status_report(None, None, tmp.path(), tmp.path()).await;
assert_eq!(
report.lines,
vec![
format!("project: {uuid} via TRACEVAULT_PROJECT (environment)"),
"attribution mode: explicit (this caller owns attribution; membership is not checked)".to_string(),
crate::commands::stream::recording_line(Some(
&crate::commands::stream::Attribution::ProjectOnly {
project_id: uuid::Uuid::parse_str(uuid).unwrap(),
}
)),
],
"the EFFECTIVE mode must reflect TRACEVAULT_PROJECT_ATTRIBUTION even when \
the winning binding has no force of its own, and the lapse line must NOT \
appear (there is no persisted force to lapse)"
);
}
}