1use 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#[derive(clap::Subcommand)]
13pub enum RepoCmd {
14 #[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")]
25 name: Option<String>,
26 #[arg(long)]
29 user: bool,
30 #[arg(long)]
32 session_id: Option<String>,
33 },
34 Status {
36 #[arg(long)]
38 session_id: Option<String>,
39 #[arg(long)]
41 path: Option<String>,
42 },
43 Reset {
45 #[arg(long)]
47 user: bool,
48 #[arg(long)]
50 session_id: Option<String>,
51 },
52}
53
54pub 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
98async 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
114fn apply_switch(state: &mut SessionState, binding: RepoBinding) {
116 state.active = Some(binding);
117}
118
119fn 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 println!("cleared workspace repo binding for session {id}");
136 Ok(())
137}
138
139#[derive(Debug, PartialEq, Eq)]
143enum SwitchTarget<'a> {
144 Path(&'a str),
145}
146
147fn 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#[derive(Debug)]
175enum SwitchDest {
176 Session(String),
177 UserDefault,
178}
179
180fn 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 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 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 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 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
250async 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
289fn 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 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 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 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 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 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 #[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 #[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 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 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 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 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 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 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 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 #[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"); 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 #[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}