1use std::path::Path;
8
9use crate::api_client::ApiClient;
10use crate::session_state::{RepoBinding, SessionState};
11
12pub fn org_slug_precedence(
15 env: Option<String>,
16 creds: Option<String>,
17 bound: Option<String>,
18) -> Option<String> {
19 env.or(creds).or(bound)
20}
21
22pub fn org_slug_for(project_root: &Path) -> Option<String> {
25 let env = std::env::var("TRACEVAULT_ORG_SLUG")
26 .ok()
27 .filter(|s| !s.is_empty());
28 let creds = crate::credentials::Credentials::load().and_then(|c| c.org_slug);
29 let bound = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.org_slug);
30 org_slug_precedence(env, creds, bound)
31}
32
33fn git_remote_url(path: &Path) -> Option<String> {
36 let out = std::process::Command::new("git")
37 .arg("-C")
38 .arg(path)
39 .args(["remote", "get-url", "origin"])
40 .output()
41 .ok()?;
42 if !out.status.success() {
43 return None;
44 }
45 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
46 if url.is_empty() {
47 None
48 } else {
49 Some(url)
50 }
51}
52
53pub async fn resolve_path_to_binding(
57 path: &Path,
58 org_slug: &str,
59 client: &ApiClient,
60) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
61 let Some(git_url) = git_remote_url(path) else {
62 return Ok(None);
63 };
64 match client.resolve_repo(org_slug, &git_url).await? {
65 Some(repo_id) => Ok(Some(RepoBinding {
66 org_slug: org_slug.to_string(),
67 repo_id: repo_id.to_string(),
68 git_url: Some(git_url),
69 updated_at: chrono::Utc::now().to_rfc3339(),
70 })),
71 None => Ok(None),
72 }
73}
74
75pub struct ResolveInputs<'a> {
80 pub repo_flag: Option<RepoBinding>,
81 pub session: &'a SessionState,
82 pub worktree_path: Option<&'a str>,
83 pub bound: Option<RepoBinding>,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum BindingSource {
89 RepoFlag,
91 Subagent,
93 SessionActive,
95 Bound,
97}
98
99impl std::fmt::Display for BindingSource {
100 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 let label = match self {
102 BindingSource::RepoFlag => "--path override",
103 BindingSource::Subagent => "subagent worktree override",
104 BindingSource::SessionActive => "session (repo switch)",
105 BindingSource::Bound => "bound .tracevault/config.toml",
106 };
107 f.write_str(label)
108 }
109}
110
111pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
114 if let Some(b) = inputs.repo_flag {
115 return Some((b, BindingSource::RepoFlag));
116 }
117 if let Some(wt) = inputs.worktree_path {
118 if let Some(b) = inputs.session.subagents.get(wt) {
119 return Some((b.clone(), BindingSource::Subagent));
120 }
121 }
122 if let Some(b) = &inputs.session.active {
123 return Some((b.clone(), BindingSource::SessionActive));
124 }
125 inputs.bound.map(|b| (b, BindingSource::Bound))
126}
127
128pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
131 Some(RepoBinding {
132 org_slug: config.org_slug.clone()?,
133 repo_id: config.repo_id.clone()?,
134 git_url: None,
135 updated_at: String::new(),
136 })
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142 use crate::session_state::{RepoBinding, SessionState};
143 use std::collections::HashMap;
144
145 fn binding(id: &str) -> RepoBinding {
146 RepoBinding {
147 org_slug: "org".into(),
148 repo_id: id.into(),
149 git_url: None,
150 updated_at: "t".into(),
151 }
152 }
153
154 #[test]
155 fn effective_binding_precedence() {
156 let session = SessionState {
157 active: Some(binding("session")),
158 subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
159 ..Default::default()
160 };
161
162 let (b, source) = effective_binding(ResolveInputs {
164 repo_flag: Some(binding("flag")),
165 session: &session,
166 worktree_path: Some("/wt/a"),
167 bound: Some(binding("bound")),
168 })
169 .unwrap();
170 assert_eq!(b.repo_id, "flag");
171 assert_eq!(source, BindingSource::RepoFlag);
172
173 let (b, source) = effective_binding(ResolveInputs {
175 repo_flag: None,
176 session: &session,
177 worktree_path: Some("/wt/a"),
178 bound: Some(binding("bound")),
179 })
180 .unwrap();
181 assert_eq!(b.repo_id, "subagent");
182 assert_eq!(source, BindingSource::Subagent);
183
184 let (b, source) = effective_binding(ResolveInputs {
186 repo_flag: None,
187 session: &session,
188 worktree_path: Some("/wt/other"),
189 bound: Some(binding("bound")),
190 })
191 .unwrap();
192 assert_eq!(b.repo_id, "session");
193 assert_eq!(source, BindingSource::SessionActive);
194
195 let empty = SessionState::default();
197 let (b, source) = effective_binding(ResolveInputs {
198 repo_flag: None,
199 session: &empty,
200 worktree_path: None,
201 bound: Some(binding("bound")),
202 })
203 .unwrap();
204 assert_eq!(b.repo_id, "bound");
205 assert_eq!(source, BindingSource::Bound);
206
207 let got = effective_binding(ResolveInputs {
209 repo_flag: None,
210 session: &empty,
211 worktree_path: None,
212 bound: None,
213 });
214 assert!(got.is_none());
215 }
216
217 #[test]
218 fn binding_source_display_labels() {
219 assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
220 assert_eq!(
221 BindingSource::Subagent.to_string(),
222 "subagent worktree override"
223 );
224 assert_eq!(
225 BindingSource::SessionActive.to_string(),
226 "session (repo switch)"
227 );
228 assert_eq!(
229 BindingSource::Bound.to_string(),
230 "bound .tracevault/config.toml"
231 );
232 }
233
234 #[test]
235 fn org_slug_precedence_order() {
236 assert_eq!(
237 org_slug_precedence(
238 Some("envorg".into()),
239 Some("creds".into()),
240 Some("bound".into())
241 ),
242 Some("envorg".into())
243 );
244 assert_eq!(
245 org_slug_precedence(None, Some("creds".into()), Some("bound".into())),
246 Some("creds".into())
247 );
248 assert_eq!(
249 org_slug_precedence(None, None, Some("bound".into())),
250 Some("bound".into())
251 );
252 assert_eq!(org_slug_precedence(None, None, None), None);
253 }
256}