1use std::path::Path;
4
5use crate::api_client::{resolve_credentials, ApiClient, RepoListItem};
6use crate::resolution::{
7 binding_from_config, effective_binding, org_slug_for, resolve_path_to_binding, BindingSource,
8 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)))]
18 Switch {
19 #[arg(group = "target")]
21 path: Option<String>,
22 #[arg(long, group = "target")]
24 name: Option<String>,
25 #[arg(long)]
28 user: bool,
29 #[arg(long)]
31 session_id: Option<String>,
32 },
33 Status {
35 #[arg(long)]
37 session_id: Option<String>,
38 #[arg(long)]
40 path: Option<String>,
41 },
42 Reset {
44 #[arg(long)]
46 user: bool,
47 #[arg(long)]
49 session_id: Option<String>,
50 },
51}
52
53pub fn resolve_session_id(explicit: Option<&str>) -> Result<String, Box<dyn std::error::Error>> {
56 if let Some(s) = explicit {
57 return Ok(s.to_string());
58 }
59 std::env::var("TRACEVAULT_SESSION_ID")
60 .ok()
61 .filter(|s| !s.is_empty())
62 .ok_or_else(|| {
63 "no session id available: pass --session-id or set TRACEVAULT_SESSION_ID \
64 (installed by `tracevault init --global`)"
65 .into()
66 })
67}
68
69pub async fn run(
70 cmd: RepoCmd,
71 project_root: &Path,
72 cwd: &Path,
73) -> Result<(), Box<dyn std::error::Error>> {
74 match cmd {
75 RepoCmd::Status { session_id, path } => {
76 status(session_id.as_deref(), path.as_deref(), project_root, cwd).await
77 }
78 RepoCmd::Switch {
79 path,
80 name,
81 user,
82 session_id,
83 } => {
84 switch(
85 path.as_deref(),
86 name.as_deref(),
87 user,
88 session_id.as_deref(),
89 project_root,
90 )
91 .await
92 }
93 RepoCmd::Reset { user, session_id } => reset(user, session_id.as_deref()),
94 }
95}
96
97async fn resolve_switch_binding(
101 path: &Path,
102 org_slug: &str,
103 client: &ApiClient,
104) -> Result<RepoBinding, Box<dyn std::error::Error>> {
105 resolve_path_to_binding(path, org_slug, client)
106 .await?
107 .ok_or_else(|| {
108 format!(
109 "repo at {} is not registered with TraceVault (org {org_slug}); nothing to bind",
110 path.display()
111 )
112 .into()
113 })
114}
115
116fn name_not_found_error(name: &str, org_slug: &str, repos: &[RepoListItem]) -> String {
120 if repos.is_empty() {
121 return format!("no repo named '{name}': org {org_slug} has no registered repos");
122 }
123 const MAX: usize = 20;
124 let mut names: Vec<&str> = repos.iter().map(|r| r.name.as_str()).collect();
125 names.sort_unstable();
126 let shown = names.len().min(MAX);
127 let mut list = names[..shown].join(", ");
128 if names.len() > MAX {
129 list.push_str(&format!(", … and {} more", names.len() - MAX));
130 }
131 format!("no repo named '{name}' in org {org_slug} (available: {list})")
132}
133
134async fn resolve_name_to_binding(
142 name: &str,
143 org_slug: &str,
144 client: &ApiClient,
145) -> Result<RepoBinding, Box<dyn std::error::Error>> {
146 let repos = client.list_repos(org_slug).await?;
147 match repos.iter().find(|r| r.name == name) {
148 Some(repo) => Ok(RepoBinding {
149 org_slug: org_slug.to_string(),
150 repo_id: repo.id.to_string(),
151 git_url: repo.github_url.clone(),
152 updated_at: chrono::Utc::now().to_rfc3339(),
153 }),
154 None => Err(name_not_found_error(name, org_slug, &repos).into()),
155 }
156}
157
158fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
160 state.active = Some(binding);
161}
162
163fn apply_reset(state: &mut SessionState) {
165 *state = SessionState::default();
166}
167
168fn reset(user: bool, session_id: Option<&str>) -> Result<(), Box<dyn std::error::Error>> {
169 if user {
170 crate::user_default::clear()?;
171 println!("cleared user-level default repo binding");
172 return Ok(());
173 }
174 let id = resolve_session_id(session_id)?;
175 let mut state = session_state::load(&id);
176 apply_reset(&mut state);
177 session_state::save(&id, &state)?;
178 println!("cleared workspace repo binding for session {id}");
180 Ok(())
181}
182
183#[derive(Debug)]
187enum SwitchTarget<'a> {
188 Path(&'a str),
189 Name(&'a str),
190}
191
192fn switch_target<'a>(
197 path: Option<&'a str>,
198 name: Option<&'a str>,
199) -> Result<SwitchTarget<'a>, Box<dyn std::error::Error>> {
200 match (path, name) {
201 (Some(p), None) if p.trim().is_empty() => {
202 Err("repo path (<path>) must not be empty".into())
203 }
204 (Some(p), None) => Ok(SwitchTarget::Path(p)),
205 (None, Some(n)) if n.trim().is_empty() => {
206 Err("repo name (--name) must not be empty".into())
207 }
208 (None, Some(n)) => Ok(SwitchTarget::Name(n)),
209 _ => Err("provide exactly one of <path> or --name".into()),
210 }
211}
212
213#[derive(Debug)]
216enum SwitchDest {
217 Session(String),
218 UserDefault,
219}
220
221fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
225 if user {
226 return SwitchDest::UserDefault;
227 }
228 match session_id {
229 Some(id) => SwitchDest::Session(id),
230 None => SwitchDest::UserDefault,
231 }
232}
233
234async fn switch(
235 path: Option<&str>,
236 name: Option<&str>,
237 user: bool,
238 session_id: Option<&str>,
239 project_root: &Path,
240) -> Result<(), Box<dyn std::error::Error>> {
241 let target = switch_target(path, name)?;
245
246 let (server_url, token) = resolve_credentials(project_root);
248 let server_url = server_url
249 .ok_or("no server URL configured: set TRACEVAULT_SERVER_URL or run `tracevault login`")?;
250 let client = ApiClient::new(&server_url, token.as_deref());
251
252 let org_slug = match org_slug_for(project_root) {
256 Some(s) => s,
257 None => {
258 let orgs = client.list_my_orgs().await.map_err(|e| {
259 format!(
260 "no org configured and could not derive it from your credential ({e}); \
261 set TRACEVAULT_ORG_SLUG, log in, or run inside a bound repo checkout"
262 )
263 })?;
264 let slugs: Vec<String> = orgs.into_iter().map(|o| o.org_name).collect();
265 crate::resolution::org_slug_from_slugs(&slugs)?
266 }
267 };
268
269 let binding = match target {
270 SwitchTarget::Path(p) => resolve_switch_binding(Path::new(p), &org_slug, &client).await?,
271 SwitchTarget::Name(n) => resolve_name_to_binding(n, &org_slug, &client).await?,
272 };
273
274 let repo_uuid = binding.repo_id.parse::<uuid::Uuid>().map_err(|e| {
277 format!(
278 "server returned an invalid repo id {:?}: {e}",
279 binding.repo_id
280 )
281 })?;
282
283 let session = resolve_session_id(session_id).ok();
288 match switch_destination(user, session) {
289 SwitchDest::Session(id) => {
290 let mut state = session_state::load(&id);
291 apply_switch(&mut state, binding.clone());
292 session_state::save(&id, &state)?;
293 println!(
294 "bound session {id} to repo {} (org {})",
295 binding.repo_id, binding.org_slug
296 );
297 }
298 SwitchDest::UserDefault => {
299 crate::user_default::save(&binding)?;
300 println!(
301 "set user-level default repo {} (org {}); applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
302 binding.repo_id, binding.org_slug
303 );
304 }
305 }
306
307 match client
310 .get_agent_instructions(&binding.org_slug, &repo_uuid)
311 .await
312 {
313 Ok(policies) => println!("{}", policies.content),
314 Err(e) => eprintln!("warning: bound, but could not fetch policies: {e}"),
315 }
316 Ok(())
317}
318
319async fn resolve_repo_flag(
324 repo_flag_path: Option<&str>,
325 project_root: &Path,
326) -> Option<RepoBinding> {
327 let path = repo_flag_path?;
328
329 let Some(org_slug) = org_slug_for(project_root) else {
330 eprintln!(
331 "--path {path}: no org slug configured (set TRACEVAULT_ORG_SLUG, log in, or bind \
332 the repo); showing binding without the --path override"
333 );
334 return None;
335 };
336
337 let (server_url, token) = resolve_credentials(project_root);
338 let Some(server_url) = server_url else {
339 eprintln!(
340 "--path {path}: no server URL configured (run `tracevault login`); showing binding \
341 without the --path override"
342 );
343 return None;
344 };
345
346 let client = ApiClient::new(&server_url, token.as_deref());
347 match resolve_path_to_binding(Path::new(path), &org_slug, &client).await {
348 Ok(Some(binding)) => Some(binding),
349 Ok(None) => {
350 eprintln!(
351 "--path {path}: no registered repo found for this path's git remote; showing \
352 binding without the --path override"
353 );
354 None
355 }
356 Err(e) => {
357 eprintln!(
358 "--path {path}: failed to resolve ({e}); showing binding without the --path \
359 override"
360 );
361 None
362 }
363 }
364}
365
366fn format_status(binding: Option<(&RepoBinding, BindingSource)>) -> String {
369 match binding {
370 Some((b, source)) => format!(
371 "bound to repo {} (org {}) via {source}",
372 b.repo_id, b.org_slug
373 ),
374 None => {
375 "not bound to any repo (workspace mode; run `tracevault repo switch <path>` or `tracevault repo switch --name <project>`)".into()
376 }
377 }
378}
379
380async fn status(
381 session_id: Option<&str>,
382 repo_flag_path: Option<&str>,
383 project_root: &Path,
384 cwd: &Path,
385) -> Result<(), Box<dyn std::error::Error>> {
386 let session = match resolve_session_id(session_id) {
390 Ok(id) => session_state::load(&id),
391 Err(_) => {
392 eprintln!(
393 "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
394 showing binding without session context"
395 );
396 SessionState::default()
397 }
398 };
399 let worktree = crate::paths::worktree_toplevel(cwd);
400 let bound = crate::config::TracevaultConfig::load(project_root)
401 .as_ref()
402 .and_then(binding_from_config);
403
404 let repo_flag = resolve_repo_flag(repo_flag_path, project_root).await;
406
407 let user_default = crate::user_default::load();
408
409 let effective = effective_binding(ResolveInputs {
410 repo_flag,
411 session: &session,
412 worktree_path: Some(&worktree),
413 bound,
414 user_default: user_default.clone(),
415 });
416 println!(
417 "{}",
418 format_status(effective.as_ref().map(|(b, s)| (b, *s)))
419 );
420
421 let default_is_effective = matches!(
424 effective.as_ref().map(|(_, s)| *s),
425 Some(BindingSource::UserDefault)
426 );
427 if let Some(ud) = &user_default {
428 if !default_is_effective {
429 println!("user default: repo {} (org {})", ud.repo_id, ud.org_slug);
430 }
431 }
432 Ok(())
433}
434
435#[cfg(test)]
436mod tests {
437 use super::*;
438 use std::io::{BufRead, BufReader, Write};
439 use std::net::TcpListener;
440 use std::thread;
441
442 #[test]
443 fn resolve_session_id_prefers_explicit() {
444 assert_eq!(resolve_session_id(Some("sess-x")).unwrap(), "sess-x");
445 }
446
447 #[test]
448 fn resolve_session_id_errors_when_absent() {
449 if std::env::var("TRACEVAULT_SESSION_ID").is_err() {
453 assert!(resolve_session_id(None).is_err());
454 }
455 }
456
457 #[test]
458 fn switch_destination_user_flag_forces_user_default() {
459 assert!(matches!(
460 switch_destination(true, Some("sess-1".to_string())),
461 SwitchDest::UserDefault
462 ));
463 assert!(matches!(
464 switch_destination(true, None),
465 SwitchDest::UserDefault
466 ));
467 }
468
469 #[test]
470 fn switch_destination_session_when_present_and_no_user_flag() {
471 assert!(matches!(
472 switch_destination(false, Some("sess-1".to_string())),
473 SwitchDest::Session(id) if id == "sess-1"
474 ));
475 }
476
477 #[test]
478 fn switch_destination_user_default_when_no_session() {
479 assert!(matches!(
480 switch_destination(false, None),
481 SwitchDest::UserDefault
482 ));
483 }
484
485 #[test]
486 fn switch_target_rejects_neither() {
487 assert!(switch_target(None, None).is_err());
488 }
489
490 #[test]
491 fn switch_target_rejects_both() {
492 assert!(switch_target(Some("/p"), Some("x")).is_err());
493 }
494
495 #[test]
496 fn switch_target_accepts_path_only() {
497 assert!(matches!(
498 switch_target(Some("/p"), None),
499 Ok(SwitchTarget::Path("/p"))
500 ));
501 }
502
503 #[test]
504 fn switch_target_accepts_name_only() {
505 assert!(matches!(
506 switch_target(None, Some("proj")),
507 Ok(SwitchTarget::Name("proj"))
508 ));
509 }
510
511 fn binding(id: &str) -> RepoBinding {
512 RepoBinding {
513 org_slug: "org".into(),
514 repo_id: id.into(),
515 git_url: 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>` or `tracevault repo switch --name <project>`)"
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 (org org) 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 (org org) 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 (org org) 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 (org org) 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 (org org) 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 #[tokio::test]
630 async fn resolve_switch_binding_ok_for_registered_repo() {
631 let tmp = tempfile::tempdir().unwrap();
632 crate::test_helpers::init_git_repo(tmp.path());
633 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
634
635 let repo_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
636 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
637 let resp = format!(
638 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
639 body.len(),
640 body
641 );
642 let base = spawn_once(Box::leak(resp.into_boxed_str()));
643 let client = ApiClient::new(&base, Some("tok"));
644
645 let got = resolve_switch_binding(tmp.path(), "org", &client)
646 .await
647 .expect("expected Ok binding");
648 assert_eq!(got.repo_id, repo_id);
649 assert_eq!(got.org_slug, "org");
650 }
651
652 #[tokio::test]
653 async fn resolve_switch_binding_errors_for_unregistered_repo() {
654 let tmp = tempfile::tempdir().unwrap();
655 crate::test_helpers::init_git_repo(tmp.path());
656 add_origin_remote(tmp.path(), "git@github.com:org/unregistered.git");
657
658 let resp = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
659 let base = spawn_once(resp);
660 let client = ApiClient::new(&base, Some("tok"));
661
662 let err = resolve_switch_binding(tmp.path(), "org", &client)
663 .await
664 .expect_err("expected Err for unregistered repo");
665 assert!(
666 err.to_string().contains("not registered"),
667 "unexpected error message: {err}"
668 );
669 }
670
671 #[tokio::test]
672 async fn resolve_name_to_binding_finds_by_name() {
673 let body = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"visdom-orchestrator","github_url":null,"clone_status":null},{"id":"22222222-2222-4222-8222-222222222222","name":"visdom-web","github_url":"https://github.com/o/web.git","clone_status":null}]"#;
674 let resp = format!(
675 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
676 body.len(),
677 body
678 );
679 let base = spawn_once(Box::leak(resp.into_boxed_str()));
680 let client = ApiClient::new(&base, Some("tok"));
681 let b = resolve_name_to_binding("visdom-orchestrator", "acme", &client)
682 .await
683 .expect("expected Ok binding");
684 assert_eq!(b.repo_id, "11111111-1111-4111-8111-111111111111");
685 assert_eq!(b.org_slug, "acme");
686 }
687
688 #[tokio::test]
689 async fn resolve_name_to_binding_errors_when_absent_listing_names() {
690 let body = r#"[{"id":"22222222-2222-4222-8222-222222222222","name":"visdom-web","github_url":null,"clone_status":null}]"#;
691 let resp = format!(
692 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
693 body.len(),
694 body
695 );
696 let base = spawn_once(Box::leak(resp.into_boxed_str()));
697 let client = ApiClient::new(&base, Some("tok"));
698 let err = resolve_name_to_binding("visdom-orch", "acme", &client)
699 .await
700 .expect_err("expected Err for missing name")
701 .to_string();
702 assert!(err.contains("no repo named"), "got: {err}");
703 assert!(
704 err.contains("visdom-web"),
705 "error should list available names, got: {err}"
706 );
707 }
708
709 #[test]
710 fn name_not_found_error_empty_org_is_explicit() {
711 let msg = name_not_found_error("x", "acme", &[]);
712 assert!(msg.contains("has no registered repos"), "got: {msg}");
713 assert!(
714 !msg.contains("available:"),
715 "empty org must not print a dangling list: {msg}"
716 );
717 }
718
719 #[test]
720 fn name_not_found_error_caps_long_lists() {
721 let repos: Vec<RepoListItem> = (0..25)
722 .map(|i| RepoListItem {
723 id: uuid::Uuid::nil(),
724 name: format!("repo-{i:02}"),
725 github_url: None,
726 clone_status: None,
727 })
728 .collect();
729 let msg = name_not_found_error("zzz", "acme", &repos);
730 assert!(
731 msg.contains("… and 5 more"),
732 "should cap at 20 and note the remainder: {msg}"
733 );
734 }
735
736 #[test]
737 fn switch_target_rejects_empty_name() {
738 assert!(switch_target(None, Some("")).is_err());
739 assert!(switch_target(None, Some(" ")).is_err());
740 let err = switch_target(None, Some(" ")).unwrap_err().to_string();
741 assert!(err.contains("must not be empty"), "got: {err}");
742 }
743
744 #[test]
745 fn switch_target_rejects_empty_path() {
746 assert!(switch_target(Some(""), None).is_err());
747 assert!(switch_target(Some(" "), None).is_err());
748 let err = switch_target(Some(" "), None).unwrap_err().to_string();
749 assert!(err.contains("must not be empty"), "got: {err}");
750 }
751
752 #[tokio::test]
753 async fn resolve_name_to_binding_is_case_sensitive() {
754 let body = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"visdom-web","github_url":null,"clone_status":null}]"#;
755 let resp = format!(
756 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
757 body.len(),
758 body
759 );
760 let base = spawn_once(Box::leak(resp.into_boxed_str()));
761 let client = ApiClient::new(&base, Some("tok"));
762 let err = resolve_name_to_binding("Visdom-Web", "acme", &client)
763 .await
764 .unwrap_err()
765 .to_string();
766 assert!(
767 err.contains("no repo named 'Visdom-Web'"),
768 "case must not match: {err}"
769 );
770 }
771
772 #[tokio::test]
777 async fn resolve_name_to_binding_propagates_list_error() {
778 let resp =
779 "HTTP/1.1 500 Internal Server Error\r\nContent-Length: 0\r\nConnection: close\r\n\r\n";
780 let base = spawn_once(resp);
781 let client = ApiClient::new(&base, Some("tok"));
782 assert!(resolve_name_to_binding("anything", "acme", &client)
783 .await
784 .is_err());
785 }
786}