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;
8use std::process::Command;
9
10use crate::api_client::{ApiClient, RepoListItem, ResolveProjectOutcome};
11use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
12
13/// `git -C <path> remote get-url origin`, trimmed. `None` if git fails or there
14/// is no origin remote. Shared by every caller that needs a checkout's origin
15/// remote URL (`init`, `sync`, `status`, and this module's own
16/// `resolve_path_to_binding`) — there is exactly one implementation.
17pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
18    let out = std::process::Command::new("git")
19        .arg("-C")
20        .arg(path)
21        .args(["remote", "get-url", "origin"])
22        .output()
23        .ok()?;
24    if !out.status.success() {
25        return None;
26    }
27    let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
28    if url.is_empty() {
29        None
30    } else {
31        Some(url)
32    }
33}
34
35/// Basename of the git repository's toplevel directory — the convention used
36/// as the server-registered repo name by `verify`/`check`/`agent-policies`/
37/// `status`/`init`/`sync`. Falls back to `"unknown"` if git fails (no repo,
38/// not a git checkout, etc.), mirroring what each of those commands' own
39/// now-removed copy of this function did.
40pub(crate) fn git_repo_name(project_root: &Path) -> String {
41    Command::new("git")
42        .args(["rev-parse", "--show-toplevel"])
43        .current_dir(project_root)
44        .output()
45        .ok()
46        .filter(|o| o.status.success())
47        .and_then(|o| repo_basename(String::from_utf8_lossy(&o.stdout).trim()))
48        .unwrap_or_else(|| "unknown".into())
49}
50
51/// The basename of a `git rev-parse --show-toplevel` path. `git` always
52/// emits forward slashes (even on Windows), but `Path::file_name` is the
53/// OS-appropriate way to take the basename — it's also tolerant of a
54/// trailing separator. `None` if the path has no basename component (e.g.
55/// root `/`). Split out from [`git_repo_name`] so the basename logic is
56/// unit-testable without shelling out to git.
57fn repo_basename(toplevel: &str) -> Option<String> {
58    Path::new(toplevel)
59        .file_name()
60        .map(|n| n.to_string_lossy().into_owned())
61}
62
63/// Either half of [`resolve_repo_by_name`]'s failure: the `list_repos` call
64/// itself failed for any reason — network/transport, or any non-2xx status
65/// (401/403/404/500/...), not only a network problem — returned raw so a
66/// caller can add its own actionable wrapping (e.g. `check`'s
67/// `connectivity_message`); or the call succeeded but no repo's name matched
68/// (so callers can phrase their own "not found" message/next-step).
69#[derive(Debug)]
70pub(crate) enum ResolveRepoByNameError {
71    ListFailed(Box<dyn std::error::Error>),
72    NotFound { repo_name: String },
73}
74
75/// Resolve the server-registered repo matching `project_root`'s git-toplevel
76/// basename: derive the name via [`git_repo_name`], call `GET /repos`, and
77/// find the matching entry. Shared via the `ListFailed`/`NotFound` split so
78/// each caller can phrase its own message for either failure.
79pub(crate) async fn resolve_repo_by_name(
80    client: &ApiClient,
81    project_root: &Path,
82) -> Result<RepoListItem, ResolveRepoByNameError> {
83    let repo_name = git_repo_name(project_root);
84    let repos = client
85        .list_repos()
86        .await
87        .map_err(ResolveRepoByNameError::ListFailed)?;
88    repos
89        .into_iter()
90        .find(|r| r.name == repo_name)
91        .ok_or(ResolveRepoByNameError::NotFound { repo_name })
92}
93
94/// Render a human line for a codebase resolved via `resolve_remote` /
95/// `get_remote_detail`: the registered name if the server has one, else the
96/// normalized URL, plus the server-side clone status. Shared by `init`
97/// (after registering) and `repo status` (live tiers) so the format has
98/// exactly one implementation.
99pub(crate) fn codebase_line(
100    name: Option<&str>,
101    normalized_url: &str,
102    clone_status: &str,
103) -> String {
104    format!(
105        "codebase: {} ({})",
106        name.unwrap_or(normalized_url),
107        clone_status
108    )
109}
110
111/// Choose the `repo status` codebase line from the available sources in
112/// priority order: live remote detail, live resolve-by-URL, cached name.
113/// The two live lines are pre-formatted (via `codebase_line`, so they carry
114/// clone status); the cached tier is name-only (no live status).
115pub(crate) fn pick_status_line(
116    detail_line: Option<String>,
117    resolved_line: Option<String>,
118    cached_name: Option<&str>,
119) -> Option<String> {
120    detail_line
121        .or(resolved_line)
122        .or_else(|| cached_name.map(|n| format!("codebase: {n}")))
123}
124
125/// Resolve a filesystem path to a registered-repo binding: read its origin
126/// remote URL and ask the server. `Ok(None)` when the path has no remote or
127/// the server has no matching codebase (pre-registered-only).
128pub async fn resolve_path_to_binding(
129    path: &Path,
130    client: &ApiClient,
131) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
132    let Some(git_url) = git_remote_url(path) else {
133        return Ok(None);
134    };
135    // Resolve the CODEBASE by normalized URL (deduped), then bind to one of its
136    // repos. Any linked repo works for ingest — every repo-keyed server read
137    // resolves codebase-wide — so the lowest-id linked repo (deterministic) is
138    // fine.
139    let Some(remote) = client.resolve_remote(&git_url).await? else {
140        return Ok(None);
141    };
142    let repos = client.get_remote_repos(remote.remote_id).await?;
143    let Some(first) = repos.into_iter().min_by_key(|r| r.id) else {
144        return Err(format!(
145            "codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
146            remote.name.as_deref().unwrap_or(&remote.normalized_url)
147        )
148        .into());
149    };
150    Ok(Some(RepoBinding {
151        repo_id: first.id.to_string(),
152        git_url: Some(git_url),
153        remote_id: Some(remote.remote_id),
154        codebase_name: remote.name,
155        updated_at: chrono::Utc::now().to_rfc3339(),
156    }))
157}
158
159/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
160/// are resolved by the caller (the `--path` override and the bound
161/// `config.toml`, respectively); `session`/`worktree_path` come from the
162/// per-session state.
163pub struct ResolveInputs<'a> {
164    pub repo_flag: Option<RepoBinding>,
165    pub session: &'a SessionState,
166    pub worktree_path: Option<&'a str>,
167    pub bound: Option<RepoBinding>,
168    /// Lowest-precedence, session-independent default (from `repo switch --user`
169    /// / a no-session switch). Applies when nothing more specific resolves.
170    pub user_default: Option<RepoBinding>,
171}
172
173/// Inputs for the effective-project precedence chain. `project_flag` and
174/// `config_default` are resolved by the caller; `session`/`worktree_path`
175/// come from the per-session state.
176pub struct ProjectResolveInputs<'a> {
177    pub project_flag: Option<ProjectBinding>,
178    pub session: &'a SessionState,
179    pub worktree_path: Option<&'a str>,
180    pub config_default: Option<ProjectBinding>,
181}
182
183/// Which precedence tier produced the [`effective_binding`] result.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum BindingSource {
186    /// A `--path <path>` flag override (on `repo status`).
187    RepoFlag,
188    /// A subagent's per-worktree override.
189    Subagent,
190    /// The session's session-level active binding.
191    SessionActive,
192    /// A pinned `.tracevault/config.toml` (bound mode).
193    Bound,
194    /// A session-independent user-level default (`repo switch --user`).
195    UserDefault,
196}
197
198impl std::fmt::Display for BindingSource {
199    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200        let label = match self {
201            BindingSource::RepoFlag => "--path override",
202            BindingSource::Subagent => "subagent worktree override",
203            BindingSource::SessionActive => "session (repo switch)",
204            BindingSource::Bound => "bound .tracevault/config.toml",
205            BindingSource::UserDefault => "user default (repo switch --user)",
206        };
207        f.write_str(label)
208    }
209}
210
211/// Which precedence tier produced the [`effective_project`] result.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum ProjectSource {
214    /// A `--project <id>` flag override.
215    ProjectFlag,
216    /// A subagent's per-worktree override.
217    Subagent,
218    /// The session's project-level active binding.
219    SessionActive,
220    /// A pinned `.tracevault/config.toml` default_project (bound mode).
221    ConfigDefault,
222    /// Repo deduction from the git remote, resolved server-side. Produced by
223    /// [`resolve_effective_project`], not [`effective_project`].
224    Deduced,
225    /// A session-independent user-level default (`project switch --user`).
226    /// Produced by [`resolve_effective_project`], not [`effective_project`].
227    UserDefault,
228}
229
230impl std::fmt::Display for ProjectSource {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        let label = match self {
233            ProjectSource::ProjectFlag => "--project override",
234            ProjectSource::Subagent => "subagent worktree override",
235            ProjectSource::SessionActive => "session (project switch)",
236            ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
237            ProjectSource::Deduced => "repo deduction",
238            ProjectSource::UserDefault => "user default (project switch --user)",
239        };
240        f.write_str(label)
241    }
242}
243
244/// The binding that applies, and which tier produced it: `--path` flag →
245/// subagent worktree override → session active → bound config → user
246/// default → none.
247pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
248    if let Some(b) = inputs.repo_flag {
249        return Some((b, BindingSource::RepoFlag));
250    }
251    if let Some(wt) = inputs.worktree_path {
252        if let Some(b) = inputs.session.subagents.get(wt) {
253            return Some((b.clone(), BindingSource::Subagent));
254        }
255    }
256    if let Some(b) = &inputs.session.active {
257        return Some((b.clone(), BindingSource::SessionActive));
258    }
259    if let Some(b) = inputs.bound {
260        return Some((b, BindingSource::Bound));
261    }
262    inputs.user_default.map(|b| (b, BindingSource::UserDefault))
263}
264
265/// The project that applies, and which tier produced it: `--project` flag →
266/// subagent worktree override → session active → config default → none.
267/// Pure; covers only the local tiers (flag → subagent → session.active_project
268/// → config_default). Server-side deduction and the user-level default are
269/// applied afterward by [`resolve_effective_project`], which calls this
270/// function first and only falls through to those tiers when it returns
271/// `None`.
272pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
273    if let Some(b) = &inputs.project_flag {
274        return Some((b.clone(), ProjectSource::ProjectFlag));
275    }
276    if let Some(wt) = inputs.worktree_path {
277        if let Some(b) = inputs.session.subagent_projects.get(wt) {
278            return Some((b.clone(), ProjectSource::Subagent));
279        }
280    }
281    if let Some(b) = &inputs.session.active_project {
282        return Some((b.clone(), ProjectSource::SessionActive));
283    }
284    inputs
285        .config_default
286        .clone()
287        .map(|b| (b, ProjectSource::ConfigDefault))
288}
289
290/// Full project-attribution precedence chain: `--project` flag → subagent
291/// override → session active → config default (all pure, via
292/// [`effective_project`]; no network call) → server-side deduction from the
293/// repo's git remote → user-level default. Deduction outranks the user-level
294/// default — this falls out of the ordering below: the user default is only
295/// consulted once deduction has returned `None`.
296///
297/// An `Ambiguous` deduction result is an error (the caller can't safely guess
298/// among several candidate projects); a `Resolved` deduction emits a warning
299/// so the user knows attribution wasn't explicit. Returns `Ok(None)` only when
300/// every tier in the chain is empty — the caller turns that into a "project
301/// required" error where appropriate.
302pub async fn resolve_effective_project(
303    inputs: &ProjectResolveInputs<'_>,
304    user_default: Option<ProjectBinding>,
305    git_url: Option<&str>,
306    client: &ApiClient,
307) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
308    // Local tiers: flag → subagent → session active → config default.
309    if let Some(hit) = effective_project(inputs) {
310        return Ok(Some(hit));
311    }
312    // Server-side deduction from the repo's git remote.
313    if let Some(url) = git_url {
314        match client.resolve_project(url).await? {
315            ResolveProjectOutcome::Resolved(pid) => {
316                eprintln!(
317                    "warning: no explicit project set; attributing to the project deduced from this repo ({pid}). Set one with `tracevault project switch <name>` or --project."
318                );
319                return Ok(Some((
320                    ProjectBinding {
321                        project_id: pid.to_string(),
322                        project_name: String::new(), // enriched for display by the caller if needed
323                        updated_at: String::new(),
324                    },
325                    ProjectSource::Deduced,
326                )));
327            }
328            ResolveProjectOutcome::Ambiguous => {
329                return Err(
330                    "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
331                        .to_string()
332                        .into(),
333                );
334            }
335            ResolveProjectOutcome::None => { /* fall through */ }
336        }
337    }
338    // User-level default (lowest tier; only consulted once deduction is empty).
339    Ok(user_default.map(|b| (b, ProjectSource::UserDefault)))
340}
341
342/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
343/// a repo_id. Pure — caller supplies the already-loaded config.
344/// Carries through the `remote_id`/`codebase_name` `init` persisted (best-effort,
345/// display-only) so bound-mode `status` can print the codebase without an extra
346/// network round-trip; `git_url` stays `None` here — bound mode has no live
347/// origin URL to hand back (that's the older `git_url` fallback's job, covering
348/// bindings that predate `codebase_name`).
349pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
350    Some(RepoBinding {
351        repo_id: config.repo_id.clone()?,
352        git_url: None,
353        remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
354        codebase_name: config.codebase_name.clone(),
355        updated_at: String::new(),
356    })
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362    use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
363    use std::collections::HashMap;
364    use std::io::{BufRead, BufReader, Write};
365    use std::net::{SocketAddr, TcpListener};
366    use std::thread;
367
368    #[test]
369    fn repo_basename_bare_name() {
370        assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
371    }
372
373    #[test]
374    fn repo_basename_nested_path() {
375        assert_eq!(
376            repo_basename("/home/user/code/myrepo"),
377            Some("myrepo".to_string())
378        );
379    }
380
381    #[test]
382    fn repo_basename_trailing_slash() {
383        // `Path::file_name` skips a trailing separator rather than treating
384        // it as an empty final component.
385        assert_eq!(
386            repo_basename("/home/user/code/myrepo/"),
387            Some("myrepo".to_string())
388        );
389    }
390
391    #[test]
392    fn repo_basename_dot_git_suffix_directory() {
393        // A checkout directory literally named `myrepo.git` (e.g. a bare
394        // clone) keeps the suffix — `git_repo_name` takes the raw basename,
395        // it does not strip `.git`.
396        assert_eq!(
397            repo_basename("/srv/repos/myrepo.git"),
398            Some("myrepo.git".to_string())
399        );
400    }
401
402    #[test]
403    fn repo_basename_root_has_no_basename() {
404        assert_eq!(repo_basename("/"), None);
405    }
406
407    /// Spawn a one-shot raw-HTTP server that returns a response built from
408    /// `status` (e.g. `"200 OK"`) and `body` to the first request it accepts.
409    /// Mirrors the `spawn_once`/`http_200` shape in `commands::repo`'s test
410    /// module (bind loopback, accept once on a background thread, write the
411    /// raw HTTP response, flush, close).
412    fn spawn_once(
413        status: &'static str,
414        body: &'static str,
415    ) -> (SocketAddr, thread::JoinHandle<()>) {
416        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
417        let addr = listener.local_addr().unwrap();
418        let response = http_200(status, body);
419        let handle = thread::spawn(move || {
420            if let Ok((stream, _)) = listener.accept() {
421                let mut reader = BufReader::new(stream);
422                let mut request_line = String::new();
423                let _ = reader.read_line(&mut request_line);
424                let mut stream = reader.into_inner();
425                let _ = stream.write_all(response.as_bytes());
426                let _ = stream.flush();
427            }
428        });
429        (addr, handle)
430    }
431
432    /// Format a raw HTTP/1.1 response with the given `status` line and a
433    /// correct `Content-Length` for a JSON `body`.
434    fn http_200(status: &str, body: &str) -> String {
435        format!(
436            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
437            status,
438            body.len(),
439            body
440        )
441    }
442
443    #[tokio::test]
444    async fn deduction_beats_user_default() {
445        // /projects/resolve -> 200 deduced; user_default present -> deduced still wins (decision 6)
446        let (addr, _h) = spawn_once(
447            "200 OK",
448            "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
449        );
450        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
451        let ud = ProjectBinding {
452            project_id: "user".into(),
453            project_name: "u".into(),
454            updated_at: "".into(),
455        };
456        let inputs = ProjectResolveInputs {
457            project_flag: None,
458            session: &SessionState::default(),
459            worktree_path: None,
460            config_default: None,
461        };
462        let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
463            .await
464            .unwrap()
465            .unwrap();
466        assert_eq!(src, ProjectSource::Deduced);
467        assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
468    }
469
470    #[tokio::test]
471    async fn ambiguous_deduction_errors_when_no_higher_rung() {
472        let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
473        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
474        let inputs = ProjectResolveInputs {
475            project_flag: None,
476            session: &SessionState::default(),
477            worktree_path: None,
478            config_default: None,
479        };
480        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
481            .await
482            .unwrap_err();
483        assert!(err.to_string().to_lowercase().contains("--project"));
484    }
485
486    #[tokio::test]
487    async fn user_default_used_when_deduction_404() {
488        // A domain 404 (server's `{"error": ...}` envelope) — the shape a
489        // real (non-skewed) server sends for "no project" — must still fall
490        // through to the user default, unlike a bare route-404.
491        let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
492        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
493        let ud = ProjectBinding {
494            project_id: "user".into(),
495            project_name: "u".into(),
496            updated_at: "".into(),
497        };
498        let inputs = ProjectResolveInputs {
499            project_flag: None,
500            session: &SessionState::default(),
501            worktree_path: None,
502            config_default: None,
503        };
504        let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
505            .await
506            .unwrap()
507            .unwrap();
508        assert_eq!(src, ProjectSource::UserDefault);
509        assert_eq!(b.project_id, "user");
510    }
511
512    #[tokio::test]
513    async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
514        // A bare 404 (no JSON error body) is axum's "no route matched"
515        // fallback, not a domain "no project" — it must propagate as an
516        // error instead of silently falling through to the user default.
517        let (addr, _h) = spawn_once("404 Not Found", "");
518        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
519        let ud = ProjectBinding {
520            project_id: "user".into(),
521            project_name: "u".into(),
522            updated_at: "".into(),
523        };
524        let inputs = ProjectResolveInputs {
525            project_flag: None,
526            session: &SessionState::default(),
527            worktree_path: None,
528            config_default: None,
529        };
530        let err = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
531            .await
532            .expect_err("a bare 404 must not silently fall through to the user default");
533        assert!(err.to_string().to_lowercase().contains("version mismatch"));
534    }
535
536    #[tokio::test]
537    async fn local_rung_skips_server_call() {
538        // no server spawned; a config_default present must resolve WITHOUT any network call
539        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
540        let cfg = ProjectBinding {
541            project_id: "cfg".into(),
542            project_name: "c".into(),
543            updated_at: "".into(),
544        };
545        let inputs = ProjectResolveInputs {
546            project_flag: None,
547            session: &SessionState::default(),
548            worktree_path: None,
549            config_default: Some(cfg),
550        };
551        let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
552            .await
553            .unwrap()
554            .unwrap();
555        assert_eq!(src, ProjectSource::ConfigDefault);
556    }
557
558    fn binding(id: &str) -> RepoBinding {
559        RepoBinding {
560            repo_id: id.into(),
561            git_url: None,
562            remote_id: None,
563            codebase_name: None,
564            updated_at: "t".into(),
565        }
566    }
567
568    #[test]
569    fn effective_binding_precedence() {
570        let session = SessionState {
571            active: Some(binding("session")),
572            subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
573            ..Default::default()
574        };
575
576        // 1. repo_flag wins over everything.
577        let (b, source) = effective_binding(ResolveInputs {
578            repo_flag: Some(binding("flag")),
579            session: &session,
580            worktree_path: Some("/wt/a"),
581            bound: Some(binding("bound")),
582            user_default: Some(binding("userdef")),
583        })
584        .unwrap();
585        assert_eq!(b.repo_id, "flag");
586        assert_eq!(source, BindingSource::RepoFlag);
587
588        // 2. subagent override wins over session active + bound + user default.
589        let (b, source) = effective_binding(ResolveInputs {
590            repo_flag: None,
591            session: &session,
592            worktree_path: Some("/wt/a"),
593            bound: Some(binding("bound")),
594            user_default: Some(binding("userdef")),
595        })
596        .unwrap();
597        assert_eq!(b.repo_id, "subagent");
598        assert_eq!(source, BindingSource::Subagent);
599
600        // 3. session active wins over bound + user default.
601        let (b, source) = effective_binding(ResolveInputs {
602            repo_flag: None,
603            session: &session,
604            worktree_path: Some("/wt/other"),
605            bound: Some(binding("bound")),
606            user_default: Some(binding("userdef")),
607        })
608        .unwrap();
609        assert_eq!(b.repo_id, "session");
610        assert_eq!(source, BindingSource::SessionActive);
611
612        // 4. bound wins over user default.
613        let empty = SessionState::default();
614        let (b, source) = effective_binding(ResolveInputs {
615            repo_flag: None,
616            session: &empty,
617            worktree_path: None,
618            bound: Some(binding("bound")),
619            user_default: Some(binding("userdef")),
620        })
621        .unwrap();
622        assert_eq!(b.repo_id, "bound");
623        assert_eq!(source, BindingSource::Bound);
624
625        // 5. user default is used when nothing more specific resolves.
626        let (b, source) = effective_binding(ResolveInputs {
627            repo_flag: None,
628            session: &empty,
629            worktree_path: None,
630            bound: None,
631            user_default: Some(binding("userdef")),
632        })
633        .unwrap();
634        assert_eq!(b.repo_id, "userdef");
635        assert_eq!(source, BindingSource::UserDefault);
636
637        // 6. nothing at all → None.
638        let got = effective_binding(ResolveInputs {
639            repo_flag: None,
640            session: &empty,
641            worktree_path: None,
642            bound: None,
643            user_default: None,
644        });
645        assert!(got.is_none());
646    }
647
648    #[test]
649    fn binding_source_display_labels() {
650        assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
651        assert_eq!(
652            BindingSource::Subagent.to_string(),
653            "subagent worktree override"
654        );
655        assert_eq!(
656            BindingSource::SessionActive.to_string(),
657            "session (repo switch)"
658        );
659        assert_eq!(
660            BindingSource::Bound.to_string(),
661            "bound .tracevault/config.toml"
662        );
663        assert_eq!(
664            BindingSource::UserDefault.to_string(),
665            "user default (repo switch --user)"
666        );
667    }
668
669    #[test]
670    fn effective_project_precedence_local_rungs() {
671        let pb = |n: &str| ProjectBinding {
672            project_id: n.into(),
673            project_name: n.into(),
674            updated_at: "".into(),
675        };
676        let mut subagent_projects = HashMap::new();
677        subagent_projects.insert("/wt".into(), pb("subagent"));
678        let session = SessionState {
679            active_project: Some(pb("session")),
680            subagent_projects,
681            ..Default::default()
682        };
683
684        // rung 1: flag wins over everything
685        let got = effective_project(&ProjectResolveInputs {
686            project_flag: Some(pb("flag")),
687            session: &session,
688            worktree_path: Some("/wt"),
689            config_default: Some(pb("cfg")),
690        })
691        .unwrap();
692        assert_eq!(got.0.project_id, "flag");
693        assert_eq!(got.1, ProjectSource::ProjectFlag);
694
695        // rung 2: subagent (worktree) beats session.active
696        let got = effective_project(&ProjectResolveInputs {
697            project_flag: None,
698            session: &session,
699            worktree_path: Some("/wt"),
700            config_default: Some(pb("cfg")),
701        })
702        .unwrap();
703        assert_eq!(got.1, ProjectSource::Subagent);
704        assert_eq!(got.0.project_id, "subagent");
705
706        // rung 3: session.active when no subagent match
707        let got = effective_project(&ProjectResolveInputs {
708            project_flag: None,
709            session: &session,
710            worktree_path: Some("/other"),
711            config_default: Some(pb("cfg")),
712        })
713        .unwrap();
714        assert_eq!(got.1, ProjectSource::SessionActive);
715
716        // rung 3b: config_default when session empty
717        let got = effective_project(&ProjectResolveInputs {
718            project_flag: None,
719            session: &SessionState::default(),
720            worktree_path: None,
721            config_default: Some(pb("cfg")),
722        })
723        .unwrap();
724        assert_eq!(got.1, ProjectSource::ConfigDefault);
725
726        // none: nothing local
727        assert!(effective_project(&ProjectResolveInputs {
728            project_flag: None,
729            session: &SessionState::default(),
730            worktree_path: None,
731            config_default: None,
732        })
733        .is_none());
734    }
735
736    #[test]
737    fn binding_from_config_carries_remote_id_and_codebase_name() {
738        let uuid = uuid::Uuid::new_v4();
739        let config = crate::config::TracevaultConfig {
740            repo_id: Some("repo-1".into()),
741            remote_id: Some(uuid.to_string()),
742            codebase_name: Some("acme/foo".into()),
743            ..Default::default()
744        };
745        let binding = binding_from_config(&config).expect("repo_id present");
746        assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
747        assert_eq!(binding.remote_id, Some(uuid));
748    }
749
750    #[test]
751    fn codebase_line_formats_name_and_status() {
752        let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
753        assert_eq!(line, "codebase: acme/foo (ready)");
754        let line = codebase_line(None, "github.com/acme/foo", "pending");
755        assert_eq!(line, "codebase: github.com/acme/foo (pending)");
756    }
757
758    #[test]
759    fn pick_status_line_detail_wins_over_resolved_and_cached() {
760        assert_eq!(
761            pick_status_line(
762                Some("codebase: a (ready)".to_string()),
763                Some("codebase: b (pending)".to_string()),
764                Some("c"),
765            ),
766            Some("codebase: a (ready)".to_string())
767        );
768    }
769
770    #[test]
771    fn pick_status_line_resolved_wins_over_cached() {
772        assert_eq!(
773            pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
774            Some("codebase: b (pending)".to_string())
775        );
776    }
777
778    #[test]
779    fn pick_status_line_cached_only_is_name_only() {
780        assert_eq!(
781            pick_status_line(None, None, Some("c")),
782            Some("codebase: c".to_string())
783        );
784    }
785
786    #[test]
787    fn pick_status_line_none_when_nothing_available() {
788        assert_eq!(pick_status_line(None, None, None), None);
789    }
790
791    #[tokio::test]
792    async fn resolve_repo_by_name_ok_when_name_matches() {
793        let tmp = tempfile::tempdir().unwrap();
794        crate::test_helpers::init_git_repo(tmp.path());
795        let repo_name = git_repo_name(tmp.path());
796        let body =
797            format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
798        let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
799        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
800
801        let repo = resolve_repo_by_name(&client, tmp.path())
802            .await
803            .expect("expected a match");
804        assert_eq!(repo.name, repo_name);
805    }
806
807    #[tokio::test]
808    async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
809        let tmp = tempfile::tempdir().unwrap();
810        crate::test_helpers::init_git_repo(tmp.path());
811        let (addr, _h) = spawn_once(
812            "200 OK",
813            r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
814        );
815        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
816
817        match resolve_repo_by_name(&client, tmp.path()).await {
818            Err(ResolveRepoByNameError::NotFound { .. }) => {}
819            other => panic!(
820                "expected NotFound, got a different outcome: {}",
821                other.is_ok()
822            ),
823        }
824    }
825
826    #[tokio::test]
827    async fn resolve_repo_by_name_list_failed_on_non_2xx() {
828        // A `list_repos` failure (401/403/500/... — not necessarily a
829        // network error, hence `ListFailed` rather than the old `Network`
830        // name) must be distinguished from `NotFound` so callers like
831        // `check`'s `connectivity_message` can add their own actionable
832        // wrapping instead of a bare "not found" message.
833        let tmp = tempfile::tempdir().unwrap();
834        crate::test_helpers::init_git_repo(tmp.path());
835        let (addr, _h) = spawn_once("500 Internal Server Error", "");
836        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
837
838        match resolve_repo_by_name(&client, tmp.path()).await {
839            Err(ResolveRepoByNameError::ListFailed(e)) => {
840                assert!(e.to_string().contains("500"), "got: {e}");
841            }
842            other => panic!(
843                "expected ListFailed, got a different outcome: {}",
844                other.is_ok()
845            ),
846        }
847    }
848}