Skip to main content

tracevault_cli/commands/
repo.rs

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