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    /// Lowest-precedence, session-independent default (from `repo switch --user`
85    /// / a no-session switch). Applies when nothing more specific resolves.
86    pub user_default: Option<RepoBinding>,
87}
88
89/// Which precedence tier produced the [`effective_binding`] result.
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum BindingSource {
92    /// A `--path <path>` flag override (on `repo status`).
93    RepoFlag,
94    /// A subagent's per-worktree override.
95    Subagent,
96    /// The session's session-level active binding.
97    SessionActive,
98    /// A pinned `.tracevault/config.toml` (bound mode).
99    Bound,
100    /// A session-independent user-level default (`repo switch --user`).
101    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
117/// The binding that applies, and which tier produced it: `--path` flag →
118/// subagent worktree override → session active → bound config → user
119/// default → none.
120pub 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
138/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
139/// both org_slug and repo_id. Pure — caller supplies the already-loaded config.
140pub 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        // 1. repo_flag wins over everything.
173        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        // 2. subagent override wins over session active + bound + user default.
185        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        // 3. session active wins over bound + user default.
197        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        // 4. bound wins over user default.
209        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        // 5. user default is used when nothing more specific resolves.
222        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        // 6. nothing at all → None.
234        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        // empty env string is treated as unset by the caller (org_slug_for),
285        // so org_slug_precedence only ever sees None or non-empty.
286    }
287}