1use 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#[derive(clap::Subcommand)]
15pub enum RepoCmd {
16 #[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
20 Switch {
21 #[arg(group = "target")]
23 path: Option<String>,
24 #[arg(long, group = "target")]
27 name: Option<String>,
28 #[arg(long, requires = "path")]
33 repo_id: Option<uuid::Uuid>,
34 #[arg(long)]
37 user: bool,
38 #[arg(long)]
40 session_id: Option<String>,
41 },
42 Status {
44 #[arg(long)]
46 session_id: Option<String>,
47 #[arg(long)]
49 path: Option<String>,
50 },
51 Reset {
53 #[arg(long)]
55 user: bool,
56 #[arg(long)]
58 session_id: Option<String>,
59 },
60}
61
62pub 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
108async 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
126struct InUse {
129 repo_id: uuid::Uuid,
130 source: String,
131}
132
133fn 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
174fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
176 state.active = Some(binding);
177}
178
179fn 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 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#[derive(Debug, PartialEq, Eq)]
212enum SwitchTarget<'a> {
213 Path(&'a str),
214}
215
216fn 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#[derive(Debug)]
244enum SwitchDest {
245 Session(String),
246 UserDefault,
247}
248
249fn 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
262fn 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 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 let session = resolve_session_id(session_id).ok();
329 let dest = switch_destination(user, session);
330
331 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 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
374async 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 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
422fn 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 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 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 if let Some((binding, _)) = &effective {
481 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 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 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 #[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 #[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 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 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 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 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 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 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 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 #[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"); 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 #[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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 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 #[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 #[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 #[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 #[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}