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
33pub fn org_slug_from_slugs(slugs: &[String]) -> Result<String, String> {
42 let mut unique: Vec<&str> = slugs.iter().map(String::as_str).collect();
43 unique.sort_unstable();
44 unique.dedup();
45 match unique.as_slice() {
46 [] => Err(
47 "could not derive an org from this credential: it has no org membership \
48 (org-scoped API keys are not supported here); set TRACEVAULT_ORG_SLUG"
49 .to_string(),
50 ),
51 [one] => Ok((*one).to_string()),
52 many => Err(format!(
53 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: {}",
54 many.join(", ")
55 )),
56 }
57}
58
59fn git_remote_url(path: &Path) -> Option<String> {
62 let out = std::process::Command::new("git")
63 .arg("-C")
64 .arg(path)
65 .args(["remote", "get-url", "origin"])
66 .output()
67 .ok()?;
68 if !out.status.success() {
69 return None;
70 }
71 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
72 if url.is_empty() {
73 None
74 } else {
75 Some(url)
76 }
77}
78
79pub async fn resolve_path_to_binding(
83 path: &Path,
84 org_slug: &str,
85 client: &ApiClient,
86) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
87 let Some(git_url) = git_remote_url(path) else {
88 return Ok(None);
89 };
90 match client.resolve_repo(org_slug, &git_url).await? {
91 Some(repo_id) => Ok(Some(RepoBinding {
92 org_slug: org_slug.to_string(),
93 repo_id: repo_id.to_string(),
94 git_url: Some(git_url),
95 updated_at: chrono::Utc::now().to_rfc3339(),
96 })),
97 None => Ok(None),
98 }
99}
100
101pub struct ResolveInputs<'a> {
106 pub repo_flag: Option<RepoBinding>,
107 pub session: &'a SessionState,
108 pub worktree_path: Option<&'a str>,
109 pub bound: Option<RepoBinding>,
110 pub user_default: Option<RepoBinding>,
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum BindingSource {
118 RepoFlag,
120 Subagent,
122 SessionActive,
124 Bound,
126 UserDefault,
128}
129
130impl std::fmt::Display for BindingSource {
131 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132 let label = match self {
133 BindingSource::RepoFlag => "--path override",
134 BindingSource::Subagent => "subagent worktree override",
135 BindingSource::SessionActive => "session (repo switch)",
136 BindingSource::Bound => "bound .tracevault/config.toml",
137 BindingSource::UserDefault => "user default (repo switch --user)",
138 };
139 f.write_str(label)
140 }
141}
142
143pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
147 if let Some(b) = inputs.repo_flag {
148 return Some((b, BindingSource::RepoFlag));
149 }
150 if let Some(wt) = inputs.worktree_path {
151 if let Some(b) = inputs.session.subagents.get(wt) {
152 return Some((b.clone(), BindingSource::Subagent));
153 }
154 }
155 if let Some(b) = &inputs.session.active {
156 return Some((b.clone(), BindingSource::SessionActive));
157 }
158 if let Some(b) = inputs.bound {
159 return Some((b, BindingSource::Bound));
160 }
161 inputs.user_default.map(|b| (b, BindingSource::UserDefault))
162}
163
164pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
167 Some(RepoBinding {
168 org_slug: config.org_slug.clone()?,
169 repo_id: config.repo_id.clone()?,
170 git_url: None,
171 updated_at: String::new(),
172 })
173}
174
175#[cfg(test)]
176mod tests {
177 use super::*;
178 use crate::session_state::{RepoBinding, SessionState};
179 use std::collections::HashMap;
180
181 fn binding(id: &str) -> RepoBinding {
182 RepoBinding {
183 org_slug: "org".into(),
184 repo_id: id.into(),
185 git_url: None,
186 updated_at: "t".into(),
187 }
188 }
189
190 #[test]
191 fn effective_binding_precedence() {
192 let session = SessionState {
193 active: Some(binding("session")),
194 subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
195 ..Default::default()
196 };
197
198 let (b, source) = effective_binding(ResolveInputs {
200 repo_flag: Some(binding("flag")),
201 session: &session,
202 worktree_path: Some("/wt/a"),
203 bound: Some(binding("bound")),
204 user_default: Some(binding("userdef")),
205 })
206 .unwrap();
207 assert_eq!(b.repo_id, "flag");
208 assert_eq!(source, BindingSource::RepoFlag);
209
210 let (b, source) = effective_binding(ResolveInputs {
212 repo_flag: None,
213 session: &session,
214 worktree_path: Some("/wt/a"),
215 bound: Some(binding("bound")),
216 user_default: Some(binding("userdef")),
217 })
218 .unwrap();
219 assert_eq!(b.repo_id, "subagent");
220 assert_eq!(source, BindingSource::Subagent);
221
222 let (b, source) = effective_binding(ResolveInputs {
224 repo_flag: None,
225 session: &session,
226 worktree_path: Some("/wt/other"),
227 bound: Some(binding("bound")),
228 user_default: Some(binding("userdef")),
229 })
230 .unwrap();
231 assert_eq!(b.repo_id, "session");
232 assert_eq!(source, BindingSource::SessionActive);
233
234 let empty = SessionState::default();
236 let (b, source) = effective_binding(ResolveInputs {
237 repo_flag: None,
238 session: &empty,
239 worktree_path: None,
240 bound: Some(binding("bound")),
241 user_default: Some(binding("userdef")),
242 })
243 .unwrap();
244 assert_eq!(b.repo_id, "bound");
245 assert_eq!(source, BindingSource::Bound);
246
247 let (b, source) = effective_binding(ResolveInputs {
249 repo_flag: None,
250 session: &empty,
251 worktree_path: None,
252 bound: None,
253 user_default: Some(binding("userdef")),
254 })
255 .unwrap();
256 assert_eq!(b.repo_id, "userdef");
257 assert_eq!(source, BindingSource::UserDefault);
258
259 let got = effective_binding(ResolveInputs {
261 repo_flag: None,
262 session: &empty,
263 worktree_path: None,
264 bound: None,
265 user_default: None,
266 });
267 assert!(got.is_none());
268 }
269
270 #[test]
271 fn binding_source_display_labels() {
272 assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
273 assert_eq!(
274 BindingSource::Subagent.to_string(),
275 "subagent worktree override"
276 );
277 assert_eq!(
278 BindingSource::SessionActive.to_string(),
279 "session (repo switch)"
280 );
281 assert_eq!(
282 BindingSource::Bound.to_string(),
283 "bound .tracevault/config.toml"
284 );
285 assert_eq!(
286 BindingSource::UserDefault.to_string(),
287 "user default (repo switch --user)"
288 );
289 }
290
291 #[test]
292 fn org_slug_precedence_order() {
293 assert_eq!(
294 org_slug_precedence(
295 Some("envorg".into()),
296 Some("creds".into()),
297 Some("bound".into())
298 ),
299 Some("envorg".into())
300 );
301 assert_eq!(
302 org_slug_precedence(None, Some("creds".into()), Some("bound".into())),
303 Some("creds".into())
304 );
305 assert_eq!(
306 org_slug_precedence(None, None, Some("bound".into())),
307 Some("bound".into())
308 );
309 assert_eq!(org_slug_precedence(None, None, None), None);
310 }
313
314 #[test]
315 fn org_slug_from_slugs_single() {
316 assert_eq!(
317 org_slug_from_slugs(&["acme".to_string()]),
318 Ok("acme".to_string())
319 );
320 }
321
322 #[test]
323 fn org_slug_from_slugs_none_errors() {
324 let err = org_slug_from_slugs(&[]).unwrap_err();
325 assert_eq!(
326 err,
327 "could not derive an org from this credential: it has no org membership \
328 (org-scoped API keys are not supported here); set TRACEVAULT_ORG_SLUG"
329 );
330 }
331
332 #[test]
333 fn org_slug_from_slugs_multiple_lists_them() {
334 let err = org_slug_from_slugs(&["acme".to_string(), "globex".to_string()]).unwrap_err();
335 assert_eq!(
336 err,
337 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: acme, globex"
338 );
339 }
340
341 #[test]
342 fn org_slug_from_slugs_single_org_duplicated_is_not_multi() {
343 assert_eq!(
345 org_slug_from_slugs(&["acme".to_string(), "acme".to_string()]),
346 Ok("acme".to_string())
347 );
348 }
349
350 #[test]
351 fn org_slug_from_slugs_multiple_sorted_and_deduped() {
352 let err = org_slug_from_slugs(&[
354 "globex".to_string(),
355 "acme".to_string(),
356 "globex".to_string(),
357 ])
358 .unwrap_err();
359 assert_eq!(
360 err,
361 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: acme, globex"
362 );
363 }
364}