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