Skip to main content

tracevault_cli/commands/
repo.rs

1//! `tracevault repo` — workspace/detached-mode repo binding commands.
2
3use crate::program::{CLI, ENV, TOP};
4use std::path::Path;
5
6use crate::api_client::{resolve_client, ApiClient};
7use crate::credentials::resolve_credentials;
8use crate::resolution::{
9    binding_from_config, checkout_config_repo_id, effective_binding, resolve_path_to_binding,
10    resolve_path_to_codebase, BindingSource, RepoChoice, ResolveInputs, ResolvedCodebase,
11};
12use crate::session_state::{self, RepoBinding, SessionState};
13
14/// Sub-actions for `repo` (workspace/detached mode).
15#[derive(clap::Subcommand)]
16pub enum RepoCmd {
17    /// Bind tracing to a registered repo for the current session and print its
18    /// policies. Give a checkout <path> — `--name` is deprecated and always
19    /// errors, telling you to bind by path instead.
20    #[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
21    Switch {
22        /// Path to a checkout of a registered repo (resolves via its git origin remote).
23        #[arg(group = "target")]
24        path: Option<String>,
25        /// Deprecated: name-only binding is no longer supported and always
26        /// errors; bind by checkout path instead (`repo switch <path>`).
27        #[arg(long, group = "target")]
28        name: Option<String>,
29        /// Which of the codebase's repo records to bind, when <path>'s
30        /// codebase has several. Without it, switch keeps the repo already in
31        /// use (the session's current binding, else a checkout's
32        /// `.visdom/tracing.toml`) and errors if none of them is.
33        #[arg(long, requires = "path")]
34        repo_id: Option<uuid::Uuid>,
35        /// Write a session-independent user-level default instead of a session
36        /// binding. Implied when no session id is available.
37        #[arg(long)]
38        user: bool,
39        /// Session to target; defaults to the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID).
40        #[arg(long)]
41        session_id: Option<String>,
42    },
43    /// Show the repo the current session is bound to.
44    Status {
45        /// Session to target; defaults to the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID).
46        #[arg(long)]
47        session_id: Option<String>,
48        /// One-off: resolve this checkout path instead of the session binding.
49        #[arg(long)]
50        path: Option<String>,
51    },
52    /// Clear the current session's binding, or (with --user) the user-level default.
53    Reset {
54        /// Clear the user-level default instead of the session binding.
55        #[arg(long)]
56        user: bool,
57        /// Session to target; defaults to the session id the session-start hook exported (in Amp: $AMP_CURRENT_THREAD_ID).
58        #[arg(long)]
59        session_id: Option<String>,
60    },
61}
62
63/// Resolve the current session id: the explicit flag wins, else
64/// `the session id the session-start hook exported` (set by the SessionStart hook of `init --global`),
65/// else, in Amp's shell, `$AMP_CURRENT_THREAD_ID` (see
66/// [`crate::session_state::env_session_id`]).
67pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
68    if let Some(s) = explicit {
69        return Ok(s.to_string());
70    }
71    crate::session_state::env_session_id().ok_or_else(|| {
72        crate::program::say(
73            "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
74         (installed by `tracevault init --global`; Amp sessions use $AMP_CURRENT_THREAD_ID)",
75        )
76        .into()
77    })
78}
79
80pub async fn run(
81    cmd: RepoCmd,
82    project_root: &Path,
83    cwd: &Path,
84) -> Result<(), Box<dyn std::error::Error>> {
85    match cmd {
86        RepoCmd::Status { session_id, path } => {
87            status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
88        }
89        RepoCmd::Switch {
90            path,
91            name,
92            repo_id,
93            user,
94            session_id,
95        } => {
96            switch(
97                path.as_deref(),
98                name.as_deref(),
99                repo_id,
100                user,
101                session_id.as_deref(),
102                project_root,
103            )
104            .await
105        }
106        RepoCmd::Reset { user, session_id } => reset(user, session_id.as_deref()),
107    }
108}
109
110/// Resolve a path to its codebase for `repo switch`, turning "unregistered"
111/// into a clear error (switch should fail loudly, unlike the best-effort
112/// `--path` status override).
113async fn resolve_switch_codebase(
114    path: &Path,
115    client: &ApiClient,
116) -> Result<ResolvedCodebase, Box<dyn std::error::Error>> {
117    resolve_path_to_codebase(path, client)
118        .await?
119        .ok_or_else(|| {
120            format!(
121                "repo at {} is not registered with Visdom; nothing to bind",
122                path.display()
123            )
124            .into()
125        })
126}
127
128/// A repo id `repo switch` should keep if the codebase links it, and where it
129/// comes from (for the message saying which one was kept).
130struct InUse {
131    repo_id: uuid::Uuid,
132    source: String,
133}
134
135/// Which of the codebase's repos `repo switch` binds. Pure.
136///
137/// An explicit `--repo-id` wins, if it is one of the codebase's repos. Else
138/// the only repo; else the first `in_use` repo the codebase links — the
139/// destination's current binding comes first, so a session is never moved to
140/// another repo of the same codebase mid-flight (that splits it across two
141/// session rows on the server, VIS-1018). Else an error listing the repos.
142/// `Ok` carries the repo id and, when several repos were possible, which
143/// `in_use` source decided.
144fn pick_switch_repo(
145    codebase: &ResolvedCodebase,
146    explicit: Option<uuid::Uuid>,
147    in_use: &[InUse],
148) -> Result<(uuid::Uuid, Option<String>), Box<dyn std::error::Error>> {
149    if let Some(id) = explicit {
150        if codebase.repos.iter().any(|r| r.id == id) {
151            return Ok((id, None));
152        }
153        return Err(format!(
154            "repo {id} is not a repo of codebase {}; its repos are: {}",
155            codebase.display_name(),
156            codebase.repo_list()
157        )
158        .into());
159    }
160    let preferred: Vec<uuid::Uuid> = in_use.iter().map(|u| u.repo_id).collect();
161    match codebase.choose(&preferred) {
162        RepoChoice::Only(id) => Ok((id, None)),
163        RepoChoice::Preferred(id, i) => Ok((id, Some(in_use[i].source.clone()))),
164        RepoChoice::Ambiguous => Err(format!(
165            "codebase {} has {} repo records: {}. None of them is this binding's current \
166             repo or a checkout's .visdom/tracing.toml repo, so switch will not guess; \
167             choose one with `{CLI} repo switch <path> --repo-id <id>`",
168            codebase.display_name(),
169            codebase.repos.len(),
170            codebase.repo_list()
171        )
172        .into()),
173    }
174}
175
176/// Apply a switch to session state (session-level active binding). Pure.
177fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
178    state.active = Some(binding);
179}
180
181/// Clear the session's workspace binding (session-level reset), and keep it
182/// cleared: the hooks would otherwise bind the session again from its
183/// checkout's remote on the next event. Pure.
184fn apply_reset(state: &mut SessionState) {
185    // Bindings only: where the session keeps its dir is not a binding, and
186    // dropping it would split the session again (VIS-1257).
187    *state = SessionState {
188        auto_bind_off: true,
189        storage_root: state.storage_root.take(),
190        ..SessionState::default()
191    };
192}
193
194fn reset(user: bool, session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
195    if user {
196        crate::user_default::clear()?;
197        println!("cleared user-level default repo binding");
198        return Ok(());
199    }
200    let id = resolve_session_id(session_id)?;
201    let mut state = session_state::load(&id);
202    apply_reset(&mut state);
203    session_state::save(&id, &state)?;
204    // NOTE: subagent worktree-scoped reset-to-parent is handled in sub-plan C.
205    println!("cleared workspace repo binding for session {id}");
206    println!(
207        "it stays unbound (no automatic binding from the checkout's remote) until \
208         `{CLI} repo switch`"
209    );
210    Ok(())
211}
212
213/// Which target `repo switch` should resolve to a binding: a checkout path.
214/// `--name` binding is deprecated (see `switch_target`) and no longer
215/// produces a variant here.
216#[derive(Debug, PartialEq, Eq)]
217enum SwitchTarget<'a> {
218    Path(&'a str),
219}
220
221/// Pure guard for `repo switch`'s `<path>` / `--name` arguments. Kept
222/// separate from `switch` so it can be unit-tested without spinning up a
223/// server or session state (also a safety net if the clap `ArgGroup` on the
224/// `Switch` variant is ever loosened). `--name` binding is hard-deprecated:
225/// a name-only invocation errors rather than resolving by name, directing
226/// callers to bind by checkout path so the codebase is resolved from its git
227/// remote.
228fn switch_target<'a>(
229    path: Option<&'a str>,
230    name: Option<&'a str>,
231) -> Result<SwitchTarget<'a>, Box<dyn std::error::Error>> {
232    match (path, name) {
233        (Some(p), _) if !p.trim().is_empty() => Ok(SwitchTarget::Path(p)),
234        (Some(_), _) => Err("repo path must not be empty".into()),
235        (None, Some(_)) => Err(crate::program::say(
236            "`--name` binding is deprecated and no longer supported; bind by checkout path \
237             (`tracevault repo switch <path>`) so the codebase is resolved from its git remote",
238        )
239        .into()),
240        (None, None) => Err(crate::program::say(
241            "provide a checkout path to bind (`tracevault repo switch <path>`)",
242        )
243        .into()),
244    }
245}
246
247/// Where a `repo switch` should persist its binding: a specific session, or the
248/// session-independent user-level default.
249#[derive(Debug)]
250enum SwitchDest {
251    Session(String),
252    UserDefault,
253}
254
255/// Pure choice of write target for `repo switch`: `--user` (or the absence of
256/// any session id) selects the user-level default; otherwise the resolved
257/// session id selects a session binding. Kept pure so it's unit-testable.
258fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
259    if user {
260        return SwitchDest::UserDefault;
261    }
262    match session_id {
263        Some(id) => SwitchDest::Session(id),
264        None => SwitchDest::UserDefault,
265    }
266}
267
268/// The repos `repo switch` should keep, most preferred first: what the
269/// destination currently resolves to (for a session, exactly what its hooks
270/// stream to: session binding → this checkout's config.toml → user default;
271/// for `--user`, the current user default), then the target checkout's own
272/// config.toml, then this checkout's. Ids that are not UUIDs are skipped.
273fn in_use_repos(dest: &SwitchDest, target: &Path, project_root: &Path) -> Vec<InUse> {
274    let bound = crate::config::TracevaultConfig::load(project_root)
275        .as_ref()
276        .and_then(binding_from_config);
277    let user_default = crate::user_default::load();
278    let current = match dest {
279        SwitchDest::Session(id) => effective_binding(ResolveInputs {
280            repo_flag: None,
281            session: &session_state::load(id),
282            worktree_path: None,
283            bound,
284            user_default,
285        })
286        .map(|(b, source)| (b, source.to_string())),
287        SwitchDest::UserDefault => {
288            user_default.map(|b| (b, BindingSource::UserDefault.to_string()))
289        }
290    };
291    let mut in_use: Vec<InUse> = current
292        .and_then(|(b, source)| {
293            Some(InUse {
294                repo_id: b.repo_id.parse().ok()?,
295                source: format!("the current binding ({source})"),
296            })
297        })
298        .into_iter()
299        .collect();
300    for checkout in [target, project_root] {
301        if let Some(repo_id) = checkout_config_repo_id(checkout) {
302            in_use.push(InUse {
303                repo_id,
304                source: format!("{}'s .visdom/tracing.toml", checkout.display()),
305            });
306        }
307    }
308    in_use
309}
310
311async fn switch(
312    path: Option<&str>,
313    name: Option<&str>,
314    repo_id: Option<uuid::Uuid>,
315    user: bool,
316    session_id: Option<&str>,
317    project_root: &Path,
318) -> Result<(), Box<dyn std::error::Error>> {
319    // Validate the target argument before any network work, so a bad/empty
320    // path or name surfaces as an argument error rather than an unrelated
321    // network error from the resolution step below.
322    let target = switch_target(path, name)?;
323
324    let client = resolve_client(project_root)?;
325
326    let SwitchTarget::Path(p) = target;
327    let target_path = Path::new(p);
328    let codebase = resolve_switch_codebase(target_path, &client).await?;
329
330    // A session id is optional now: with one (and no --user) we bind that
331    // session; without one (or with --user) we set the user-level default,
332    // which any new session inherits. This is what lets a container bind its
333    // repo before Claude — and its session — exists.
334    let session = resolve_session_id(session_id).ok();
335    let dest = switch_destination(user, session);
336
337    // Resolve the repo BEFORE persisting anything: an ambiguous codebase must
338    // not leave a persisted binding behind.
339    let in_use = in_use_repos(&dest, target_path, project_root);
340    let (repo_uuid, kept) = pick_switch_repo(&codebase, repo_id, &in_use)?;
341    if let Some(source) = kept {
342        let name = codebase
343            .repos
344            .iter()
345            .find(|r| r.id == repo_uuid)
346            .map_or("", |r| r.name.as_str());
347        eprintln!(
348            "codebase {} has {} repo records; keeping repo {name}, {source}",
349            codebase.display_name(),
350            codebase.repos.len()
351        );
352    }
353    let binding = codebase.binding(repo_uuid);
354
355    match dest {
356        SwitchDest::Session(id) => {
357            let mut state = session_state::load(&id);
358            apply_switch(&mut state, binding.clone());
359            session_state::save(&id, &state)?;
360            println!("bound session {id} to repo {}", binding.repo_id);
361        }
362        SwitchDest::UserDefault => {
363            crate::user_default::save(&binding)?;
364            println!(
365                "set user-level default repo {}; applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
366                binding.repo_id
367            );
368        }
369    }
370
371    // Best-effort policy fetch (applies to either destination). A failure here
372    // must not make the whole command report as an error.
373    match client.get_agent_instructions(&repo_uuid).await {
374        Ok(policies) => println!("{}", policies.content),
375        Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
376    }
377    Ok(())
378}
379
380/// Resolve a `--path <path>` override into a live `RepoBinding`, if possible.
381/// Best-effort: prints a clear message and returns `None` on any failure
382/// (missing credentials, or a server error) rather than failing the whole
383/// `status` inspector.
384async fn resolve_repo_flag(
385    repo_flag_path: Option<&str>,
386    project_root: &Path,
387) -> Option<RepoBinding> {
388    let path = repo_flag_path?;
389
390    // Best-effort, per this function's contract: a credential/URL mismatch
391    // prints the reason and drops the `--path` override rather than failing the
392    // whole `status` inspector.
393    let (server_url, credential) = match resolve_credentials(project_root) {
394        Ok(resolved) => resolved,
395        Err(e) => {
396            eprintln!("--path {path}: {e}");
397            return None;
398        }
399    };
400    let Some(server_url) = server_url else {
401        eprintln!(
402            "--path {path}: no server URL configured (run `{TOP} login`); showing binding \
403             without the --path override"
404        );
405        return None;
406    };
407
408    let client = ApiClient::with_credential(&server_url, credential);
409    match resolve_path_to_binding(Path::new(path), &client).await {
410        Ok(Some(binding)) => Some(binding),
411        Ok(None) => {
412            eprintln!(
413                "--path {path}: no registered repo found for this path's git remote; showing \
414                 binding without the --path override"
415            );
416            None
417        }
418        Err(e) => {
419            eprintln!(
420                "--path {path}: failed to resolve ({e}); showing binding without the --path \
421                 override"
422            );
423            None
424        }
425    }
426}
427
428/// Pure formatter for `repo status`'s output: which repo is bound, and via
429/// which precedence tier. Kept separate from I/O so it can be unit-tested.
430fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
431    match binding {
432        Some((b, source)) => format!("bound to repo {} via {source}", b.repo_id),
433        None => crate::program::say(
434            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)",
435        ),
436    }
437}
438
439async fn status(
440    session_id: Option<&str>,
441    repo_flag_path: Option<&str>,
442    project_root: &Path,
443    cwd: &Path,
444) -> Result<(), Box<dyn std::error::Error>> {
445    // Session state is best-effort: if a session id resolves, load it; else
446    // warn and fall back to an empty SessionState rather than silently
447    // reporting "not bound" without the user knowing why.
448    let session = match resolve_session_id(session_id) {
449        Ok(id) => session_state::load(&id),
450        Err(_) => {
451            eprintln!(
452                "warning: no session id (pass --session-id or set {ENV}_SESSION_ID); \
453                 showing binding without session context"
454            );
455            SessionState::default()
456        }
457    };
458    let worktree = crate::paths::worktree_toplevel(cwd);
459    let config = crate::config::TracevaultConfig::load(project_root);
460    let bound = config.as_ref().and_then(binding_from_config);
461    let config_project = config
462        .as_ref()
463        .and_then(crate::resolution::project_from_config);
464
465    // A --path override on status resolves live (needs the server).
466    let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;
467
468    let user_default = crate::user_default::load();
469
470    // What ingest does for this session, through the hook's own gate (no
471    // `--path` override: the hook has none). Without it a project-only
472    // session reads as "not bound" here although its events ship (VIS-1255).
473    let recording = crate::commands::stream::recording_attribution_for(
474        &session,
475        &worktree,
476        bound.clone(),
477        user_default.clone(),
478        config_project,
479    );
480
481    let effective = effective_binding(ResolveInputs {
482        repo_flag,
483        session: &session,
484        worktree_path: Some(&worktree),
485        bound,
486        user_default: user_default.clone(),
487    });
488    println!(
489        "{}",
490        format_status(effective.as_ref().map(|(b, s)| (b, *s)))
491    );
492    println!(
493        "{}",
494        crate::commands::stream::recording_line_for(&recording)
495    );
496
497    // Surface which codebase the effective binding belongs to, with live clone
498    // status when reachable. Best-effort — a failure must not fail `status`:
499    //   1. `remote_id` (persisted at init / set by switch) → fetch the remote
500    //      detail for name + clone status (works without a checkout);
501    //   2. else a `git_url` → live `resolve_remote` for name + clone status;
502    //   3. else fall back to the cached `codebase_name` (name only, offline).
503    if let Some((binding, _)) = &effective {
504        // Best-effort codebase line: a credential/URL mismatch degrades to the
505        // offline fallback (cached name only) with the reason printed, rather
506        // than failing `repo status` — whose job is to explain local state.
507        let (server_url, credential) = match resolve_credentials(project_root) {
508            Ok(resolved) => resolved,
509            Err(e) => {
510                eprintln!("Warning: {e}");
511                (None, None)
512            }
513        };
514        let client = server_url
515            .as_ref()
516            .map(|su| ApiClient::with_credential(su, credential));
517        let detail_line = if let (Some(client), Some(remote_id)) = (&client, binding.remote_id) {
518            client.get_remote_detail(remote_id).await.ok().map(|d| {
519                crate::resolution::codebase_line(
520                    d.name.as_deref(),
521                    &d.normalized_url,
522                    &d.clone_status,
523                )
524            })
525        } else {
526            None
527        };
528        let resolved_line = if detail_line.is_none() {
529            if let (Some(client), Some(git_url)) = (&client, binding.git_url.as_deref()) {
530                client
531                    .resolve_remote(git_url)
532                    .await
533                    .ok()
534                    .flatten()
535                    .map(|r| {
536                        crate::resolution::codebase_line(
537                            r.name.as_deref(),
538                            &r.normalized_url,
539                            &r.clone_status,
540                        )
541                    })
542            } else {
543                None
544            }
545        } else {
546            None
547        };
548        if let Some(line) = crate::resolution::pick_status_line(
549            detail_line,
550            resolved_line,
551            binding.codebase_name.as_deref(),
552        ) {
553            println!("{line}");
554        }
555    }
556
557    // Surface a configured user default even when a more specific tier won, so
558    // it's discoverable (avoids double-printing when it IS the winning tier).
559    let default_is_effective = matches!(
560        effective.as_ref().map(|(_, s)| *s),
561        Some(BindingSource::UserDefault)
562    );
563    if let Some(ud) = &user_default {
564        if !default_is_effective {
565            println!("user default: repo {}", ud.repo_id);
566        }
567    }
568    Ok(())
569}
570
571#[cfg(test)]
572mod tests {
573    use super::*;
574    use std::io::{BufRead, BufReader, Write};
575    use std::net::TcpListener;
576    use std::thread;
577
578    #[test]
579    fn resolve_session_id_prefers_explicit() {
580        assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
581    }
582
583    #[test]
584    fn resolve_session_id_errors_when_absent() {
585        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
586        let mut guard = crate::test_helpers::EnvVarGuard::new();
587        guard.remove("TRACEVAULT_SESSION_ID");
588        guard.remove("AMP_CURRENT_THREAD_ID");
589        assert!(resolve_session_id(None).is_err());
590    }
591
592    /// In Amp's shell the plugin cannot export `TRACEVAULT_SESSION_ID`, but
593    /// Amp sets `AMP_CURRENT_THREAD_ID`, and the thread id is the session id
594    /// (VIS-1199), so `repo switch` / `status` find the session unaided.
595    #[test]
596    fn resolve_session_id_falls_back_to_the_amp_thread() {
597        let _env_lock = crate::test_helpers::lock_env_mutation_sync();
598        let mut guard = crate::test_helpers::EnvVarGuard::new();
599        guard.remove("TRACEVAULT_SESSION_ID");
600        guard.set("AMP_CURRENT_THREAD_ID", "T-0123-abcd");
601        assert_eq!(resolve_session_id(None).unwrap(), "T-0123-abcd");
602        // The explicit flag and TRACEVAULT_SESSION_ID still win.
603        assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
604        guard.set("TRACEVAULT_SESSION_ID", "sess-env");
605        assert_eq!(resolve_session_id(None).unwrap(), "sess-env");
606        // An empty TRACEVAULT_SESSION_ID counts as unset.
607        guard.set("TRACEVAULT_SESSION_ID", "");
608        assert_eq!(resolve_session_id(None).unwrap(), "T-0123-abcd");
609    }
610
611    #[test]
612    fn switch_destination_user_flag_forces_user_default() {
613        assert!(matches!(
614            switch_destination(true, Some("sess-1".to_string())),
615            SwitchDest::UserDefault
616        ));
617        assert!(matches!(
618            switch_destination(true, None),
619            SwitchDest::UserDefault
620        ));
621    }
622
623    #[test]
624    fn switch_destination_session_when_present_and_no_user_flag() {
625        assert!(matches!(
626            switch_destination(false, Some("sess-1".to_string())),
627            SwitchDest::Session(id) if id == "sess-1"
628        ));
629    }
630
631    #[test]
632    fn switch_destination_user_default_when_no_session() {
633        assert!(matches!(
634            switch_destination(false, None),
635            SwitchDest::UserDefault
636        ));
637    }
638
639    #[test]
640    fn switch_target_rejects_neither() {
641        assert!(switch_target(None, None).is_err());
642    }
643
644    // The clap `ArgGroup` on `Switch` already prevents both being given
645    // together, but as a safety net at this level path wins: a non-empty
646    // path resolves the target regardless of a (deprecated) --name.
647    #[test]
648    fn switch_target_path_wins_when_both_given() {
649        assert!(matches!(
650            switch_target(Some("/p"), Some("x")),
651            Ok(SwitchTarget::Path("/p"))
652        ));
653    }
654
655    #[test]
656    fn switch_target_accepts_path_only() {
657        assert!(matches!(
658            switch_target(Some("/p"), None),
659            Ok(SwitchTarget::Path("/p"))
660        ));
661    }
662
663    // --name now warns and does NOT resolve by name: switch_target maps a name-only
664    // invocation to a deprecation error directing to path binding (no list_repos call).
665    #[test]
666    fn switch_target_name_is_deprecated() {
667        let err = switch_target(None, Some("some-repo"))
668            .unwrap_err()
669            .to_string();
670        assert!(err.contains("deprecated"), "got: {err}");
671        assert!(err.contains("path"), "should direct to path binding: {err}");
672    }
673
674    fn binding(id: &str) -> RepoBinding {
675        RepoBinding {
676            repo_id: id.into(),
677            git_url: None,
678            remote_id: None,
679            codebase_name: None,
680            updated_at: "t".into(),
681        }
682    }
683
684    #[test]
685    fn apply_switch_sets_session_active() {
686        let mut state = SessionState::default();
687        apply_switch(&mut state, binding("new-repo"));
688        assert_eq!(state.active.unwrap().repo_id, "new-repo");
689    }
690
691    #[test]
692    fn apply_reset_clears_active_and_subagents() {
693        let mut state = SessionState {
694            active: Some(binding("r")),
695            subagents: std::collections::HashMap::from([("/wt/a".to_string(), binding("r2"))]),
696            storage_root: Some("/umbrella".into()),
697            ..Default::default()
698        };
699        apply_reset(&mut state);
700        assert_eq!(
701            state,
702            SessionState {
703                auto_bind_off: true,
704                storage_root: Some("/umbrella".into()),
705                ..SessionState::default()
706            }
707        );
708    }
709
710    #[test]
711    fn apply_switch_overwrites_existing_active() {
712        let mut state = SessionState {
713            active: Some(binding("old-repo")),
714            subagents: Default::default(),
715            ..Default::default()
716        };
717        apply_switch(&mut state, binding("new-repo"));
718        assert_eq!(state.active.unwrap().repo_id, "new-repo");
719    }
720
721    #[test]
722    fn format_status_none() {
723        assert_eq!(
724            format_status(None),
725            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)"
726        );
727    }
728
729    #[test]
730    fn format_status_repo_flag() {
731        let b = binding("r1");
732        assert_eq!(
733            format_status(Some((&b, BindingSource::RepoFlag))),
734            "bound to repo r1 via --path override"
735        );
736    }
737
738    #[test]
739    fn format_status_subagent() {
740        let b = binding("r2");
741        assert_eq!(
742            format_status(Some((&b, BindingSource::Subagent))),
743            "bound to repo r2 via subagent worktree override"
744        );
745    }
746
747    #[test]
748    fn format_status_session_active() {
749        let b = binding("r3");
750        assert_eq!(
751            format_status(Some((&b, BindingSource::SessionActive))),
752            "bound to repo r3 via session (repo switch)"
753        );
754    }
755
756    #[test]
757    fn format_status_bound() {
758        let b = binding("r4");
759        assert_eq!(
760            format_status(Some((&b, BindingSource::Bound))),
761            "bound to repo r4 via bound .visdom/tracing.toml"
762        );
763    }
764
765    #[test]
766    fn format_status_user_default() {
767        let b = binding("r5");
768        assert_eq!(
769            format_status(Some((&b, BindingSource::UserDefault))),
770            "bound to repo r5 via user default (repo switch --user)"
771        );
772    }
773
774    fn add_origin_remote(dir: &std::path::Path, url: &str) {
775        let ok = std::process::Command::new("git")
776            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
777            .status()
778            .expect("git remote add failed")
779            .success();
780        assert!(ok, "git remote add must succeed");
781    }
782
783    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
784    /// request it accepts (mirrors `tests/resolve_repo_test.rs`).
785    fn spawn_once(response: &'static str) -> String {
786        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
787        let addr = listener.local_addr().unwrap();
788        thread::spawn(move || {
789            if let Ok((stream, _)) = listener.accept() {
790                let mut reader = BufReader::new(stream);
791                let mut request_line = String::new();
792                let _ = reader.read_line(&mut request_line);
793                let mut stream = reader.into_inner();
794                let _ = stream.write_all(response.as_bytes());
795                let _ = stream.flush();
796            }
797        });
798        format!("http://{addr}")
799    }
800
801    /// Format a raw HTTP/1.1 200 response with a correct `Content-Length` for
802    /// a JSON `body`.
803    fn http_200(body: &str) -> String {
804        format!(
805            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
806            body.len(),
807            body
808        )
809    }
810
811    /// Generalizes `spawn_once` to a listener that answers each of `responses`
812    /// in order, one per accepted connection (the resolve-by-remote flow makes
813    /// two requests: `resolve_remote` then `get_remote_repos`).
814    fn spawn_n(responses: Vec<String>) -> String {
815        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
816        let addr = listener.local_addr().unwrap();
817        thread::spawn(move || {
818            for response in responses {
819                let response: &'static str = Box::leak(response.into_boxed_str());
820                if let Ok((stream, _)) = listener.accept() {
821                    let mut reader = BufReader::new(stream);
822                    let mut request_line = String::new();
823                    let _ = reader.read_line(&mut request_line);
824                    let mut stream = reader.into_inner();
825                    let _ = stream.write_all(response.as_bytes());
826                    let _ = stream.flush();
827                }
828            }
829        });
830        format!("http://{addr}")
831    }
832
833    #[tokio::test]
834    async fn resolve_switch_codebase_ok_for_registered_repo() {
835        // Path resolution now goes through the codebase (remote) resolver:
836        // resolve_remote finds the codebase, then get_remote_repos returns its
837        // linked repos — the switch binds to the first one.
838        let tmp = tempfile::tempdir().unwrap();
839        crate::test_helpers::init_git_repo(tmp.path());
840        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
841
842        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
843        let repo_id = "11111111-1111-4111-8111-111111111111";
844        let remote = format!(
845            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
846        );
847        let detail = format!(
848            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":"{repo_id}","name":"repo"}}]}}"#
849        );
850        let base = spawn_n(vec![http_200(&remote), http_200(&detail)]);
851        let client = ApiClient::new(&base, Some("tok"));
852
853        let codebase = resolve_switch_codebase(tmp.path(), &client)
854            .await
855            .expect("expected Ok codebase");
856        let got = codebase.binding(pick_switch_repo(&codebase, None, &[]).unwrap().0);
857        assert_eq!(got.repo_id, repo_id);
858        assert_eq!(got.remote_id, Some(remote_id.parse().unwrap()));
859        assert_eq!(got.codebase_name.as_deref(), Some("repo"));
860    }
861
862    #[tokio::test]
863    async fn resolve_switch_codebase_errors_for_unregistered_repo() {
864        let tmp = tempfile::tempdir().unwrap();
865        crate::test_helpers::init_git_repo(tmp.path());
866        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
867
868        // A genuine domain 404 carries the server's JSON error envelope
869        // (`{"error": "..."}` — what every `AppError` renders), which is
870        // what distinguishes "not tracked" from a bare route-404 (see
871        // `ApiClient::resolve_remote`).
872        let body = r#"{"error":"No remote for that URL"}"#;
873        let resp = format!(
874            "HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
875            body.len(), body
876        );
877        let base = spawn_once(Box::leak(resp.into_boxed_str()));
878        let client = ApiClient::new(&base, Some("tok"));
879
880        let err = resolve_switch_codebase(tmp.path(), &client)
881            .await
882            .expect_err("expected Err for unregistered repo");
883        assert!(
884            err.to_string().contains("not registered"),
885            "unexpected error message: {err}"
886        );
887    }
888
889    #[tokio::test]
890    async fn resolve_switch_codebase_flags_bare_404_as_version_skew() {
891        // A bare 404 (no JSON error body) is axum's "no route matched"
892        // fallback — the shape an old server sends for a route it doesn't
893        // have yet. `repo switch` must not misreport this as "not
894        // registered"; it should surface a diagnosable version-mismatch
895        // error instead.
896        let tmp = tempfile::tempdir().unwrap();
897        crate::test_helpers::init_git_repo(tmp.path());
898        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
899
900        let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
901        let base = spawn_once(resp);
902        let client = ApiClient::new(&base, Some("tok"));
903
904        let err = resolve_switch_codebase(tmp.path(), &client)
905            .await
906            .expect_err("expected Err for a bare route-404");
907        assert!(
908            !err.to_string().contains("not registered"),
909            "must not be misreported as 'not registered'; got: {err}"
910        );
911        assert!(
912            err.to_string().to_lowercase().contains("version mismatch"),
913            "expected a version-mismatch hint; got: {err}"
914        );
915    }
916
917    #[test]
918    fn switch_target_rejects_empty_name() {
919        // `--name` is deprecated outright, so there's no separate empty-name
920        // branch anymore — an empty name still hits the deprecation error.
921        assert!(switch_target(None, Some("")).is_err());
922        assert!(switch_target(None, Some("   ")).is_err());
923        let err = switch_target(None, Some(" ")).unwrap_err().to_string();
924        assert!(err.contains("deprecated"), "got: {err}");
925    }
926
927    #[test]
928    fn switch_target_rejects_empty_path() {
929        assert!(switch_target(Some(""), None).is_err());
930        assert!(switch_target(Some("   "), None).is_err());
931        let err = switch_target(Some(" "), None).unwrap_err().to_string();
932        assert!(err.contains("must not be empty"), "got: {err}");
933    }
934
935    // repo switch resolves by NORMALIZED url: origin spelling differs from what
936    // was registered, but resolve_remote matches, and we bind to a linked repo.
937    #[tokio::test]
938    async fn resolve_path_binds_via_remote_across_url_spelling() {
939        let tmp = tempfile::tempdir().unwrap();
940        crate::test_helpers::init_git_repo(tmp.path());
941        add_origin_remote(tmp.path(), "git@github.com:o/x.git"); // scp spelling
942        let remote = r#"{"remote_id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_status":"ready"}"#;
943        let detail = r#"{"id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_url":"https://github.com/o/x.git","clone_status":"ready","clone_error":null,"last_fetched_at":null,"repo_count":1,"created_at":"2026-01-01T00:00:00Z","repos":[{"id":"11111111-1111-4111-8111-111111111111","name":"x"}]}"#;
944        let base = spawn_n(vec![http_200(remote), http_200(detail)]);
945        let client = ApiClient::new(&base, Some("tok"));
946        let b = resolve_path_to_binding(tmp.path(), &client)
947            .await
948            .unwrap()
949            .expect("Some binding");
950        assert_eq!(b.repo_id, "11111111-1111-4111-8111-111111111111");
951        assert_eq!(
952            b.remote_id,
953            Some("44000761-8d22-4256-bd2c-27a0ba278c6f".parse().unwrap())
954        );
955        assert_eq!(b.codebase_name.as_deref(), Some("x"));
956    }
957
958    // A tracked codebase with no linked repos (bare remote) → explicit error.
959    #[tokio::test]
960    async fn resolve_path_bare_remote_errors() {
961        let tmp = tempfile::tempdir().unwrap();
962        crate::test_helpers::init_git_repo(tmp.path());
963        add_origin_remote(tmp.path(), "git@github.com:o/x.git");
964        let remote = r#"{"remote_id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_status":"pending"}"#;
965        let detail = r#"{"id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_url":"https://github.com/o/x.git","clone_status":"pending","clone_error":null,"last_fetched_at":null,"repo_count":0,"created_at":"2026-01-01T00:00:00Z","repos":[]}"#;
966        let base = spawn_n(vec![http_200(remote), http_200(detail)]);
967        let client = ApiClient::new(&base, Some("tok"));
968        let err = resolve_path_to_binding(tmp.path(), &client)
969            .await
970            .unwrap_err()
971            .to_string();
972        assert!(err.contains("no tracked repo"), "got: {err}");
973    }
974
975    // ── VIS-1018: several repo records for one codebase ───────────────────────
976
977    const LOW: &str = "44000761-0000-4000-8000-000000000001";
978    const HIGH: &str = "7995d35d-0000-4000-8000-000000000002";
979
980    fn codebase_with(repo_ids: &[&str]) -> ResolvedCodebase {
981        ResolvedCodebase {
982            git_url: "git@github.com:org/repo.git".into(),
983            remote: crate::api_client::ResolveRemoteResponse {
984                remote_id: uuid::Uuid::from_u128(7),
985                name: Some("repo".into()),
986                normalized_url: "github.com/org/repo".into(),
987                clone_status: "ready".into(),
988            },
989            repos: repo_ids
990                .iter()
991                .enumerate()
992                .map(|(i, id)| crate::api_client::RemoteRepoRef {
993                    id: id.parse().unwrap(),
994                    name: format!("repo-{i}"),
995                })
996                .collect(),
997        }
998    }
999
1000    fn in_use(repo_id: &str, source: &str) -> InUse {
1001        InUse {
1002            repo_id: repo_id.parse().unwrap(),
1003            source: source.into(),
1004        }
1005    }
1006
1007    /// The prod split: the session streamed to the higher-id repo (its
1008    /// config.toml binding); a switch to the same checkout must keep it, not
1009    /// move the session to the lowest id.
1010    #[test]
1011    fn switch_keeps_the_current_binding_over_the_lowest_id() {
1012        let codebase = codebase_with(&[LOW, HIGH]);
1013        let (id, kept) =
1014            pick_switch_repo(&codebase, None, &[in_use(HIGH, "the current binding")]).unwrap();
1015        assert_eq!(id.to_string(), HIGH);
1016        assert_eq!(kept.as_deref(), Some("the current binding"));
1017    }
1018
1019    /// The current binding outranks a checkout's config.toml.
1020    #[test]
1021    fn switch_prefers_the_current_binding_over_a_checkout_config() {
1022        let codebase = codebase_with(&[LOW, HIGH]);
1023        let (id, _) = pick_switch_repo(
1024            &codebase,
1025            None,
1026            &[
1027                in_use(LOW, "the current binding"),
1028                in_use(HIGH, "tracing.toml"),
1029            ],
1030        )
1031        .unwrap();
1032        assert_eq!(id.to_string(), LOW);
1033    }
1034
1035    /// A current binding to another codebase says nothing about this one:
1036    /// the next in-use repo that this codebase links decides.
1037    #[test]
1038    fn switch_skips_in_use_repos_of_other_codebases() {
1039        let codebase = codebase_with(&[LOW, HIGH]);
1040        let other = "99999999-0000-4000-8000-000000000009";
1041        let (id, kept) = pick_switch_repo(
1042            &codebase,
1043            None,
1044            &[
1045                in_use(other, "the current binding"),
1046                in_use(HIGH, "tracing.toml"),
1047            ],
1048        )
1049        .unwrap();
1050        assert_eq!(id.to_string(), HIGH);
1051        assert_eq!(kept.as_deref(), Some("tracing.toml"));
1052    }
1053
1054    /// Several repos and none in use: an error naming them, never a guess.
1055    #[test]
1056    fn switch_reports_ambiguity_instead_of_picking() {
1057        let codebase = codebase_with(&[LOW, HIGH]);
1058        let err = pick_switch_repo(&codebase, None, &[])
1059            .unwrap_err()
1060            .to_string();
1061        assert!(err.contains(LOW) && err.contains(HIGH), "got: {err}");
1062        assert!(err.contains("--repo-id"), "got: {err}");
1063    }
1064
1065    /// `--repo-id` is the explicit choice, also against the current binding.
1066    #[test]
1067    fn switch_repo_id_flag_overrides_the_current_binding() {
1068        let codebase = codebase_with(&[LOW, HIGH]);
1069        let (id, kept) = pick_switch_repo(
1070            &codebase,
1071            Some(LOW.parse().unwrap()),
1072            &[in_use(HIGH, "the current binding")],
1073        )
1074        .unwrap();
1075        assert_eq!(id.to_string(), LOW);
1076        assert_eq!(kept, None);
1077    }
1078
1079    #[test]
1080    fn switch_repo_id_flag_must_name_a_repo_of_the_codebase() {
1081        let codebase = codebase_with(&[LOW, HIGH]);
1082        let other = "99999999-0000-4000-8000-000000000009";
1083        let err = pick_switch_repo(&codebase, Some(other.parse().unwrap()), &[])
1084            .unwrap_err()
1085            .to_string();
1086        assert!(err.contains("is not a repo of codebase"), "got: {err}");
1087    }
1088
1089    /// One repo: nothing to choose, whatever is in use elsewhere.
1090    #[test]
1091    fn switch_binds_the_only_repo() {
1092        let codebase = codebase_with(&[LOW]);
1093        let other = "99999999-0000-4000-8000-000000000009";
1094        let (id, kept) =
1095            pick_switch_repo(&codebase, None, &[in_use(other, "the current binding")]).unwrap();
1096        assert_eq!(id.to_string(), LOW);
1097        assert_eq!(kept, None);
1098    }
1099
1100    /// `resolve_path_to_binding` (used by `check` and `repo status --path`)
1101    /// picks the repo the checkout's own config.toml binds — the one its hooks
1102    /// stream to — rather than the lowest id.
1103    #[tokio::test]
1104    async fn resolve_path_prefers_the_checkout_config_repo() {
1105        let tmp = tempfile::tempdir().unwrap();
1106        crate::test_helpers::init_git_repo(tmp.path());
1107        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
1108        std::fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
1109        std::fs::write(
1110            tmp.path().join(".visdom/tracing.toml"),
1111            format!("repo_id = \"{HIGH}\"\n"),
1112        )
1113        .unwrap();
1114        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
1115        let remote = format!(
1116            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
1117        );
1118        let detail = format!(
1119            r#"{{"name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{{"id":"{LOW}","name":"tracevault"}},{{"id":"{HIGH}","name":"tracing"}}]}}"#
1120        );
1121        let base = spawn_n(vec![http_200(&remote), http_200(&detail)]);
1122        let client = ApiClient::new(&base, Some("tok"));
1123
1124        let got = resolve_path_to_binding(tmp.path(), &client)
1125            .await
1126            .unwrap()
1127            .expect("registered");
1128        assert_eq!(got.repo_id, HIGH);
1129    }
1130
1131    // ── in_use_repos: what switch keeps, read from real state ─────────────────
1132
1133    const TARGET_CFG: &str = "c0000000-0000-4000-8000-00000000000c";
1134    const CWD_CFG: &str = "b0000000-0000-4000-8000-00000000000b";
1135    const ACTIVE: &str = "a0000000-0000-4000-8000-00000000000a";
1136    const USER: &str = "d0000000-0000-4000-8000-00000000000d";
1137
1138    /// A git checkout whose `.visdom/tracing.toml` binds `repo_id`.
1139    fn checkout_bound_to(repo_id: &str) -> tempfile::TempDir {
1140        let dir = tempfile::tempdir().unwrap();
1141        crate::test_helpers::init_git_repo(dir.path());
1142        std::fs::create_dir_all(dir.path().join(".visdom")).unwrap();
1143        std::fs::write(
1144            dir.path().join(".visdom/tracing.toml"),
1145            format!("repo_id = \"{repo_id}\"\n"),
1146        )
1147        .unwrap();
1148        dir
1149    }
1150
1151    fn ids(in_use: &[InUse]) -> Vec<String> {
1152        in_use.iter().map(|u| u.repo_id.to_string()).collect()
1153    }
1154
1155    /// Session destination: the session's own binding first, then the target
1156    /// checkout's config, then this checkout's.
1157    #[tokio::test]
1158    async fn in_use_puts_the_session_binding_first() {
1159        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1160        let home = tempfile::tempdir().unwrap();
1161        let mut guard = crate::test_helpers::EnvVarGuard::new();
1162        guard.set("XDG_STATE_HOME", home.path());
1163        guard.set("XDG_CONFIG_HOME", home.path());
1164        let target = checkout_bound_to(TARGET_CFG);
1165        let cwd = checkout_bound_to(CWD_CFG);
1166        let state = SessionState {
1167            active: Some(binding(ACTIVE)),
1168            ..Default::default()
1169        };
1170        session_state::save("sess-inuse", &state).unwrap();
1171
1172        let got = in_use_repos(
1173            &SwitchDest::Session("sess-inuse".into()),
1174            target.path(),
1175            cwd.path(),
1176        );
1177
1178        assert_eq!(ids(&got), [ACTIVE, TARGET_CFG, CWD_CFG]);
1179    }
1180
1181    /// A session without its own binding streams to this checkout's
1182    /// config.toml, so that is its current binding.
1183    #[tokio::test]
1184    async fn in_use_falls_back_to_what_the_session_streams_to() {
1185        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1186        let home = tempfile::tempdir().unwrap();
1187        let mut guard = crate::test_helpers::EnvVarGuard::new();
1188        guard.set("XDG_STATE_HOME", home.path());
1189        guard.set("XDG_CONFIG_HOME", home.path());
1190        let target = checkout_bound_to(TARGET_CFG);
1191        let cwd = checkout_bound_to(CWD_CFG);
1192
1193        let got = in_use_repos(
1194            &SwitchDest::Session("sess-unbound".into()),
1195            target.path(),
1196            cwd.path(),
1197        );
1198
1199        assert_eq!(ids(&got)[0], CWD_CFG);
1200        assert!(
1201            got[0].source.contains("current binding"),
1202            "{}",
1203            got[0].source
1204        );
1205    }
1206
1207    /// `--user`: the current user default comes first, not any session.
1208    #[tokio::test]
1209    async fn in_use_for_the_user_default_starts_with_the_user_default() {
1210        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1211        let home = tempfile::tempdir().unwrap();
1212        let mut guard = crate::test_helpers::EnvVarGuard::new();
1213        guard.set("XDG_STATE_HOME", home.path());
1214        guard.set("XDG_CONFIG_HOME", home.path());
1215        crate::user_default::save(&binding(USER)).unwrap();
1216        let target = checkout_bound_to(TARGET_CFG);
1217        let cwd = checkout_bound_to(CWD_CFG);
1218
1219        let got = in_use_repos(&SwitchDest::UserDefault, target.path(), cwd.path());
1220
1221        assert_eq!(ids(&got), [USER, TARGET_CFG, CWD_CFG]);
1222    }
1223
1224    /// End to end: an ambiguous codebase fails the switch and leaves the
1225    /// session's binding as it was.
1226    #[tokio::test]
1227    async fn ambiguous_switch_leaves_the_session_binding_unchanged() {
1228        let _env_lock = crate::test_helpers::lock_env_mutation().await;
1229        let home = tempfile::tempdir().unwrap();
1230        let other = "99999999-0000-4000-8000-000000000009";
1231        let state = SessionState {
1232            active: Some(binding(other)),
1233            ..Default::default()
1234        };
1235        let target = tempfile::tempdir().unwrap();
1236        crate::test_helpers::init_git_repo(target.path());
1237        add_origin_remote(target.path(), "git@github.com:org/repo.git");
1238        let remote = r#"{"remote_id":"2280a1c9-0000-4000-8000-000000000003","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}"#;
1239        let detail = format!(
1240            r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{{"id":"{LOW}","name":"tracevault"}},{{"id":"{HIGH}","name":"tracing"}}]}}"#
1241        );
1242        let base = spawn_n(vec![http_200(remote), http_200(&detail)]);
1243        let mut guard = crate::test_helpers::EnvVarGuard::new();
1244        guard.set("XDG_STATE_HOME", home.path());
1245        guard.set("XDG_CONFIG_HOME", home.path());
1246        guard.set("TRACEVAULT_SERVER_URL", &base);
1247        guard.set("TRACEVAULT_API_KEY", "tok");
1248        session_state::save("sess-ambiguous", &state).unwrap();
1249
1250        let err = switch(
1251            Some(&target.path().to_string_lossy()),
1252            None,
1253            None,
1254            false,
1255            Some("sess-ambiguous"),
1256            home.path(),
1257        )
1258        .await
1259        .unwrap_err();
1260
1261        assert!(err.to_string().contains("--repo-id"), "got: {err}");
1262        assert_eq!(session_state::load("sess-ambiguous"), state);
1263    }
1264}