1use std::path::Path;
4
5use crate::api_client::{resolve_client, ApiClient};
6use crate::credentials::resolve_credentials;
7use crate::resolution::{
8 binding_from_config, effective_binding, resolve_path_to_binding, BindingSource, ResolveInputs,
9};
10use crate::session_state::{self, RepoBinding, SessionState};
11
12#[derive(clap::Subcommand)]
14pub enum RepoCmd {
15 #[command(group(clap::ArgGroup::new("target").required(true).multiple(false)))]
19 Switch {
20 #[arg(group = "target")]
22 path: Option<String>,
23 #[arg(long, group = "target")]
26 name: Option<String>,
27 #[arg(long)]
30 user: bool,
31 #[arg(long)]
33 session_id: Option<String>,
34 },
35 Status {
37 #[arg(long)]
39 session_id: Option<String>,
40 #[arg(long)]
42 path: Option<String>,
43 },
44 Reset {
46 #[arg(long)]
48 user: bool,
49 #[arg(long)]
51 session_id: Option<String>,
52 },
53}
54
55pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
58 if let Some(s) = explicit {
59 return Ok(s.to_string());
60 }
61 std::env::var("TRACEVAULT_SESSION_ID")
62 .ok()
63 .filter(|s| !s.is_empty())
64 .ok_or_else(|| {
65 "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
66 (installed by `tracevault init --global`)"
67 .into()
68 })
69}
70
71pub async fn run(
72 cmd: RepoCmd,
73 project_root: &Path,
74 cwd: &Path,
75) -> Result<(), Box<dyn std::error::Error>> {
76 match cmd {
77 RepoCmd::Status { session_id, path } => {
78 status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
79 }
80 RepoCmd::Switch {
81 path,
82 name,
83 user,
84 session_id,
85 } => {
86 switch(
87 path.as_deref(),
88 name.as_deref(),
89 user,
90 session_id.as_deref(),
91 project_root,
92 )
93 .await
94 }
95 RepoCmd::Reset { user, session_id } => reset(user, session_id.as_deref()),
96 }
97}
98
99async fn resolve_switch_binding(
103 path: &Path,
104 client: &ApiClient,
105) -> Result<RepoBinding, Box<dyn std::error::Error>> {
106 resolve_path_to_binding(path, client).await?.ok_or_else(|| {
107 format!(
108 "repo at {} is not registered with TraceVault; nothing to bind",
109 path.display()
110 )
111 .into()
112 })
113}
114
115fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
117 state.active = Some(binding);
118}
119
120fn apply_reset(state: &mut SessionState) {
122 *state = SessionState::default();
123}
124
125fn reset(user: bool, session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
126 if user {
127 crate::user_default::clear()?;
128 println!("cleared user-level default repo binding");
129 return Ok(());
130 }
131 let id = resolve_session_id(session_id)?;
132 let mut state = session_state::load(&id);
133 apply_reset(&mut state);
134 session_state::save(&id, &state)?;
135 println!("cleared workspace repo binding for session {id}");
137 Ok(())
138}
139
140#[derive(Debug, PartialEq, Eq)]
144enum SwitchTarget<'a> {
145 Path(&'a str),
146}
147
148fn switch_target<'a>(
156 path: Option<&'a str>,
157 name: Option<&'a str>,
158) -> Result<SwitchTarget<'a>, Box<dyn std::error::Error>> {
159 match (path, name) {
160 (Some(p), _) if !p.trim().is_empty() => Ok(SwitchTarget::Path(p)),
161 (Some(_), _) => Err("repo path must not be empty".into()),
162 (None, Some(_)) => Err(
163 "`--name` binding is deprecated and no longer supported; bind by checkout path \
164 (`tracevault repo switch <path>`) so the codebase is resolved from its git remote"
165 .into(),
166 ),
167 (None, None) => {
168 Err("provide a checkout path to bind (`tracevault repo switch <path>`)".into())
169 }
170 }
171}
172
173#[derive(Debug)]
176enum SwitchDest {
177 Session(String),
178 UserDefault,
179}
180
181fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
185 if user {
186 return SwitchDest::UserDefault;
187 }
188 match session_id {
189 Some(id) => SwitchDest::Session(id),
190 None => SwitchDest::UserDefault,
191 }
192}
193
194async fn switch(
195 path: Option<&str>,
196 name: Option<&str>,
197 user: bool,
198 session_id: Option<&str>,
199 project_root: &Path,
200) -> Result<(), Box<dyn std::error::Error>> {
201 let target = switch_target(path, name)?;
205
206 let client = resolve_client(project_root)?;
207
208 let binding = match target {
209 SwitchTarget::Path(p) => resolve_switch_binding(Path::new(p), &client).await?,
210 };
211
212 let repo_uuid = binding.repo_id.parse::<uuid::Uuid>().map_err(|e| {
215 format!(
216 "server returned an invalid repo id {:?}: {e}",
217 binding.repo_id
218 )
219 })?;
220
221 let session = resolve_session_id(session_id).ok();
226 match switch_destination(user, session) {
227 SwitchDest::Session(id) => {
228 let mut state = session_state::load(&id);
229 apply_switch(&mut state, binding.clone());
230 session_state::save(&id, &state)?;
231 println!("bound session {id} to repo {}", binding.repo_id);
232 }
233 SwitchDest::UserDefault => {
234 crate::user_default::save(&binding)?;
235 println!(
236 "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)",
237 binding.repo_id
238 );
239 }
240 }
241
242 match client.get_agent_instructions(&repo_uuid).await {
245 Ok(policies) => println!("{}", policies.content),
246 Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
247 }
248 Ok(())
249}
250
251async fn resolve_repo_flag(
256 repo_flag_path: Option<&str>,
257 project_root: &Path,
258) -> Option<RepoBinding> {
259 let path = repo_flag_path?;
260
261 let (server_url, credential) = match resolve_credentials(project_root) {
265 Ok(resolved) => resolved,
266 Err(e) => {
267 eprintln!("--path {path}: {e}");
268 return None;
269 }
270 };
271 let Some(server_url) = server_url else {
272 eprintln!(
273 "--path {path}: no server URL configured (run `tracevault login`); showing binding \
274 without the --path override"
275 );
276 return None;
277 };
278
279 let client = ApiClient::with_credential(&server_url, credential);
280 match resolve_path_to_binding(Path::new(path), &client).await {
281 Ok(Some(binding)) => Some(binding),
282 Ok(None) => {
283 eprintln!(
284 "--path {path}: no registered repo found for this path's git remote; showing \
285 binding without the --path override"
286 );
287 None
288 }
289 Err(e) => {
290 eprintln!(
291 "--path {path}: failed to resolve ({e}); showing binding without the --path \
292 override"
293 );
294 None
295 }
296 }
297}
298
299fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
302 match binding {
303 Some((b, source)) => format!("bound to repo {} via {source}", b.repo_id),
304 None => {
305 "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)".into()
306 }
307 }
308}
309
310async fn status(
311 session_id: Option<&str>,
312 repo_flag_path: Option<&str>,
313 project_root: &Path,
314 cwd: &Path,
315) -> Result<(), Box<dyn std::error::Error>> {
316 let session = match resolve_session_id(session_id) {
320 Ok(id) => session_state::load(&id),
321 Err(_) => {
322 eprintln!(
323 "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
324 showing binding without session context"
325 );
326 SessionState::default()
327 }
328 };
329 let worktree = crate::paths::worktree_toplevel(cwd);
330 let bound = crate::config::TracevaultConfig::load(project_root)
331 .as_ref()
332 .and_then(binding_from_config);
333
334 let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;
336
337 let user_default = crate::user_default::load();
338
339 let effective = effective_binding(ResolveInputs {
340 repo_flag,
341 session: &session,
342 worktree_path: Some(&worktree),
343 bound,
344 user_default: user_default.clone(),
345 });
346 println!(
347 "{}",
348 format_status(effective.as_ref().map(|(b, s)| (b, *s)))
349 );
350
351 if let Some((binding, _)) = &effective {
358 let (server_url, credential) = match resolve_credentials(project_root) {
362 Ok(resolved) => resolved,
363 Err(e) => {
364 eprintln!("Warning: {e}");
365 (None, None)
366 }
367 };
368 let client = server_url
369 .as_ref()
370 .map(|su| ApiClient::with_credential(su, credential));
371 let detail_line = if let (Some(client), Some(remote_id)) = (&client, binding.remote_id) {
372 client.get_remote_detail(remote_id).await.ok().map(|d| {
373 crate::resolution::codebase_line(
374 d.name.as_deref(),
375 &d.normalized_url,
376 &d.clone_status,
377 )
378 })
379 } else {
380 None
381 };
382 let resolved_line = if detail_line.is_none() {
383 if let (Some(client), Some(git_url)) = (&client, binding.git_url.as_deref()) {
384 client
385 .resolve_remote(git_url)
386 .await
387 .ok()
388 .flatten()
389 .map(|r| {
390 crate::resolution::codebase_line(
391 r.name.as_deref(),
392 &r.normalized_url,
393 &r.clone_status,
394 )
395 })
396 } else {
397 None
398 }
399 } else {
400 None
401 };
402 if let Some(line) = crate::resolution::pick_status_line(
403 detail_line,
404 resolved_line,
405 binding.codebase_name.as_deref(),
406 ) {
407 println!("{line}");
408 }
409 }
410
411 let default_is_effective = matches!(
414 effective.as_ref().map(|(_, s)| *s),
415 Some(BindingSource::UserDefault)
416 );
417 if let Some(ud) = &user_default {
418 if !default_is_effective {
419 println!("user default: repo {}", ud.repo_id);
420 }
421 }
422 Ok(())
423}
424
425#[cfg(test)]
426mod tests {
427 use super::*;
428 use std::io::{BufRead, BufReader, Write};
429 use std::net::TcpListener;
430 use std::thread;
431
432 #[test]
433 fn resolve_session_id_prefers_explicit() {
434 assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
435 }
436
437 #[test]
438 fn resolve_session_id_errors_when_absent() {
439 if std::env::var("TRACEVAULT_SESSION_ID").is_err() {
443 assert!(resolve_session_id(None).is_err());
444 }
445 }
446
447 #[test]
448 fn switch_destination_user_flag_forces_user_default() {
449 assert!(matches!(
450 switch_destination(true, Some("sess-1".to_string())),
451 SwitchDest::UserDefault
452 ));
453 assert!(matches!(
454 switch_destination(true, None),
455 SwitchDest::UserDefault
456 ));
457 }
458
459 #[test]
460 fn switch_destination_session_when_present_and_no_user_flag() {
461 assert!(matches!(
462 switch_destination(false, Some("sess-1".to_string())),
463 SwitchDest::Session(id) if id == "sess-1"
464 ));
465 }
466
467 #[test]
468 fn switch_destination_user_default_when_no_session() {
469 assert!(matches!(
470 switch_destination(false, None),
471 SwitchDest::UserDefault
472 ));
473 }
474
475 #[test]
476 fn switch_target_rejects_neither() {
477 assert!(switch_target(None, None).is_err());
478 }
479
480 #[test]
484 fn switch_target_path_wins_when_both_given() {
485 assert!(matches!(
486 switch_target(Some("/p"), Some("x")),
487 Ok(SwitchTarget::Path("/p"))
488 ));
489 }
490
491 #[test]
492 fn switch_target_accepts_path_only() {
493 assert!(matches!(
494 switch_target(Some("/p"), None),
495 Ok(SwitchTarget::Path("/p"))
496 ));
497 }
498
499 #[test]
502 fn switch_target_name_is_deprecated() {
503 let err = switch_target(None, Some("some-repo"))
504 .unwrap_err()
505 .to_string();
506 assert!(err.contains("deprecated"), "got: {err}");
507 assert!(err.contains("path"), "should direct to path binding: {err}");
508 }
509
510 fn binding(id: &str) -> RepoBinding {
511 RepoBinding {
512 repo_id: id.into(),
513 git_url: None,
514 remote_id: None,
515 codebase_name: None,
516 updated_at: "t".into(),
517 }
518 }
519
520 #[test]
521 fn apply_switch_sets_session_active() {
522 let mut state = SessionState::default();
523 apply_switch(&mut state, binding("new-repo"));
524 assert_eq!(state.active.unwrap().repo_id, "new-repo");
525 }
526
527 #[test]
528 fn apply_reset_clears_active_and_subagents() {
529 let mut state = SessionState {
530 active: Some(binding("r")),
531 subagents: std::collections::HashMap::from([("/wt/a".to_string(), binding("r2"))]),
532 ..Default::default()
533 };
534 apply_reset(&mut state);
535 assert_eq!(state, SessionState::default());
536 }
537
538 #[test]
539 fn apply_switch_overwrites_existing_active() {
540 let mut state = SessionState {
541 active: Some(binding("old-repo")),
542 subagents: Default::default(),
543 ..Default::default()
544 };
545 apply_switch(&mut state, binding("new-repo"));
546 assert_eq!(state.active.unwrap().repo_id, "new-repo");
547 }
548
549 #[test]
550 fn format_status_none() {
551 assert_eq!(
552 format_status(None),
553 "not bound to any repo (workspace mode; run `tracevault repo switch <path>`)"
554 );
555 }
556
557 #[test]
558 fn format_status_repo_flag() {
559 let b = binding("r1");
560 assert_eq!(
561 format_status(Some((&b, BindingSource::RepoFlag))),
562 "bound to repo r1 via --path override"
563 );
564 }
565
566 #[test]
567 fn format_status_subagent() {
568 let b = binding("r2");
569 assert_eq!(
570 format_status(Some((&b, BindingSource::Subagent))),
571 "bound to repo r2 via subagent worktree override"
572 );
573 }
574
575 #[test]
576 fn format_status_session_active() {
577 let b = binding("r3");
578 assert_eq!(
579 format_status(Some((&b, BindingSource::SessionActive))),
580 "bound to repo r3 via session (repo switch)"
581 );
582 }
583
584 #[test]
585 fn format_status_bound() {
586 let b = binding("r4");
587 assert_eq!(
588 format_status(Some((&b, BindingSource::Bound))),
589 "bound to repo r4 via bound .tracevault/config.toml"
590 );
591 }
592
593 #[test]
594 fn format_status_user_default() {
595 let b = binding("r5");
596 assert_eq!(
597 format_status(Some((&b, BindingSource::UserDefault))),
598 "bound to repo r5 via user default (repo switch --user)"
599 );
600 }
601
602 fn add_origin_remote(dir: &std::path::Path, url: &str) {
603 let ok = std::process::Command::new("git")
604 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
605 .status()
606 .expect("git remote add failed")
607 .success();
608 assert!(ok, "git remote add must succeed");
609 }
610
611 fn spawn_once(response: &'static str) -> String {
614 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
615 let addr = listener.local_addr().unwrap();
616 thread::spawn(move || {
617 if let Ok((stream, _)) = listener.accept() {
618 let mut reader = BufReader::new(stream);
619 let mut request_line = String::new();
620 let _ = reader.read_line(&mut request_line);
621 let mut stream = reader.into_inner();
622 let _ = stream.write_all(response.as_bytes());
623 let _ = stream.flush();
624 }
625 });
626 format!("http://{addr}")
627 }
628
629 fn http_200(body: &str) -> String {
632 format!(
633 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
634 body.len(),
635 body
636 )
637 }
638
639 fn spawn_n(responses: Vec<String>) -> String {
643 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
644 let addr = listener.local_addr().unwrap();
645 thread::spawn(move || {
646 for response in responses {
647 let response: &'static str = Box::leak(response.into_boxed_str());
648 if let Ok((stream, _)) = listener.accept() {
649 let mut reader = BufReader::new(stream);
650 let mut request_line = String::new();
651 let _ = reader.read_line(&mut request_line);
652 let mut stream = reader.into_inner();
653 let _ = stream.write_all(response.as_bytes());
654 let _ = stream.flush();
655 }
656 }
657 });
658 format!("http://{addr}")
659 }
660
661 #[tokio::test]
662 async fn resolve_switch_binding_ok_for_registered_repo() {
663 let tmp = tempfile::tempdir().unwrap();
667 crate::test_helpers::init_git_repo(tmp.path());
668 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
669
670 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
671 let repo_id = "11111111-1111-4111-8111-111111111111";
672 let remote = format!(
673 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
674 );
675 let detail = format!(
676 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"}}]}}"#
677 );
678 let base = spawn_n(vec![http_200(&remote), http_200(&detail)]);
679 let client = ApiClient::new(&base, Some("tok"));
680
681 let got = resolve_switch_binding(tmp.path(), &client)
682 .await
683 .expect("expected Ok binding");
684 assert_eq!(got.repo_id, repo_id);
685 assert_eq!(got.remote_id, Some(remote_id.parse().unwrap()));
686 assert_eq!(got.codebase_name.as_deref(), Some("repo"));
687 }
688
689 #[tokio::test]
690 async fn resolve_switch_binding_errors_for_unregistered_repo() {
691 let tmp = tempfile::tempdir().unwrap();
692 crate::test_helpers::init_git_repo(tmp.path());
693 add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
694
695 let body = r#"{"error":"No remote for that URL"}"#;
700 let resp = format!(
701 "HTTP/1.1 404 Not Found\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
702 body.len(), body
703 );
704 let base = spawn_once(Box::leak(resp.into_boxed_str()));
705 let client = ApiClient::new(&base, Some("tok"));
706
707 let err = resolve_switch_binding(tmp.path(), &client)
708 .await
709 .expect_err("expected Err for unregistered repo");
710 assert!(
711 err.to_string().contains("not registered"),
712 "unexpected error message: {err}"
713 );
714 }
715
716 #[tokio::test]
717 async fn resolve_switch_binding_flags_bare_404_as_version_skew() {
718 let tmp = tempfile::tempdir().unwrap();
724 crate::test_helpers::init_git_repo(tmp.path());
725 add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
726
727 let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
728 let base = spawn_once(resp);
729 let client = ApiClient::new(&base, Some("tok"));
730
731 let err = resolve_switch_binding(tmp.path(), &client)
732 .await
733 .expect_err("expected Err for a bare route-404");
734 assert!(
735 !err.to_string().contains("not registered"),
736 "must not be misreported as 'not registered'; got: {err}"
737 );
738 assert!(
739 err.to_string().to_lowercase().contains("version mismatch"),
740 "expected a version-mismatch hint; got: {err}"
741 );
742 }
743
744 #[test]
745 fn switch_target_rejects_empty_name() {
746 assert!(switch_target(None, Some("")).is_err());
749 assert!(switch_target(None, Some(" ")).is_err());
750 let err = switch_target(None, Some(" ")).unwrap_err().to_string();
751 assert!(err.contains("deprecated"), "got: {err}");
752 }
753
754 #[test]
755 fn switch_target_rejects_empty_path() {
756 assert!(switch_target(Some(""), None).is_err());
757 assert!(switch_target(Some(" "), None).is_err());
758 let err = switch_target(Some(" "), None).unwrap_err().to_string();
759 assert!(err.contains("must not be empty"), "got: {err}");
760 }
761
762 #[tokio::test]
765 async fn resolve_path_binds_via_remote_across_url_spelling() {
766 let tmp = tempfile::tempdir().unwrap();
767 crate::test_helpers::init_git_repo(tmp.path());
768 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"}"#;
770 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"}]}"#;
771 let base = spawn_n(vec![http_200(remote), http_200(detail)]);
772 let client = ApiClient::new(&base, Some("tok"));
773 let b = resolve_path_to_binding(tmp.path(), &client)
774 .await
775 .unwrap()
776 .expect("Some binding");
777 assert_eq!(b.repo_id, "11111111-1111-4111-8111-111111111111");
778 assert_eq!(
779 b.remote_id,
780 Some("44000761-8d22-4256-bd2c-27a0ba278c6f".parse().unwrap())
781 );
782 assert_eq!(b.codebase_name.as_deref(), Some("x"));
783 }
784
785 #[tokio::test]
787 async fn resolve_path_bare_remote_errors() {
788 let tmp = tempfile::tempdir().unwrap();
789 crate::test_helpers::init_git_repo(tmp.path());
790 add_origin_remote(tmp.path(), "git@github.com:o/x.git");
791 let remote = r#"{"remote_id":"44000761-8d22-4256-bd2c-27a0ba278c6f","name":"x","normalized_url":"github.com/o/x","clone_status":"pending"}"#;
792 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":[]}"#;
793 let base = spawn_n(vec![http_200(remote), http_200(detail)]);
794 let client = ApiClient::new(&base, Some("tok"));
795 let err = resolve_path_to_binding(tmp.path(), &client)
796 .await
797 .unwrap_err()
798 .to_string();
799 assert!(err.contains("no tracked repo"), "got: {err}");
800 }
801}