Skip to main content

tracevault_cli/
resolution.rs

1//! Detached/workspace-mode repo resolution: turn a filesystem path into a
2//! `RepoBinding` (via the path's git remote + the server), and pick the
3//! effective binding for an event/command from the precedence chain
4//! (`--path` flag → subagent worktree override → session active → bound
5//! `.tracevault/config.toml`). See design §2/§3/§4.
6
7use std::path::Path;
8
9use crate::api_client::ApiClient;
10use crate::session_state::{RepoBinding, SessionState};
11
12/// Pure precedence for the org slug: first non-`None` of env, credentials,
13/// bound config. Callers pass `None` for an env value that was empty.
14pub 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
22/// Resolve the org slug for `project_root`: `TRACEVAULT_ORG_SLUG` (non-empty)
23/// → `credentials.json` `org_slug` → bound `config.toml` `org_slug`.
24pub 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
33/// Pick the org slug from the credential's memberships when none is
34/// configured locally. The slugs are de-duplicated first (a credential can
35/// have more than one membership row for the same org, e.g. multiple roles),
36/// then: exactly one distinct org → that slug; zero or many → an error telling
37/// the user to set `TRACEVAULT_ORG_SLUG`. The empty case is not only "no
38/// memberships": `/me/orgs` is also empty for an org-scoped API key (which has
39/// no user), so the message names that case explicitly. Sorting makes the
40/// multi-org message deterministic regardless of server ordering.
41pub 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
59/// `git -C <path> remote get-url origin`, trimmed. `None` if git fails or there
60/// is no origin remote.
61fn 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
79/// Resolve a filesystem path to a registered-repo binding: read its origin
80/// remote URL and ask the server. `Ok(None)` when the path has no remote or
81/// the server has no matching repo (pre-registered-only).
82pub 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
101/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
102/// are resolved by the caller (the `--path` override and the bound
103/// `config.toml`, respectively); `session`/`worktree_path` come from the
104/// per-session state.
105pub 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    /// Lowest-precedence, session-independent default (from `repo switch --user`
111    /// / a no-session switch). Applies when nothing more specific resolves.
112    pub user_default: Option<RepoBinding>,
113}
114
115/// Which precedence tier produced the [`effective_binding`] result.
116#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum BindingSource {
118    /// A `--path <path>` flag override (on `repo status`).
119    RepoFlag,
120    /// A subagent's per-worktree override.
121    Subagent,
122    /// The session's session-level active binding.
123    SessionActive,
124    /// A pinned `.tracevault/config.toml` (bound mode).
125    Bound,
126    /// A session-independent user-level default (`repo switch --user`).
127    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
143/// The binding that applies, and which tier produced it: `--path` flag →
144/// subagent worktree override → session active → bound config → user
145/// default → none.
146pub 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
164/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
165/// both org_slug and repo_id. Pure — caller supplies the already-loaded config.
166pub 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        // 1. repo_flag wins over everything.
199        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        // 2. subagent override wins over session active + bound + user default.
211        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        // 3. session active wins over bound + user default.
223        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        // 4. bound wins over user default.
235        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        // 5. user default is used when nothing more specific resolves.
248        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        // 6. nothing at all → None.
260        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        // empty env string is treated as unset by the caller (org_slug_for),
311        // so org_slug_precedence only ever sees None or non-empty.
312    }
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        // One org with two membership rows must derive, not be rejected as multi-org.
344        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        // Message must not depend on server ordering, and repeats collapse.
353        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}