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