Skip to main content

tracevault_cli/commands/
project.rs

1//! `tracevault project` — workspace/detached-mode project-attribution
2//! commands. Mirrors `commands::repo`'s `switch`/`status` structure, but binds
3//! the project-attribution axis (design §7/Task 7) rather than the repo axis.
4
5use std::collections::HashSet;
6use std::path::Path;
7
8use crate::api_client::{resolve_credentials, ApiClient, ProjectListItem};
9use crate::resolution::{
10    self, effective_project, git_remote_url, org_slug_for, resolve_effective_project,
11    ProjectResolveInputs, ProjectSource,
12};
13use crate::session_state::{self, ProjectBinding, SessionState};
14
15/// Sub-actions for `tracevault project` (project-attribution axis).
16#[derive(clap::Subcommand)]
17pub enum ProjectCmd {
18    /// Bind project attribution to a registered project for the current
19    /// session (or, with `--user`, the session-independent user default).
20    Switch {
21        /// Exact, case-sensitive name of a registered project.
22        name: String,
23        /// Write a session-independent user-level default instead of a
24        /// session binding. Implied when no session id is available. Also
25        /// skips the current-codebase containment check (a user default
26        /// isn't tied to any one checkout).
27        #[arg(long)]
28        user: bool,
29        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
30        #[arg(long)]
31        session_id: Option<String>,
32    },
33    /// Show the project the current session is attributed to.
34    Status {
35        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
36        #[arg(long)]
37        session_id: Option<String>,
38        /// One-off: resolve this project name and feed it in at the
39        /// `--project` precedence tier instead of the session/config
40        /// bindings.
41        #[arg(long)]
42        project: Option<String>,
43    },
44}
45
46pub async fn run(
47    cmd: ProjectCmd,
48    project_root: &Path,
49    cwd: &Path,
50) -> Result<(), Box<dyn std::error::Error>> {
51    match cmd {
52        ProjectCmd::Switch {
53            name,
54            user,
55            session_id,
56        } => switch(&name, user, session_id.as_deref(), project_root, cwd).await,
57        ProjectCmd::Status {
58            session_id,
59            project,
60        } => status(session_id.as_deref(), project.as_deref(), project_root, cwd).await,
61    }
62}
63
64/// Exact, case-sensitive name → item. Miss lists the available names.
65fn resolve_project_name<'a>(
66    items: &'a [ProjectListItem],
67    name: &str,
68) -> Result<&'a ProjectListItem, String> {
69    items.iter().find(|p| p.name == name).ok_or_else(|| {
70        let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
71        names.sort_unstable();
72        format!(
73            "project '{name}' not found. Available: {}",
74            names.join(", ")
75        )
76    })
77}
78
79/// Resolve credentials + the org slug the same way `repo::switch` does: the
80/// locally-configured org wins; only when none is set do we ask the server
81/// which org this credential belongs to.
82async fn resolve_org_and_client(
83    project_root: &Path,
84) -> Result<(String, ApiClient), Box<dyn std::error::Error>> {
85    let (server_url, token) = resolve_credentials(project_root);
86    let server_url = server_url
87        .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
88    let client = ApiClient::new(&server_url, token.as_deref());
89
90    let org_slug = match org_slug_for(project_root) {
91        Some(s) => s,
92        None => {
93            let orgs = client.list_my_orgs().await.map_err(|e| {
94                format!(
95                    "no org configured and could not derive it from your credential ({e}); \
96                     set TRACEVAULT_ORG_SLUG, log in, or run inside a bound repo checkout"
97                )
98            })?;
99            let slugs: Vec<String> = orgs.into_iter().map(|o| o.org_name).collect();
100            resolution::org_slug_from_slugs(&slugs)?
101        }
102    };
103    Ok((org_slug, client))
104}
105
106/// Resolve `name` to a registered project (via `list_projects`) and, unless
107/// `check_codebase` is `false`, verify that project contains the current
108/// codebase (resolved from `cwd`'s git origin remote, mirroring
109/// `resolve_path_to_binding`). Kept separate from `switch` so the
110/// client-dependent flow is unit-testable with a mock `ApiClient`, mirroring
111/// `commands::repo::resolve_switch_binding`.
112async fn resolve_switch_project(
113    name: &str,
114    org_slug: &str,
115    client: &ApiClient,
116    check_codebase: bool,
117    cwd: &Path,
118) -> Result<ProjectBinding, Box<dyn std::error::Error>> {
119    let items = client.list_projects(org_slug).await?;
120    let matched = resolve_project_name(&items, name)
121        .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
122    let project_id = matched.id;
123    let project_name = matched.name.clone();
124
125    if check_codebase {
126        if let Some(git_url) = git_remote_url(cwd) {
127            if let Some(remote) = client.resolve_remote(org_slug, &git_url).await? {
128                let codebase_repo_ids: HashSet<uuid::Uuid> = client
129                    .get_remote_repos(org_slug, remote.remote_id)
130                    .await?
131                    .into_iter()
132                    .map(|r| r.id)
133                    .collect();
134                let project_repo_ids: HashSet<uuid::Uuid> = client
135                    .get_project(org_slug, project_id)
136                    .await?
137                    .repos
138                    .into_iter()
139                    .map(|r| r.id)
140                    .collect();
141                if codebase_repo_ids.is_disjoint(&project_repo_ids) {
142                    return Err(
143                        format!("project '{name}' does not contain the current codebase").into(),
144                    );
145                }
146            }
147            // Codebase not registered with the server → nothing to check
148            // against; allow the switch (mirrors resolve_path_to_binding's
149            // Ok(None) for an untracked remote).
150        }
151        // No git origin remote at all (workspace mode, no checkout) → nothing
152        // to check against; allow the switch.
153    }
154
155    Ok(ProjectBinding {
156        org_slug: org_slug.to_string(),
157        project_id: project_id.to_string(),
158        project_name,
159        updated_at: chrono::Utc::now().to_rfc3339(),
160    })
161}
162
163/// Where a `project switch` should persist its binding: a specific session,
164/// or the session-independent user-level default. Mirrors
165/// `commands::repo::SwitchDest`/`switch_destination`.
166#[derive(Debug)]
167enum SwitchDest {
168    Session(String),
169    UserDefault,
170}
171
172fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
173    if user {
174        return SwitchDest::UserDefault;
175    }
176    match session_id {
177        Some(id) => SwitchDest::Session(id),
178        None => SwitchDest::UserDefault,
179    }
180}
181
182async fn switch(
183    name: &str,
184    user: bool,
185    session_id: Option<&str>,
186    project_root: &Path,
187    cwd: &Path,
188) -> Result<(), Box<dyn std::error::Error>> {
189    let (org_slug, client) = resolve_org_and_client(project_root).await?;
190    let session = crate::commands::repo::resolve_session_id(session_id).ok();
191    let dest = switch_destination(user, session);
192    let check_codebase = matches!(dest, SwitchDest::Session(_));
193    let binding = resolve_switch_project(name, &org_slug, &client, check_codebase, cwd).await?;
194
195    match dest {
196        SwitchDest::Session(id) => {
197            let mut state = session_state::load(&id);
198            state.active_project = Some(binding.clone());
199            session_state::save(&id, &state)?;
200            println!(
201                "bound session {id} to project {} (org {})",
202                binding.project_name, binding.org_slug
203            );
204        }
205        SwitchDest::UserDefault => {
206            crate::user_project_default::save(&binding)?;
207            println!(
208                "set user-level default project {} (org {}); applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
209                binding.project_name, binding.org_slug
210            );
211        }
212    }
213    Ok(())
214}
215
216/// If `effective`'s source is `Deduced`, its binding carries an empty
217/// `project_name` (`resolve_effective_project` doesn't enrich it — see the
218/// comment there). When a projects list is already available in this scope
219/// (fetched for the `--project`/config-default lookups), use it to fill in
220/// the friendly name for display; otherwise leave it empty and
221/// `format_status` falls back to printing the id. Kept simple: this never
222/// triggers an extra API call just for cosmetic enrichment.
223fn enrich_deduced_name(
224    effective: Option<(ProjectBinding, ProjectSource)>,
225    items: Option<&[ProjectListItem]>,
226) -> Option<(ProjectBinding, ProjectSource)> {
227    effective.map(|(mut binding, source)| {
228        if source == ProjectSource::Deduced && binding.project_name.is_empty() {
229            if let Some(items) = items {
230                if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
231                    if let Some(matched) = items.iter().find(|p| p.id == id) {
232                        binding.project_name = matched.name.clone();
233                    }
234                }
235            }
236        }
237        (binding, source)
238    })
239}
240
241/// Pure formatter for `project status`'s output: which project is
242/// attributed, and via which precedence tier. Mirrors
243/// `commands::repo::format_status`. A `Deduced` binding carries an empty
244/// `project_name` (resolution.rs doesn't enrich it), so this falls back to
245/// the id for display.
246fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
247    match effective {
248        Some((b, source)) => {
249            let label = if b.project_name.is_empty() {
250                &b.project_id
251            } else {
252                &b.project_name
253            };
254            format!("project: {label} (org {}) via {source}", b.org_slug)
255        }
256        None => "no project bound".to_string(),
257    }
258}
259
260async fn status(
261    session_id: Option<&str>,
262    project_flag_name: Option<&str>,
263    project_root: &Path,
264    cwd: &Path,
265) -> Result<(), Box<dyn std::error::Error>> {
266    // Session state is best-effort: if a session id resolves, load it; else
267    // warn and fall back to an empty SessionState.
268    let session = match crate::commands::repo::resolve_session_id(session_id) {
269        Ok(id) => session_state::load(&id),
270        Err(_) => {
271            eprintln!(
272                "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
273                 showing binding without session context"
274            );
275            SessionState::default()
276        }
277    };
278    let worktree = crate::paths::worktree_toplevel(cwd);
279    let config_default_name =
280        crate::config::TracevaultConfig::load(project_root).and_then(|c| c.default_project);
281    let user_default = crate::user_project_default::load();
282    let git_url = git_remote_url(cwd);
283
284    // Resolving a project *name* (--project override, or the config-file
285    // default_project) into a binding needs the server; running the full
286    // rung 4/5 chain (deduction, user default) needs it too. Best-effort: no
287    // client degrades to the pure local rungs (flag/config_default stay
288    // unresolved) rather than failing the whole inspector.
289    let effective = match resolve_org_and_client(project_root).await {
290        Ok((org_slug, client)) => {
291            let items = if project_flag_name.is_some() || config_default_name.is_some() {
292                client.list_projects(&org_slug).await.ok()
293            } else {
294                None
295            };
296            let to_binding = |name: &str| -> Option<ProjectBinding> {
297                let matched = items
298                    .as_ref()
299                    .and_then(|items| resolve_project_name(items, name).ok())?;
300                Some(ProjectBinding {
301                    org_slug: org_slug.clone(),
302                    project_id: matched.id.to_string(),
303                    project_name: matched.name.clone(),
304                    updated_at: chrono::Utc::now().to_rfc3339(),
305                })
306            };
307
308            let project_flag = project_flag_name.and_then(to_binding);
309            if let Some(name) = project_flag_name {
310                if project_flag.is_none() {
311                    eprintln!(
312                        "warning: --project '{name}' could not be resolved; ignoring the override"
313                    );
314                }
315            }
316            let config_default = config_default_name.as_deref().and_then(to_binding);
317            if let Some(name) = config_default_name.as_deref() {
318                if config_default.is_none() {
319                    eprintln!(
320                        "warning: configured default_project '{name}' could not be resolved; ignoring it"
321                    );
322                }
323            }
324
325            let inputs = ProjectResolveInputs {
326                project_flag,
327                session: &session,
328                worktree_path: Some(&worktree),
329                config_default,
330            };
331            // `status` is a read-only inspector: unlike the callers that need
332            // an authoritative binding to act on, an unresolvable rung here
333            // (notably the ambiguous/409 "belongs to multiple projects" case)
334            // is informational, not fatal — report it and exit 0 rather than
335            // propagating the error up through `run`/`main` as a hard
336            // failure. `resolve_effective_project` itself keeps returning
337            // `Err` unchanged; only this call site swallows it.
338            let resolved = match resolve_effective_project(
339                &inputs,
340                user_default,
341                &org_slug,
342                git_url.as_deref(),
343                &client,
344            )
345            .await
346            {
347                Ok(effective) => effective,
348                Err(e) => {
349                    println!("project: unresolved — {e}");
350                    return Ok(());
351                }
352            };
353            enrich_deduced_name(resolved, items.as_deref())
354        }
355        Err(e) => {
356            eprintln!(
357                "warning: could not resolve org/credentials ({e}); showing local status only"
358            );
359            let inputs = ProjectResolveInputs {
360                project_flag: None,
361                session: &session,
362                worktree_path: Some(&worktree),
363                config_default: None,
364            };
365            effective_project(&inputs)
366        }
367    };
368
369    println!(
370        "{}",
371        format_status(effective.as_ref().map(|(b, s)| (b, *s)))
372    );
373    Ok(())
374}
375
376#[cfg(test)]
377mod tests {
378    use super::*;
379    use std::io::{BufRead, BufReader, Write};
380    use std::net::TcpListener;
381    use std::thread;
382
383    #[test]
384    fn resolve_project_name_exact_match_and_miss() {
385        let items = vec![
386            ProjectListItem {
387                id: uuid::Uuid::nil(),
388                name: "payments".into(),
389            },
390            ProjectListItem {
391                id: uuid::Uuid::from_u128(2),
392                name: "web".into(),
393            },
394        ];
395        let ok = resolve_project_name(&items, "web").unwrap();
396        assert_eq!(ok.id, uuid::Uuid::from_u128(2));
397        let err = resolve_project_name(&items, "Web").unwrap_err(); // case-sensitive
398        assert!(err.contains("payments") && err.contains("web")); // lists available names
399    }
400
401    #[test]
402    fn switch_destination_user_flag_forces_user_default() {
403        assert!(matches!(
404            switch_destination(true, Some("sess-1".to_string())),
405            SwitchDest::UserDefault
406        ));
407        assert!(matches!(
408            switch_destination(true, None),
409            SwitchDest::UserDefault
410        ));
411    }
412
413    #[test]
414    fn switch_destination_session_when_present_and_no_user_flag() {
415        assert!(matches!(
416            switch_destination(false, Some("sess-1".to_string())),
417            SwitchDest::Session(id) if id == "sess-1"
418        ));
419    }
420
421    #[test]
422    fn switch_destination_user_default_when_no_session() {
423        assert!(matches!(
424            switch_destination(false, None),
425            SwitchDest::UserDefault
426        ));
427    }
428
429    fn pb(name: &str) -> ProjectBinding {
430        ProjectBinding {
431            org_slug: "org".into(),
432            project_id: format!("id-{name}"),
433            project_name: name.into(),
434            updated_at: "t".into(),
435        }
436    }
437
438    #[test]
439    fn format_status_none() {
440        assert_eq!(format_status(None), "no project bound");
441    }
442
443    #[test]
444    fn format_status_project_flag() {
445        let b = pb("web");
446        assert_eq!(
447            format_status(Some((&b, ProjectSource::ProjectFlag))),
448            "project: web (org org) via --project override"
449        );
450    }
451
452    #[test]
453    fn format_status_session_active() {
454        let b = pb("payments");
455        assert_eq!(
456            format_status(Some((&b, ProjectSource::SessionActive))),
457            "project: payments (org org) via session (project switch)"
458        );
459    }
460
461    #[test]
462    fn format_status_deduced_falls_back_to_id_when_name_empty() {
463        let b = ProjectBinding {
464            org_slug: "org".into(),
465            project_id: "deduced-id".into(),
466            project_name: String::new(),
467            updated_at: "".into(),
468        };
469        assert_eq!(
470            format_status(Some((&b, ProjectSource::Deduced))),
471            "project: deduced-id (org org) via repo deduction"
472        );
473    }
474
475    #[test]
476    fn format_status_user_default() {
477        let b = pb("payments");
478        assert_eq!(
479            format_status(Some((&b, ProjectSource::UserDefault))),
480            "project: payments (org org) via user default (project switch --user)"
481        );
482    }
483
484    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
485    /// request it accepts (mirrors `commands::repo`'s test helper).
486    fn spawn_once(response: String) -> String {
487        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
488        let addr = listener.local_addr().unwrap();
489        let response: &'static str = Box::leak(response.into_boxed_str());
490        thread::spawn(move || {
491            if let Ok((stream, _)) = listener.accept() {
492                let mut reader = BufReader::new(stream);
493                let mut request_line = String::new();
494                let _ = reader.read_line(&mut request_line);
495                let mut stream = reader.into_inner();
496                let _ = stream.write_all(response.as_bytes());
497                let _ = stream.flush();
498            }
499        });
500        format!("http://{addr}")
501    }
502
503    /// Generalizes `spawn_once` to a listener that answers each of
504    /// `responses` in order, one per accepted connection (the
505    /// containment-check flow makes several sequential requests).
506    fn spawn_n(responses: Vec<String>) -> String {
507        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
508        let addr = listener.local_addr().unwrap();
509        thread::spawn(move || {
510            for response in responses {
511                let response: &'static str = Box::leak(response.into_boxed_str());
512                if let Ok((stream, _)) = listener.accept() {
513                    let mut reader = BufReader::new(stream);
514                    let mut request_line = String::new();
515                    let _ = reader.read_line(&mut request_line);
516                    let mut stream = reader.into_inner();
517                    let _ = stream.write_all(response.as_bytes());
518                    let _ = stream.flush();
519                }
520            }
521        });
522        format!("http://{addr}")
523    }
524
525    fn http_200(body: &str) -> String {
526        format!(
527            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
528            body.len(),
529            body
530        )
531    }
532
533    /// Happy-path flow test (mirrors `resolve_switch_binding_ok_for_registered_repo`
534    /// in `commands/repo.rs`): mock `GET /projects`, resolve the switch's
535    /// project binding, apply it to a (uniquely-named, cleaned-up-afterward)
536    /// session's state, and confirm the write round-trips through the real
537    /// `session_state::save`/`load_from` — the exact assertion the brief
538    /// calls for.
539    #[tokio::test]
540    async fn project_switch_happy_path_writes_active_project_to_session_file() {
541        let tmp = tempfile::tempdir().unwrap();
542        crate::test_helpers::init_git_repo(tmp.path()); // no origin remote → containment check is a no-op
543
544        // C3: isolate `session_state::sessions_dir()` (which honors
545        // `$XDG_STATE_HOME`) to a tempdir for the duration of this test, so
546        // it never touches the developer's real state dir.
547        //
548        // SAFETY: test-scoped env mutation, mirroring the precedent in
549        // `commands::project`'s tests (`status_reports_ambiguous_deduction_
550        // as_informational_not_fatal`). No other test in this crate reads
551        // or sets XDG_STATE_HOME, so this can't race another test's
552        // expectations; restored in a guard so a panic mid-test still
553        // cleans up the process env.
554        let state_tmp = tempfile::tempdir().unwrap();
555        let mut _guard = crate::test_helpers::EnvVarGuard::new();
556        _guard.set("XDG_STATE_HOME", state_tmp.path());
557
558        let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
559        let base = spawn_once(http_200(list));
560        let client = ApiClient::new(&base, Some("tok"));
561
562        let binding = resolve_switch_project("web", "org", &client, true, tmp.path())
563            .await
564            .expect("expected Ok binding");
565        assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
566        assert_eq!(binding.project_name, "web");
567        assert_eq!(binding.org_slug, "org");
568
569        let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
570        let mut state = session_state::load(&session_id);
571        state.active_project = Some(binding.clone());
572        session_state::save(&session_id, &state).expect("save must succeed");
573
574        let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
575        assert!(sessions_dir.starts_with(state_tmp.path()));
576        let loaded = session_state::load_from(&sessions_dir, &session_id);
577        assert_eq!(loaded.active_project, Some(binding));
578    }
579
580    #[tokio::test]
581    async fn project_switch_errors_when_name_not_found() {
582        let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
583        let base = spawn_once(http_200(list));
584        let client = ApiClient::new(&base, Some("tok"));
585
586        let err = resolve_switch_project("web", "org", &client, false, Path::new("/nonexistent"))
587            .await
588            .expect_err("expected Err for an unknown project name");
589        let msg = err.to_string();
590        assert!(msg.contains("not found"), "got: {msg}");
591        assert!(msg.contains("payments"), "got: {msg}");
592    }
593
594    #[tokio::test]
595    async fn project_switch_errors_when_project_does_not_contain_codebase() {
596        let tmp = tempfile::tempdir().unwrap();
597        crate::test_helpers::init_git_repo(tmp.path());
598        let ok = std::process::Command::new("git")
599            .args([
600                "-C",
601                &tmp.path().to_string_lossy(),
602                "remote",
603                "add",
604                "origin",
605                "git@github.com:org/repo.git",
606            ])
607            .status()
608            .expect("git remote add failed")
609            .success();
610        assert!(ok, "git remote add must succeed");
611
612        let list =
613            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
614        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
615        let remote = format!(
616            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
617        );
618        let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
619        let detail = format!(
620            r#"{{"id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_url":"https://github.com/org/repo.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{{"id":"{codebase_repo_id}","name":"repo"}}]}}"#
621        );
622        let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
623        let base = spawn_n(vec![
624            http_200(&list),
625            http_200(&remote),
626            http_200(&detail),
627            http_200(project_detail),
628        ]);
629        let client = ApiClient::new(&base, Some("tok"));
630
631        let err = resolve_switch_project("payments", "org", &client, true, tmp.path())
632            .await
633            .expect_err("expected Err: project doesn't contain the current codebase");
634        assert!(
635            err.to_string()
636                .contains("does not contain the current codebase"),
637            "got: {err}"
638        );
639    }
640
641    /// Regression for C2: a no-session, non-`--user` `switch` resolves to
642    /// `SwitchDest::UserDefault` (mirroring `switch_destination`'s
643    /// no-session fallback), so the codebase-containment check must be
644    /// skipped even though `--user` wasn't passed. `cwd` has a git origin
645    /// remote, but `check_codebase` being correctly derived from the
646    /// destination (not from `!user`) means `resolve_switch_project` never
647    /// calls out to `resolve_remote`/`get_project` to check it — the mock
648    /// server below only ever answers one request (`list_projects`). If the
649    /// gating regressed back to `!user`, the second HTTP call this test
650    /// deliberately can't serve (mirrors `spawn_once`'s one-shot listener,
651    /// which closes after the first `accept()`) would fail fast, and the
652    /// switch would error instead of succeeding.
653    ///
654    /// Credentials/org are supplied two ways at once: a
655    /// `.tracevault/config.toml` in `cwd`, and `TRACEVAULT_SERVER_URL`/
656    /// `_ORG_SLUG`/`_API_KEY` env vars pinned (via the guard below) at the
657    /// same mock server/values. The env vars sit above the config file in
658    /// `resolve_credentials`'s precedence, so without pinning them
659    /// explicitly, an ambient shell that already exports
660    /// `TRACEVAULT_SERVER_URL` (etc.) would leak in and point this test's
661    /// client at the wrong server — deterministic in CI (which doesn't set
662    /// them) but flaky on a developer machine that has them exported. The
663    /// guard's `set` calls make the test's behavior independent of the
664    /// ambient environment. `_env_lock` (taken below) also serializes this
665    /// against `status_reports_ambiguous_deduction_as_informational_not_
666    /// fatal`, which touches the same three vars. `XDG_CONFIG_HOME` is
667    /// redirected so this doesn't read the developer's real
668    /// `credentials.json` (which could otherwise short-circuit
669    /// `org_slug_for`/`resolve_credentials` before the config file/env vars
670    /// are consulted, and race for real on a machine with actual
671    /// TraceVault credentials) and so the resulting user-default write
672    /// lands in a tempdir, not `~/.config`. `user_project_default`'s own
673    /// real-path round-trip test mutates the same var, so both hold
674    /// `test_helpers::lock_env_mutation()` for their duration.
675    #[tokio::test]
676    async fn switch_without_session_or_user_flag_skips_codebase_check() {
677        let _env_lock = crate::test_helpers::lock_env_mutation().await;
678        let tmp = tempfile::tempdir().unwrap();
679        crate::test_helpers::init_git_repo(tmp.path());
680        let ok = std::process::Command::new("git")
681            .args([
682                "-C",
683                &tmp.path().to_string_lossy(),
684                "remote",
685                "add",
686                "origin",
687                "git@github.com:org/repo.git",
688            ])
689            .status()
690            .expect("git remote add failed")
691            .success();
692        assert!(ok, "git remote add must succeed");
693
694        let list =
695            r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
696        let base = spawn_once(http_200(&list));
697
698        let config_dir = tmp.path().join(".tracevault");
699        std::fs::create_dir_all(&config_dir).unwrap();
700        std::fs::write(
701            config_dir.join("config.toml"),
702            format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\norg_slug = \"org\"\n"),
703        )
704        .unwrap();
705
706        // SAFETY: test-scoped env mutation, restored in a guard so a panic
707        // in `switch` still cleans up the process env. `_env_lock` (taken
708        // above) also covers `resolve_credentials`/`org_slug_for`'s *reads*
709        // of TRACEVAULT_SERVER_URL/_ORG_SLUG/_API_KEY: those env vars sit
710        // above `.tracevault/config.toml` in precedence, so if the
711        // developer's ambient shell happens to already export them (e.g.
712        // pointing at a real server), `resolve_credentials` would pick
713        // those up instead of this test's config file and the request
714        // would go to the wrong place — deterministic in CI (which doesn't
715        // set them) but flaky locally. Pin them explicitly at this test's
716        // own mock server so behavior doesn't depend on the ambient
717        // environment, mirroring the precedent in `status_reports_
718        // ambiguous_deduction_as_informational_not_fatal`. `_env_lock`
719        // (taken above) also serializes this against that test and any
720        // other test in the crate touching the same three vars.
721        let mut _guard = crate::test_helpers::EnvVarGuard::new();
722        _guard.remove("TRACEVAULT_SESSION_ID");
723        _guard.set("XDG_CONFIG_HOME", tmp.path());
724        _guard.set("TRACEVAULT_SERVER_URL", &base);
725        _guard.set("TRACEVAULT_ORG_SLUG", "org");
726        _guard.set("TRACEVAULT_API_KEY", "tok");
727
728        let result = switch("payments", false, None, tmp.path(), tmp.path()).await;
729        assert!(
730            result.is_ok(),
731            "expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
732        );
733
734        let saved = crate::user_project_default::load();
735        assert_eq!(
736            saved.map(|b| b.project_name),
737            Some("payments".to_string()),
738            "no-session switch must fall back to the user-level default binding"
739        );
740    }
741
742    fn items() -> Vec<ProjectListItem> {
743        vec![
744            ProjectListItem {
745                id: uuid::Uuid::from_u128(1),
746                name: "payments".into(),
747            },
748            ProjectListItem {
749                id: uuid::Uuid::from_u128(2),
750                name: "web".into(),
751            },
752        ]
753    }
754
755    fn deduced(id: uuid::Uuid) -> (ProjectBinding, ProjectSource) {
756        (
757            ProjectBinding {
758                org_slug: "org".into(),
759                project_id: id.to_string(),
760                project_name: String::new(),
761                updated_at: "".into(),
762            },
763            ProjectSource::Deduced,
764        )
765    }
766
767    #[test]
768    fn enrich_deduced_name_fills_in_name_when_id_found_in_list() {
769        let effective = Some(deduced(uuid::Uuid::from_u128(2)));
770        let (b, source) = enrich_deduced_name(effective, Some(&items())).unwrap();
771        assert_eq!(b.project_name, "web");
772        assert_eq!(source, ProjectSource::Deduced);
773    }
774
775    #[test]
776    fn enrich_deduced_name_leaves_empty_when_no_list_available() {
777        let effective = Some(deduced(uuid::Uuid::from_u128(2)));
778        let (b, _source) = enrich_deduced_name(effective, None).unwrap();
779        assert_eq!(b.project_name, "");
780    }
781
782    #[test]
783    fn enrich_deduced_name_leaves_empty_when_id_not_in_list() {
784        let effective = Some(deduced(uuid::Uuid::from_u128(999)));
785        let (b, _source) = enrich_deduced_name(effective, Some(&items())).unwrap();
786        assert_eq!(b.project_name, "");
787    }
788
789    #[test]
790    fn enrich_deduced_name_leaves_non_deduced_sources_untouched() {
791        // Only the Deduced source carries an empty name by design; other
792        // sources must pass through unchanged even if a list is available.
793        let b = pb("payments");
794        let effective = Some((b.clone(), ProjectSource::SessionActive));
795        let (out, source) = enrich_deduced_name(effective, Some(&items())).unwrap();
796        assert_eq!(out, b);
797        assert_eq!(source, ProjectSource::SessionActive);
798    }
799
800    #[test]
801    fn enrich_deduced_name_passes_through_none() {
802        assert!(enrich_deduced_name(None, Some(&items())).is_none());
803    }
804
805    /// F1: an ambiguous ("this repo belongs to multiple projects") deduction
806    /// result is a hard `Err` from `resolve_effective_project` — but `status`
807    /// is a read-only inspector, so it must swallow that into an
808    /// informational line and still exit `Ok`, not propagate the error up
809    /// through `run`/`main` as a fatal exit. Mocks the `/projects/resolve`
810    /// endpoint with a 409, mirroring resolution.rs's
811    /// `ambiguous_deduction_errors_when_no_higher_rung`.
812    #[tokio::test]
813    async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
814        let _env_lock = crate::test_helpers::lock_env_mutation().await;
815        let tmp = tempfile::tempdir().unwrap();
816        crate::test_helpers::init_git_repo(tmp.path());
817        let ok = std::process::Command::new("git")
818            .args([
819                "-C",
820                &tmp.path().to_string_lossy(),
821                "remote",
822                "add",
823                "origin",
824                "git@github.com:org/repo.git",
825            ])
826            .status()
827            .expect("git remote add failed")
828            .success();
829        assert!(ok, "git remote add must succeed");
830
831        let base = spawn_once(
832            "HTTP/1.1 409 Conflict\r\nContent-Type: application/json\r\nContent-Length: 20\r\nConnection: close\r\n\r\n{\"error\":\"multiple\"}"
833                .to_string(),
834        );
835
836        // SAFETY: test-scoped env mutation, mirroring the precedent in
837        // `commands::login`'s tests, restored in a guard so a panic in
838        // `status` still cleans up the process env. `_env_lock` (taken
839        // above) serializes this against any other test in the crate that
840        // reads or sets TRACEVAULT_SERVER_URL/TRACEVAULT_ORG_SLUG/
841        // TRACEVAULT_API_KEY (e.g. `switch_without_session_or_user_flag_
842        // skips_codebase_check`, whose credential resolution would
843        // otherwise observe these values while they're set here and get
844        // routed at this test's mock server instead of its own).
845        let mut _guard = crate::test_helpers::EnvVarGuard::new();
846        _guard.set("TRACEVAULT_SERVER_URL", &base);
847        _guard.set("TRACEVAULT_ORG_SLUG", "org");
848        _guard.set("TRACEVAULT_API_KEY", "tok");
849
850        let result = status(None, None, tmp.path(), tmp.path()).await;
851
852        assert!(
853            result.is_ok(),
854            "status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
855        );
856    }
857}