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/// `git -C <path> remote get-url origin`, trimmed. `None` if git fails or there
34/// is no origin remote.
35fn 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
53/// Resolve a filesystem path to a registered-repo binding: read its origin
54/// remote URL and ask the server. `Ok(None)` when the path has no remote or
55/// the server has no matching repo (pre-registered-only).
56pub 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
75/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
76/// are resolved by the caller (the `--path` override and the bound
77/// `config.toml`, respectively); `session`/`worktree_path` come from the
78/// per-session state.
79pub 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/// Which precedence tier produced the [`effective_binding`] result.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum BindingSource {
89    /// A `--path <path>` flag override (on `repo status`).
90    RepoFlag,
91    /// A subagent's per-worktree override.
92    Subagent,
93    /// The session's session-level active binding.
94    SessionActive,
95    /// A pinned `.tracevault/config.toml` (bound mode).
96    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
111/// The binding that applies, and which tier produced it: `--path` flag →
112/// subagent worktree override → session active → bound config → none.
113pub 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
128/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
129/// both org_slug and repo_id. Pure — caller supplies the already-loaded config.
130pub 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        // 1. repo_flag wins over everything.
163        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        // 2. subagent override (for the worktree) wins over session active + bound.
174        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        // 3. session active wins over bound when no subagent override matches.
185        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        // 4. bound is last resort.
196        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        // 5. nothing → None.
208        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        // empty env string is treated as unset by the caller (org_slug_for),
254        // so org_slug_precedence only ever sees None or non-empty.
255    }
256}