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, resolve_credentials, ApiClient};
6use crate::resolution::{
7    binding_from_config, effective_binding, resolve_path_to_binding, BindingSource, ResolveInputs,
8};
9use crate::session_state::{self, RepoBinding, SessionState};
10
11/// Sub-actions for `tracevault repo` (workspace/detached mode).
12#[derive(clap::Subcommand)]
13pub enum RepoCmd {
14    /// Bind tracing to a registered repo for the current session and print its
15    /// policies. Give a checkout <path> — `--name` is deprecated and always
16    /// errors, telling you to bind by path instead.
17    #[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
18    Switch {
19        /// Path to a checkout of a registered repo (resolves via its git origin remote).
20        #[arg(group = "target")]
21        path: Option<String>,
22        /// Deprecated: name-only binding is no longer supported and always
23        /// errors; bind by checkout path instead (`tracevault repo switch <path>`).
24        #[arg(long, group = "target")]
25        name: Option<String>,
26        /// Write a session-independent user-level default instead of a session
27        /// binding. Implied when no session id is available.
28        #[arg(long)]
29        user: bool,
30        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
31        #[arg(long)]
32        session_id: Option<String>,
33    },
34    /// Show the repo the current session is bound to.
35    Status {
36        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
37        #[arg(long)]
38        session_id: Option<String>,
39        /// One-off: resolve this checkout path instead of the session binding.
40        #[arg(long)]
41        path: Option<String>,
42    },
43    /// Clear the current session's binding, or (with --user) the user-level default.
44    Reset {
45        /// Clear the user-level default instead of the session binding.
46        #[arg(long)]
47        user: bool,
48        /// Session to target; defaults to $TRACEVAULT_SESSION_ID.
49        #[arg(long)]
50        session_id: Option<String>,
51    },
52}
53
54/// Resolve the current session id: the explicit flag wins, else
55/// `$TRACEVAULT_SESSION_ID` (set by the SessionStart hook of `init --global`).
56pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
57    if let Some(s) = explicit {
58        return Ok(s.to_string());
59    }
60    std::env::var("TRACEVAULT_SESSION_ID")
61        .ok()
62        .filter(|s| !s.is_empty())
63        .ok_or_else(|| {
64            "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
65             (installed by `tracevault init --global`)"
66                .into()
67        })
68}
69
70pub async fn run(
71    cmd: RepoCmd,
72    project_root: &Path,
73    cwd: &Path,
74) -> Result<(), Box<dyn std::error::Error>> {
75    match cmd {
76        RepoCmd::Status { session_id, path } => {
77            status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
78        }
79        RepoCmd::Switch {
80            path,
81            name,
82            user,
83            session_id,
84        } => {
85            switch(
86                path.as_deref(),
87                name.as_deref(),
88                user,
89                session_id.as_deref(),
90                project_root,
91            )
92            .await
93        }
94        RepoCmd::Reset { user, session_id } => reset(user, session_id.as_deref()),
95    }
96}
97
98/// Resolve a path to a binding for `repo switch`, turning "unregistered" into
99/// a clear error (switch should fail loudly, unlike the best-effort `--path`
100/// status override).
101async fn resolve_switch_binding(
102    path: &Path,
103    client: &ApiClient,
104) -> Result<RepoBinding, Box<dyn std::error::Error>> {
105    resolve_path_to_binding(path, client).await?.ok_or_else(|| {
106        format!(
107            "repo at {} is not registered with TraceVault; nothing to bind",
108            path.display()
109        )
110        .into()
111    })
112}
113
114/// Apply a switch to session state (session-level active binding). Pure.
115fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
116    state.active = Some(binding);
117}
118
119/// Clear the session's workspace binding (session-level reset). Pure.
120fn apply_reset(state: &mut SessionState) {
121    *state = SessionState::default();
122}
123
124fn reset(user: bool, session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
125    if user {
126        crate::user_default::clear()?;
127        println!("cleared user-level default repo binding");
128        return Ok(());
129    }
130    let id = resolve_session_id(session_id)?;
131    let mut state = session_state::load(&id);
132    apply_reset(&mut state);
133    session_state::save(&id, &state)?;
134    // NOTE: subagent worktree-scoped reset-to-parent is handled in sub-plan C.
135    println!("cleared workspace repo binding for session {id}");
136    Ok(())
137}
138
139/// Which target `repo switch` should resolve to a binding: a checkout path.
140/// `--name` binding is deprecated (see `switch_target`) and no longer
141/// produces a variant here.
142#[derive(Debug, PartialEq, Eq)]
143enum SwitchTarget<'a> {
144    Path(&'a str),
145}
146
147/// Pure guard for `repo switch`'s `<path>` / `--name` arguments. Kept
148/// separate from `switch` so it can be unit-tested without spinning up a
149/// server or session state (also a safety net if the clap `ArgGroup` on the
150/// `Switch` variant is ever loosened). `--name` binding is hard-deprecated:
151/// a name-only invocation errors rather than resolving by name, directing
152/// callers to bind by checkout path so the codebase is resolved from its git
153/// remote.
154fn switch_target<'a>(
155    path: Option<&'a str>,
156    name: Option<&'a str>,
157) -> Result<SwitchTarget<'a>, Box<dyn std::error::Error>> {
158    match (path, name) {
159        (Some(p), _) if !p.trim().is_empty() => Ok(SwitchTarget::Path(p)),
160        (Some(_), _) => Err("repo path must not be empty".into()),
161        (None, Some(_)) => Err(
162            "`--name` binding is deprecated and no longer supported; bind by checkout path \
163             (`tracevault repo switch <path>`) so the codebase is resolved from its git remote"
164                .into(),
165        ),
166        (None, None) => {
167            Err("provide a checkout path to bind (`tracevault repo switch <path>`)".into())
168        }
169    }
170}
171
172/// Where a `repo switch` should persist its binding: a specific session, or the
173/// session-independent user-level default.
174#[derive(Debug)]
175enum SwitchDest {
176    Session(String),
177    UserDefault,
178}
179
180/// Pure choice of write target for `repo switch`: `--user` (or the absence of
181/// any session id) selects the user-level default; otherwise the resolved
182/// session id selects a session binding. Kept pure so it's unit-testable.
183fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
184    if user {
185        return SwitchDest::UserDefault;
186    }
187    match session_id {
188        Some(id) => SwitchDest::Session(id),
189        None => SwitchDest::UserDefault,
190    }
191}
192
193async fn switch(
194    path: Option<&str>,
195    name: Option<&str>,
196    user: bool,
197    session_id: Option<&str>,
198    project_root: &Path,
199) -> Result<(), Box<dyn std::error::Error>> {
200    // Validate the target argument before any network work, so a bad/empty
201    // path or name surfaces as an argument error rather than an unrelated
202    // network error from the resolution step below.
203    let target = switch_target(path, name)?;
204
205    let client = resolve_client(project_root)?;
206
207    let binding = match target {
208        SwitchTarget::Path(p) => resolve_switch_binding(Path::new(p), &client).await?,
209    };
210
211    // Validate the repo id BEFORE persisting anything: a malformed repo_id must
212    // not leave a persisted binding behind.
213    let repo_uuid = binding.repo_id.parse::<uuid::Uuid>().map_err(|e| {
214        format!(
215            "server returned an invalid repo id {:?}: {e}",
216            binding.repo_id
217        )
218    })?;
219
220    // A session id is optional now: with one (and no --user) we bind that
221    // session; without one (or with --user) we set the user-level default,
222    // which any new session inherits. This is what lets a container bind its
223    // repo before Claude — and its session — exists.
224    let session = resolve_session_id(session_id).ok();
225    match switch_destination(user, session) {
226        SwitchDest::Session(id) => {
227            let mut state = session_state::load(&id);
228            apply_switch(&mut state, binding.clone());
229            session_state::save(&id, &state)?;
230            println!("bound session {id} to repo {}", binding.repo_id);
231        }
232        SwitchDest::UserDefault => {
233            crate::user_default::save(&binding)?;
234            println!(
235                "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)",
236                binding.repo_id
237            );
238        }
239    }
240
241    // Best-effort policy fetch (applies to either destination). A failure here
242    // must not make the whole command report as an error.
243    match client.get_agent_instructions(&repo_uuid).await {
244        Ok(policies) => println!("{}", policies.content),
245        Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
246    }
247    Ok(())
248}
249
250/// Resolve a `--path <path>` override into a live `RepoBinding`, if possible.
251/// Best-effort: prints a clear message and returns `None` on any failure
252/// (missing credentials, or a server error) rather than failing the whole
253/// `status` inspector.
254async fn resolve_repo_flag(
255    repo_flag_path: Option<&str>,
256    project_root: &Path,
257) -> Option<RepoBinding> {
258    let path = repo_flag_path?;
259
260    let (server_url, token) = resolve_credentials(project_root);
261    let Some(server_url) = server_url else {
262        eprintln!(
263            "--path {path}: no server URL configured (run `tracevault login`); showing binding \
264             without the --path override"
265        );
266        return None;
267    };
268
269    let client = ApiClient::new(&server_url, token.as_deref());
270    match resolve_path_to_binding(Path::new(path), &client).await {
271        Ok(Some(binding)) => Some(binding),
272        Ok(None) => {
273            eprintln!(
274                "--path {path}: no registered repo found for this path's git remote; showing \
275                 binding without the --path override"
276            );
277            None
278        }
279        Err(e) => {
280            eprintln!(
281                "--path {path}: failed to resolve ({e}); showing binding without the --path \
282                 override"
283            );
284            None
285        }
286    }
287}
288
289/// Pure formatter for `repo status`'s output: which repo is bound, and via
290/// which precedence tier. Kept separate from I/O so it can be unit-tested.
291fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
292    match binding {
293        Some((b, source)) => format!("bound to repo {} via {source}", b.repo_id),
294        None => {
295            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)".into()
296        }
297    }
298}
299
300async fn status(
301    session_id: Option<&str>,
302    repo_flag_path: Option<&str>,
303    project_root: &Path,
304    cwd: &Path,
305) -> Result<(), Box<dyn std::error::Error>> {
306    // Session state is best-effort: if a session id resolves, load it; else
307    // warn and fall back to an empty SessionState rather than silently
308    // reporting "not bound" without the user knowing why.
309    let session = match resolve_session_id(session_id) {
310        Ok(id) => session_state::load(&id),
311        Err(_) => {
312            eprintln!(
313                "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
314                 showing binding without session context"
315            );
316            SessionState::default()
317        }
318    };
319    let worktree = crate::paths::worktree_toplevel(cwd);
320    let bound = crate::config::TracevaultConfig::load(project_root)
321        .as_ref()
322        .and_then(binding_from_config);
323
324    // A --path override on status resolves live (needs the server).
325    let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;
326
327    let user_default = crate::user_default::load();
328
329    let effective = effective_binding(ResolveInputs {
330        repo_flag,
331        session: &session,
332        worktree_path: Some(&worktree),
333        bound,
334        user_default: user_default.clone(),
335    });
336    println!(
337        "{}",
338        format_status(effective.as_ref().map(|(b, s)| (b, *s)))
339    );
340
341    // Surface which codebase the effective binding belongs to, with live clone
342    // status when reachable. Best-effort — a failure must not fail `status`:
343    //   1. `remote_id` (persisted at init / set by switch) → fetch the remote
344    //      detail for name + clone status (works without a checkout);
345    //   2. else a `git_url` → live `resolve_remote` for name + clone status;
346    //   3. else fall back to the cached `codebase_name` (name only, offline).
347    if let Some((binding, _)) = &effective {
348        let (server_url, token) = resolve_credentials(project_root);
349        let client = server_url
350            .as_ref()
351            .map(|su| ApiClient::new(su, token.as_deref()));
352        let detail_line = if let (Some(client), Some(remote_id)) = (&client, binding.remote_id) {
353            client.get_remote_detail(remote_id).await.ok().map(|d| {
354                crate::resolution::codebase_line(
355                    d.name.as_deref(),
356                    &d.normalized_url,
357                    &d.clone_status,
358                )
359            })
360        } else {
361            None
362        };
363        let resolved_line = if detail_line.is_none() {
364            if let (Some(client), Some(git_url)) = (&client, binding.git_url.as_deref()) {
365                client
366                    .resolve_remote(git_url)
367                    .await
368                    .ok()
369                    .flatten()
370                    .map(|r| {
371                        crate::resolution::codebase_line(
372                            r.name.as_deref(),
373                            &r.normalized_url,
374                            &r.clone_status,
375                        )
376                    })
377            } else {
378                None
379            }
380        } else {
381            None
382        };
383        if let Some(line) = crate::resolution::pick_status_line(
384            detail_line,
385            resolved_line,
386            binding.codebase_name.as_deref(),
387        ) {
388            println!("{line}");
389        }
390    }
391
392    // Surface a configured user default even when a more specific tier won, so
393    // it's discoverable (avoids double-printing when it IS the winning tier).
394    let default_is_effective = matches!(
395        effective.as_ref().map(|(_, s)| *s),
396        Some(BindingSource::UserDefault)
397    );
398    if let Some(ud) = &user_default {
399        if !default_is_effective {
400            println!("user default: repo {}", ud.repo_id);
401        }
402    }
403    Ok(())
404}
405
406#[cfg(test)]
407mod tests {
408    use super::*;
409    use std::io::{BufRead, BufReader, Write};
410    use std::net::TcpListener;
411    use std::thread;
412
413    #[test]
414    fn resolve_session_id_prefers_explicit() {
415        assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
416    }
417
418    #[test]
419    fn resolve_session_id_errors_when_absent() {
420        // No explicit id and (in this test process) no env var set → error.
421        // Guard against a leaked env var from another test by checking the
422        // message only when the var is genuinely absent.
423        if std::env::var("TRACEVAULT_SESSION_ID").is_err() {
424            assert!(resolve_session_id(None).is_err());
425        }
426    }
427
428    #[test]
429    fn switch_destination_user_flag_forces_user_default() {
430        assert!(matches!(
431            switch_destination(true, Some("sess-1".to_string())),
432            SwitchDest::UserDefault
433        ));
434        assert!(matches!(
435            switch_destination(true, None),
436            SwitchDest::UserDefault
437        ));
438    }
439
440    #[test]
441    fn switch_destination_session_when_present_and_no_user_flag() {
442        assert!(matches!(
443            switch_destination(false, Some("sess-1".to_string())),
444            SwitchDest::Session(id) if id == "sess-1"
445        ));
446    }
447
448    #[test]
449    fn switch_destination_user_default_when_no_session() {
450        assert!(matches!(
451            switch_destination(false, None),
452            SwitchDest::UserDefault
453        ));
454    }
455
456    #[test]
457    fn switch_target_rejects_neither() {
458        assert!(switch_target(None, None).is_err());
459    }
460
461    // The clap `ArgGroup` on `Switch` already prevents both being given
462    // together, but as a safety net at this level path wins: a non-empty
463    // path resolves the target regardless of a (deprecated) --name.
464    #[test]
465    fn switch_target_path_wins_when_both_given() {
466        assert!(matches!(
467            switch_target(Some("/p"), Some("x")),
468            Ok(SwitchTarget::Path("/p"))
469        ));
470    }
471
472    #[test]
473    fn switch_target_accepts_path_only() {
474        assert!(matches!(
475            switch_target(Some("/p"), None),
476            Ok(SwitchTarget::Path("/p"))
477        ));
478    }
479
480    // --name now warns and does NOT resolve by name: switch_target maps a name-only
481    // invocation to a deprecation error directing to path binding (no list_repos call).
482    #[test]
483    fn switch_target_name_is_deprecated() {
484        let err = switch_target(None, Some("some-repo"))
485            .unwrap_err()
486            .to_string();
487        assert!(err.contains("deprecated"), "got: {err}");
488        assert!(err.contains("path"), "should direct to path binding: {err}");
489    }
490
491    fn binding(id: &str) -> RepoBinding {
492        RepoBinding {
493            repo_id: id.into(),
494            git_url: None,
495            remote_id: None,
496            codebase_name: None,
497            updated_at: "t".into(),
498        }
499    }
500
501    #[test]
502    fn apply_switch_sets_session_active() {
503        let mut state = SessionState::default();
504        apply_switch(&mut state, binding("new-repo"));
505        assert_eq!(state.active.unwrap().repo_id, "new-repo");
506    }
507
508    #[test]
509    fn apply_reset_clears_active_and_subagents() {
510        let mut state = SessionState {
511            active: Some(binding("r")),
512            subagents: std::collections::HashMap::from([("/wt/a".to_string(), binding("r2"))]),
513            ..Default::default()
514        };
515        apply_reset(&mut state);
516        assert_eq!(state, SessionState::default());
517    }
518
519    #[test]
520    fn apply_switch_overwrites_existing_active() {
521        let mut state = SessionState {
522            active: Some(binding("old-repo")),
523            subagents: Default::default(),
524            ..Default::default()
525        };
526        apply_switch(&mut state, binding("new-repo"));
527        assert_eq!(state.active.unwrap().repo_id, "new-repo");
528    }
529
530    #[test]
531    fn format_status_none() {
532        assert_eq!(
533            format_status(None),
534            "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)"
535        );
536    }
537
538    #[test]
539    fn format_status_repo_flag() {
540        let b = binding("r1");
541        assert_eq!(
542            format_status(Some((&b, BindingSource::RepoFlag))),
543            "bound to repo r1 via --path override"
544        );
545    }
546
547    #[test]
548    fn format_status_subagent() {
549        let b = binding("r2");
550        assert_eq!(
551            format_status(Some((&b, BindingSource::Subagent))),
552            "bound to repo r2 via subagent worktree override"
553        );
554    }
555
556    #[test]
557    fn format_status_session_active() {
558        let b = binding("r3");
559        assert_eq!(
560            format_status(Some((&b, BindingSource::SessionActive))),
561            "bound to repo r3 via session (repo switch)"
562        );
563    }
564
565    #[test]
566    fn format_status_bound() {
567        let b = binding("r4");
568        assert_eq!(
569            format_status(Some((&b, BindingSource::Bound))),
570            "bound to repo r4 via bound .tracevault/config.toml"
571        );
572    }
573
574    #[test]
575    fn format_status_user_default() {
576        let b = binding("r5");
577        assert_eq!(
578            format_status(Some((&b, BindingSource::UserDefault))),
579            "bound to repo r5 via user default (repo switch --user)"
580        );
581    }
582
583    fn add_origin_remote(dir: &std::path::Path, url: &str) {
584        let ok = std::process::Command::new("git")
585            .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
586            .status()
587            .expect("git remote add failed")
588            .success();
589        assert!(ok, "git remote add must succeed");
590    }
591
592    /// Spawn a one-shot raw-HTTP server that returns `response` to the first
593    /// request it accepts (mirrors `tests/resolve_repo_test.rs`).
594    fn spawn_once(response: &'static str) -> String {
595        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
596        let addr = listener.local_addr().unwrap();
597        thread::spawn(move || {
598            if let Ok((stream, _)) = listener.accept() {
599                let mut reader = BufReader::new(stream);
600                let mut request_line = String::new();
601                let _ = reader.read_line(&mut request_line);
602                let mut stream = reader.into_inner();
603                let _ = stream.write_all(response.as_bytes());
604                let _ = stream.flush();
605            }
606        });
607        format!("http://{addr}")
608    }
609
610    /// Format a raw HTTP/1.1 200 response with a correct `Content-Length` for
611    /// a JSON `body`.
612    fn http_200(body: &str) -> String {
613        format!(
614            "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
615            body.len(),
616            body
617        )
618    }
619
620    /// Generalizes `spawn_once` to a listener that answers each of `responses`
621    /// in order, one per accepted connection (the resolve-by-remote flow makes
622    /// two requests: `resolve_remote` then `get_remote_repos`).
623    fn spawn_n(responses: Vec<String>) -> String {
624        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
625        let addr = listener.local_addr().unwrap();
626        thread::spawn(move || {
627            for response in responses {
628                let response: &'static str = Box::leak(response.into_boxed_str());
629                if let Ok((stream, _)) = listener.accept() {
630                    let mut reader = BufReader::new(stream);
631                    let mut request_line = String::new();
632                    let _ = reader.read_line(&mut request_line);
633                    let mut stream = reader.into_inner();
634                    let _ = stream.write_all(response.as_bytes());
635                    let _ = stream.flush();
636                }
637            }
638        });
639        format!("http://{addr}")
640    }
641
642    #[tokio::test]
643    async fn resolve_switch_binding_ok_for_registered_repo() {
644        // Path resolution now goes through the codebase (remote) resolver:
645        // resolve_remote finds the codebase, then get_remote_repos returns its
646        // linked repos — the switch binds to the first one.
647        let tmp = tempfile::tempdir().unwrap();
648        crate::test_helpers::init_git_repo(tmp.path());
649        add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
650
651        let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
652        let repo_id = "11111111-1111-4111-8111-111111111111";
653        let remote = format!(
654            r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
655        );
656        let detail = format!(
657            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"}}]}}"#
658        );
659        let base = spawn_n(vec![http_200(&remote), http_200(&detail)]);
660        let client = ApiClient::new(&base, Some("tok"));
661
662        let got = resolve_switch_binding(tmp.path(), &client)
663            .await
664            .expect("expected Ok binding");
665        assert_eq!(got.repo_id, repo_id);
666        assert_eq!(got.remote_id, Some(remote_id.parse().unwrap()));
667        assert_eq!(got.codebase_name.as_deref(), Some("repo"));
668    }
669
670    #[tokio::test]
671    async fn resolve_switch_binding_errors_for_unregistered_repo() {
672        let tmp = tempfile::tempdir().unwrap();
673        crate::test_helpers::init_git_repo(tmp.path());
674        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
675
676        // A genuine domain 404 carries the server's JSON error envelope
677        // (`{"error": "..."}` — what every `AppError` renders), which is
678        // what distinguishes "not tracked" from a bare route-404 (see
679        // `ApiClient::resolve_remote`).
680        let body = r#"{"error":"No remote for that URL"}"#;
681        let resp = format!(
682            "HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
683            body.len(), body
684        );
685        let base = spawn_once(Box::leak(resp.into_boxed_str()));
686        let client = ApiClient::new(&base, Some("tok"));
687
688        let err = resolve_switch_binding(tmp.path(), &client)
689            .await
690            .expect_err("expected Err for unregistered repo");
691        assert!(
692            err.to_string().contains("not registered"),
693            "unexpected error message: {err}"
694        );
695    }
696
697    #[tokio::test]
698    async fn resolve_switch_binding_flags_bare_404_as_version_skew() {
699        // A bare 404 (no JSON error body) is axum's "no route matched"
700        // fallback — the shape an old server sends for a route it doesn't
701        // have yet. `repo switch` must not misreport this as "not
702        // registered"; it should surface a diagnosable version-mismatch
703        // error instead.
704        let tmp = tempfile::tempdir().unwrap();
705        crate::test_helpers::init_git_repo(tmp.path());
706        add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
707
708        let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
709        let base = spawn_once(resp);
710        let client = ApiClient::new(&base, Some("tok"));
711
712        let err = resolve_switch_binding(tmp.path(), &client)
713            .await
714            .expect_err("expected Err for a bare route-404");
715        assert!(
716            !err.to_string().contains("not registered"),
717            "must not be misreported as 'not registered'; got: {err}"
718        );
719        assert!(
720            err.to_string().to_lowercase().contains("version mismatch"),
721            "expected a version-mismatch hint; got: {err}"
722        );
723    }
724
725    #[test]
726    fn switch_target_rejects_empty_name() {
727        // `--name` is deprecated outright, so there's no separate empty-name
728        // branch anymore — an empty name still hits the deprecation error.
729        assert!(switch_target(None, Some("")).is_err());
730        assert!(switch_target(None, Some("   ")).is_err());
731        let err = switch_target(None, Some(" ")).unwrap_err().to_string();
732        assert!(err.contains("deprecated"), "got: {err}");
733    }
734
735    #[test]
736    fn switch_target_rejects_empty_path() {
737        assert!(switch_target(Some(""), None).is_err());
738        assert!(switch_target(Some("   "), None).is_err());
739        let err = switch_target(Some(" "), None).unwrap_err().to_string();
740        assert!(err.contains("must not be empty"), "got: {err}");
741    }
742
743    // repo switch resolves by NORMALIZED url: origin spelling differs from what
744    // was registered, but resolve_remote matches, and we bind to a linked repo.
745    #[tokio::test]
746    async fn resolve_path_binds_via_remote_across_url_spelling() {
747        let tmp = tempfile::tempdir().unwrap();
748        crate::test_helpers::init_git_repo(tmp.path());
749        add_origin_remote(tmp.path(), "git@github.com:o/x.git"); // scp spelling
750        let remote = r#"{"remote_id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_status":"ready"}"#;
751        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"}]}"#;
752        let base = spawn_n(vec![http_200(remote), http_200(detail)]);
753        let client = ApiClient::new(&base, Some("tok"));
754        let b = resolve_path_to_binding(tmp.path(), &client)
755            .await
756            .unwrap()
757            .expect("Some binding");
758        assert_eq!(b.repo_id, "11111111-1111-4111-8111-111111111111");
759        assert_eq!(
760            b.remote_id,
761            Some("44000761-8d22-4256-bd2c-27a0ba278c6f".parse().unwrap())
762        );
763        assert_eq!(b.codebase_name.as_deref(), Some("x"));
764    }
765
766    // A tracked codebase with no linked repos (bare remote) → explicit error.
767    #[tokio::test]
768    async fn resolve_path_bare_remote_errors() {
769        let tmp = tempfile::tempdir().unwrap();
770        crate::test_helpers::init_git_repo(tmp.path());
771        add_origin_remote(tmp.path(), "git@github.com:o/x.git");
772        let remote = r#"{"remote_id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_status":"pending"}"#;
773        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":[]}"#;
774        let base = spawn_n(vec![http_200(remote), http_200(detail)]);
775        let client = ApiClient::new(&base, Some("tok"));
776        let err = resolve_path_to_binding(tmp.path(), &client)
777            .await
778            .unwrap_err()
779            .to_string();
780        assert!(err.contains("no tracked repo"), "got: {err}");
781    }
782}