use std::path::Path;
use std::process::Command;
use crate::api_client::{ApiClient, RepoListItem, ResolveProjectOutcome};
use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
let out = std::process::Command::new("git")
.arg("-C")
.arg(path)
.args(["remote", "get-url", "origin"])
.output()
.ok()?;
if !out.status.success() {
return None;
}
let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
if url.is_empty() {
None
} else {
Some(url)
}
}
pub(crate) fn git_repo_name(project_root: &Path) -> String {
Command::new("git")
.args(["rev-parse", "--show-toplevel"])
.current_dir(project_root)
.output()
.ok()
.filter(|o| o.status.success())
.and_then(|o| repo_basename(String::from_utf8_lossy(&o.stdout).trim()))
.unwrap_or_else(|| "unknown".into())
}
fn repo_basename(toplevel: &str) -> Option<String> {
Path::new(toplevel)
.file_name()
.map(|n| n.to_string_lossy().into_owned())
}
#[derive(Debug)]
pub(crate) enum ResolveRepoByNameError {
ListFailed(Box<dyn std::error::Error>),
NotFound { repo_name: String },
}
pub(crate) async fn resolve_repo_by_name(
client: &ApiClient,
project_root: &Path,
) -> Result<RepoListItem, ResolveRepoByNameError> {
let repo_name = git_repo_name(project_root);
let repos = client
.list_repos()
.await
.map_err(ResolveRepoByNameError::ListFailed)?;
repos
.into_iter()
.find(|r| r.name == repo_name)
.ok_or(ResolveRepoByNameError::NotFound { repo_name })
}
pub(crate) fn codebase_line(
name: Option<&str>,
normalized_url: &str,
clone_status: &str,
) -> String {
format!(
"codebase: {} ({})",
name.unwrap_or(normalized_url),
clone_status
)
}
pub(crate) fn pick_status_line(
detail_line: Option<String>,
resolved_line: Option<String>,
cached_name: Option<&str>,
) -> Option<String> {
detail_line
.or(resolved_line)
.or_else(|| cached_name.map(|n| format!("codebase: {n}")))
}
pub async fn resolve_path_to_binding(
path: &Path,
client: &ApiClient,
) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
let Some(git_url) = git_remote_url(path) else {
return Ok(None);
};
let Some(remote) = client.resolve_remote(&git_url).await? else {
return Ok(None);
};
let repos = client.get_remote_repos(remote.remote_id).await?;
let Some(first) = repos.into_iter().min_by_key(|r| r.id) else {
return Err(format!(
"codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
remote.name.as_deref().unwrap_or(&remote.normalized_url)
)
.into());
};
Ok(Some(RepoBinding {
repo_id: first.id.to_string(),
git_url: Some(git_url),
remote_id: Some(remote.remote_id),
codebase_name: remote.name,
updated_at: chrono::Utc::now().to_rfc3339(),
}))
}
pub struct ResolveInputs<'a> {
pub repo_flag: Option<RepoBinding>,
pub session: &'a SessionState,
pub worktree_path: Option<&'a str>,
pub bound: Option<RepoBinding>,
pub user_default: Option<RepoBinding>,
}
pub struct ProjectResolveInputs<'a> {
pub project_flag: Option<ProjectBinding>,
pub session: &'a SessionState,
pub worktree_path: Option<&'a str>,
pub config_default: Option<ProjectBinding>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BindingSource {
RepoFlag,
Subagent,
SessionActive,
Bound,
UserDefault,
}
impl std::fmt::Display for BindingSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let label = match self {
BindingSource::RepoFlag => "--path override",
BindingSource::Subagent => "subagent worktree override",
BindingSource::SessionActive => "session (repo switch)",
BindingSource::Bound => "bound .tracevault/config.toml",
BindingSource::UserDefault => "user default (repo switch --user)",
};
f.write_str(label)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProjectSource {
ProjectFlag,
Subagent,
SessionActive,
ConfigDefault,
Deduced,
UserDefault,
}
impl std::fmt::Display for ProjectSource {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let label = match self {
ProjectSource::ProjectFlag => "--project override",
ProjectSource::Subagent => "subagent worktree override",
ProjectSource::SessionActive => "session (project switch)",
ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
ProjectSource::Deduced => "repo deduction",
ProjectSource::UserDefault => "user default (project switch --user)",
};
f.write_str(label)
}
}
pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
if let Some(b) = inputs.repo_flag {
return Some((b, BindingSource::RepoFlag));
}
if let Some(wt) = inputs.worktree_path {
if let Some(b) = inputs.session.subagents.get(wt) {
return Some((b.clone(), BindingSource::Subagent));
}
}
if let Some(b) = &inputs.session.active {
return Some((b.clone(), BindingSource::SessionActive));
}
if let Some(b) = inputs.bound {
return Some((b, BindingSource::Bound));
}
inputs.user_default.map(|b| (b, BindingSource::UserDefault))
}
pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
if let Some(b) = &inputs.project_flag {
return Some((b.clone(), ProjectSource::ProjectFlag));
}
if let Some(wt) = inputs.worktree_path {
if let Some(b) = inputs.session.subagent_projects.get(wt) {
return Some((b.clone(), ProjectSource::Subagent));
}
}
if let Some(b) = &inputs.session.active_project {
return Some((b.clone(), ProjectSource::SessionActive));
}
inputs
.config_default
.clone()
.map(|b| (b, ProjectSource::ConfigDefault))
}
pub async fn resolve_effective_project(
inputs: &ProjectResolveInputs<'_>,
user_default: Option<ProjectBinding>,
git_url: Option<&str>,
client: &ApiClient,
) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
if let Some(hit) = effective_project(inputs) {
return Ok(Some(hit));
}
if let Some(url) = git_url {
match client.resolve_project(url).await? {
ResolveProjectOutcome::Resolved(pid) => {
eprintln!(
"warning: no explicit project set; attributing to the project deduced from this repo ({pid}). Set one with `tracevault project switch <name>` or --project."
);
return Ok(Some((
ProjectBinding {
project_id: pid.to_string(),
project_name: String::new(), updated_at: String::new(),
},
ProjectSource::Deduced,
)));
}
ResolveProjectOutcome::Ambiguous => {
return Err(
"this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
.to_string()
.into(),
);
}
ResolveProjectOutcome::None => { }
}
}
Ok(user_default.map(|b| (b, ProjectSource::UserDefault)))
}
pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
Some(RepoBinding {
repo_id: config.repo_id.clone()?,
git_url: None,
remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
codebase_name: config.codebase_name.clone(),
updated_at: String::new(),
})
}
#[cfg(test)]
mod tests {
use super::*;
use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
use std::collections::HashMap;
use std::io::{BufRead, BufReader, Write};
use std::net::{SocketAddr, TcpListener};
use std::thread;
#[test]
fn repo_basename_bare_name() {
assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
}
#[test]
fn repo_basename_nested_path() {
assert_eq!(
repo_basename("/home/user/code/myrepo"),
Some("myrepo".to_string())
);
}
#[test]
fn repo_basename_trailing_slash() {
assert_eq!(
repo_basename("/home/user/code/myrepo/"),
Some("myrepo".to_string())
);
}
#[test]
fn repo_basename_dot_git_suffix_directory() {
assert_eq!(
repo_basename("/srv/repos/myrepo.git"),
Some("myrepo.git".to_string())
);
}
#[test]
fn repo_basename_root_has_no_basename() {
assert_eq!(repo_basename("/"), None);
}
fn spawn_once(
status: &'static str,
body: &'static str,
) -> (SocketAddr, thread::JoinHandle<()>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let response = http_200(status, body);
let handle = 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();
}
});
(addr, handle)
}
fn http_200(status: &str, body: &str) -> String {
format!(
"HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
status,
body.len(),
body
)
}
#[tokio::test]
async fn deduction_beats_user_default() {
let (addr, _h) = spawn_once(
"200 OK",
"{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
);
let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
let ud = ProjectBinding {
project_id: "user".into(),
project_name: "u".into(),
updated_at: "".into(),
};
let inputs = ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: None,
};
let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
.await
.unwrap()
.unwrap();
assert_eq!(src, ProjectSource::Deduced);
assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
}
#[tokio::test]
async fn ambiguous_deduction_errors_when_no_higher_rung() {
let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
let inputs = ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: None,
};
let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
.await
.unwrap_err();
assert!(err.to_string().to_lowercase().contains("--project"));
}
#[tokio::test]
async fn user_default_used_when_deduction_404() {
let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
let ud = ProjectBinding {
project_id: "user".into(),
project_name: "u".into(),
updated_at: "".into(),
};
let inputs = ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: None,
};
let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
.await
.unwrap()
.unwrap();
assert_eq!(src, ProjectSource::UserDefault);
assert_eq!(b.project_id, "user");
}
#[tokio::test]
async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
let (addr, _h) = spawn_once("404 Not Found", "");
let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
let ud = ProjectBinding {
project_id: "user".into(),
project_name: "u".into(),
updated_at: "".into(),
};
let inputs = ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: None,
};
let err = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
.await
.expect_err("a bare 404 must not silently fall through to the user default");
assert!(err.to_string().to_lowercase().contains("version mismatch"));
}
#[tokio::test]
async fn local_rung_skips_server_call() {
let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
let cfg = ProjectBinding {
project_id: "cfg".into(),
project_name: "c".into(),
updated_at: "".into(),
};
let inputs = ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: Some(cfg),
};
let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
.await
.unwrap()
.unwrap();
assert_eq!(src, ProjectSource::ConfigDefault);
}
fn binding(id: &str) -> RepoBinding {
RepoBinding {
repo_id: id.into(),
git_url: None,
remote_id: None,
codebase_name: None,
updated_at: "t".into(),
}
}
#[test]
fn effective_binding_precedence() {
let session = SessionState {
active: Some(binding("session")),
subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
..Default::default()
};
let (b, source) = effective_binding(ResolveInputs {
repo_flag: Some(binding("flag")),
session: &session,
worktree_path: Some("/wt/a"),
bound: Some(binding("bound")),
user_default: Some(binding("userdef")),
})
.unwrap();
assert_eq!(b.repo_id, "flag");
assert_eq!(source, BindingSource::RepoFlag);
let (b, source) = effective_binding(ResolveInputs {
repo_flag: None,
session: &session,
worktree_path: Some("/wt/a"),
bound: Some(binding("bound")),
user_default: Some(binding("userdef")),
})
.unwrap();
assert_eq!(b.repo_id, "subagent");
assert_eq!(source, BindingSource::Subagent);
let (b, source) = effective_binding(ResolveInputs {
repo_flag: None,
session: &session,
worktree_path: Some("/wt/other"),
bound: Some(binding("bound")),
user_default: Some(binding("userdef")),
})
.unwrap();
assert_eq!(b.repo_id, "session");
assert_eq!(source, BindingSource::SessionActive);
let empty = SessionState::default();
let (b, source) = effective_binding(ResolveInputs {
repo_flag: None,
session: &empty,
worktree_path: None,
bound: Some(binding("bound")),
user_default: Some(binding("userdef")),
})
.unwrap();
assert_eq!(b.repo_id, "bound");
assert_eq!(source, BindingSource::Bound);
let (b, source) = effective_binding(ResolveInputs {
repo_flag: None,
session: &empty,
worktree_path: None,
bound: None,
user_default: Some(binding("userdef")),
})
.unwrap();
assert_eq!(b.repo_id, "userdef");
assert_eq!(source, BindingSource::UserDefault);
let got = effective_binding(ResolveInputs {
repo_flag: None,
session: &empty,
worktree_path: None,
bound: None,
user_default: None,
});
assert!(got.is_none());
}
#[test]
fn binding_source_display_labels() {
assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
assert_eq!(
BindingSource::Subagent.to_string(),
"subagent worktree override"
);
assert_eq!(
BindingSource::SessionActive.to_string(),
"session (repo switch)"
);
assert_eq!(
BindingSource::Bound.to_string(),
"bound .tracevault/config.toml"
);
assert_eq!(
BindingSource::UserDefault.to_string(),
"user default (repo switch --user)"
);
}
#[test]
fn effective_project_precedence_local_rungs() {
let pb = |n: &str| ProjectBinding {
project_id: n.into(),
project_name: n.into(),
updated_at: "".into(),
};
let mut subagent_projects = HashMap::new();
subagent_projects.insert("/wt".into(), pb("subagent"));
let session = SessionState {
active_project: Some(pb("session")),
subagent_projects,
..Default::default()
};
let got = effective_project(&ProjectResolveInputs {
project_flag: Some(pb("flag")),
session: &session,
worktree_path: Some("/wt"),
config_default: Some(pb("cfg")),
})
.unwrap();
assert_eq!(got.0.project_id, "flag");
assert_eq!(got.1, ProjectSource::ProjectFlag);
let got = effective_project(&ProjectResolveInputs {
project_flag: None,
session: &session,
worktree_path: Some("/wt"),
config_default: Some(pb("cfg")),
})
.unwrap();
assert_eq!(got.1, ProjectSource::Subagent);
assert_eq!(got.0.project_id, "subagent");
let got = effective_project(&ProjectResolveInputs {
project_flag: None,
session: &session,
worktree_path: Some("/other"),
config_default: Some(pb("cfg")),
})
.unwrap();
assert_eq!(got.1, ProjectSource::SessionActive);
let got = effective_project(&ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: Some(pb("cfg")),
})
.unwrap();
assert_eq!(got.1, ProjectSource::ConfigDefault);
assert!(effective_project(&ProjectResolveInputs {
project_flag: None,
session: &SessionState::default(),
worktree_path: None,
config_default: None,
})
.is_none());
}
#[test]
fn binding_from_config_carries_remote_id_and_codebase_name() {
let uuid = uuid::Uuid::new_v4();
let config = crate::config::TracevaultConfig {
repo_id: Some("repo-1".into()),
remote_id: Some(uuid.to_string()),
codebase_name: Some("acme/foo".into()),
..Default::default()
};
let binding = binding_from_config(&config).expect("repo_id present");
assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
assert_eq!(binding.remote_id, Some(uuid));
}
#[test]
fn codebase_line_formats_name_and_status() {
let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
assert_eq!(line, "codebase: acme/foo (ready)");
let line = codebase_line(None, "github.com/acme/foo", "pending");
assert_eq!(line, "codebase: github.com/acme/foo (pending)");
}
#[test]
fn pick_status_line_detail_wins_over_resolved_and_cached() {
assert_eq!(
pick_status_line(
Some("codebase: a (ready)".to_string()),
Some("codebase: b (pending)".to_string()),
Some("c"),
),
Some("codebase: a (ready)".to_string())
);
}
#[test]
fn pick_status_line_resolved_wins_over_cached() {
assert_eq!(
pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
Some("codebase: b (pending)".to_string())
);
}
#[test]
fn pick_status_line_cached_only_is_name_only() {
assert_eq!(
pick_status_line(None, None, Some("c")),
Some("codebase: c".to_string())
);
}
#[test]
fn pick_status_line_none_when_nothing_available() {
assert_eq!(pick_status_line(None, None, None), None);
}
#[tokio::test]
async fn resolve_repo_by_name_ok_when_name_matches() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let repo_name = git_repo_name(tmp.path());
let body =
format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
let repo = resolve_repo_by_name(&client, tmp.path())
.await
.expect("expected a match");
assert_eq!(repo.name, repo_name);
}
#[tokio::test]
async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let (addr, _h) = spawn_once(
"200 OK",
r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
);
let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
match resolve_repo_by_name(&client, tmp.path()).await {
Err(ResolveRepoByNameError::NotFound { .. }) => {}
other => panic!(
"expected NotFound, got a different outcome: {}",
other.is_ok()
),
}
}
#[tokio::test]
async fn resolve_repo_by_name_list_failed_on_non_2xx() {
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let (addr, _h) = spawn_once("500 Internal Server Error", "");
let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
match resolve_repo_by_name(&client, tmp.path()).await {
Err(ResolveRepoByNameError::ListFailed(e)) => {
assert!(e.to_string().contains("500"), "got: {e}");
}
other => panic!(
"expected ListFailed, got a different outcome: {}",
other.is_ok()
),
}
}
}