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 pub user_default: Option<RepoBinding>,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum BindingSource {
92 RepoFlag,
94 Subagent,
96 SessionActive,
98 Bound,
100 UserDefault,
102}
103
104impl std::fmt::Display for BindingSource {
105 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
106 let label = match self {
107 BindingSource::RepoFlag => "--path override",
108 BindingSource::Subagent => "subagent worktree override",
109 BindingSource::SessionActive => "session (repo switch)",
110 BindingSource::Bound => "bound .tracevault/config.toml",
111 BindingSource::UserDefault => "user default (repo switch --user)",
112 };
113 f.write_str(label)
114 }
115}
116
117pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
121 if let Some(b) = inputs.repo_flag {
122 return Some((b, BindingSource::RepoFlag));
123 }
124 if let Some(wt) = inputs.worktree_path {
125 if let Some(b) = inputs.session.subagents.get(wt) {
126 return Some((b.clone(), BindingSource::Subagent));
127 }
128 }
129 if let Some(b) = &inputs.session.active {
130 return Some((b.clone(), BindingSource::SessionActive));
131 }
132 if let Some(b) = inputs.bound {
133 return Some((b, BindingSource::Bound));
134 }
135 inputs.user_default.map(|b| (b, BindingSource::UserDefault))
136}
137
138pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
141 Some(RepoBinding {
142 org_slug: config.org_slug.clone()?,
143 repo_id: config.repo_id.clone()?,
144 git_url: None,
145 updated_at: String::new(),
146 })
147}
148
149#[cfg(test)]
150mod tests {
151 use super::*;
152 use crate::session_state::{RepoBinding, SessionState};
153 use std::collections::HashMap;
154
155 fn binding(id: &str) -> RepoBinding {
156 RepoBinding {
157 org_slug: "org".into(),
158 repo_id: id.into(),
159 git_url: None,
160 updated_at: "t".into(),
161 }
162 }
163
164 #[test]
165 fn effective_binding_precedence() {
166 let session = SessionState {
167 active: Some(binding("session")),
168 subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
169 ..Default::default()
170 };
171
172 let (b, source) = effective_binding(ResolveInputs {
174 repo_flag: Some(binding("flag")),
175 session: &session,
176 worktree_path: Some("/wt/a"),
177 bound: Some(binding("bound")),
178 user_default: Some(binding("userdef")),
179 })
180 .unwrap();
181 assert_eq!(b.repo_id, "flag");
182 assert_eq!(source, BindingSource::RepoFlag);
183
184 let (b, source) = effective_binding(ResolveInputs {
186 repo_flag: None,
187 session: &session,
188 worktree_path: Some("/wt/a"),
189 bound: Some(binding("bound")),
190 user_default: Some(binding("userdef")),
191 })
192 .unwrap();
193 assert_eq!(b.repo_id, "subagent");
194 assert_eq!(source, BindingSource::Subagent);
195
196 let (b, source) = effective_binding(ResolveInputs {
198 repo_flag: None,
199 session: &session,
200 worktree_path: Some("/wt/other"),
201 bound: Some(binding("bound")),
202 user_default: Some(binding("userdef")),
203 })
204 .unwrap();
205 assert_eq!(b.repo_id, "session");
206 assert_eq!(source, BindingSource::SessionActive);
207
208 let empty = SessionState::default();
210 let (b, source) = effective_binding(ResolveInputs {
211 repo_flag: None,
212 session: &empty,
213 worktree_path: None,
214 bound: Some(binding("bound")),
215 user_default: Some(binding("userdef")),
216 })
217 .unwrap();
218 assert_eq!(b.repo_id, "bound");
219 assert_eq!(source, BindingSource::Bound);
220
221 let (b, source) = effective_binding(ResolveInputs {
223 repo_flag: None,
224 session: &empty,
225 worktree_path: None,
226 bound: None,
227 user_default: Some(binding("userdef")),
228 })
229 .unwrap();
230 assert_eq!(b.repo_id, "userdef");
231 assert_eq!(source, BindingSource::UserDefault);
232
233 let got = effective_binding(ResolveInputs {
235 repo_flag: None,
236 session: &empty,
237 worktree_path: None,
238 bound: None,
239 user_default: None,
240 });
241 assert!(got.is_none());
242 }
243
244 #[test]
245 fn binding_source_display_labels() {
246 assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
247 assert_eq!(
248 BindingSource::Subagent.to_string(),
249 "subagent worktree override"
250 );
251 assert_eq!(
252 BindingSource::SessionActive.to_string(),
253 "session (repo switch)"
254 );
255 assert_eq!(
256 BindingSource::Bound.to_string(),
257 "bound .tracevault/config.toml"
258 );
259 assert_eq!(
260 BindingSource::UserDefault.to_string(),
261 "user default (repo switch --user)"
262 );
263 }
264
265 #[test]
266 fn org_slug_precedence_order() {
267 assert_eq!(
268 org_slug_precedence(
269 Some("envorg".into()),
270 Some("creds".into()),
271 Some("bound".into())
272 ),
273 Some("envorg".into())
274 );
275 assert_eq!(
276 org_slug_precedence(None, Some("creds".into()), Some("bound".into())),
277 Some("creds".into())
278 );
279 assert_eq!(
280 org_slug_precedence(None, None, Some("bound".into())),
281 Some("bound".into())
282 );
283 assert_eq!(org_slug_precedence(None, None, None), None);
284 }
287}