1use std::path::Path;
8use std::process::Command;
9
10use crate::api_client::{ApiClient, RepoListItem, ResolveProjectOutcome};
11use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
12
13pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
18 let out = std::process::Command::new("git")
19 .arg("-C")
20 .arg(path)
21 .args(["remote", "get-url", "origin"])
22 .output()
23 .ok()?;
24 if !out.status.success() {
25 return None;
26 }
27 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
28 if url.is_empty() {
29 None
30 } else {
31 Some(url)
32 }
33}
34
35pub(crate) fn git_repo_name(project_root: &Path) -> String {
41 Command::new("git")
42 .args(["rev-parse", "--show-toplevel"])
43 .current_dir(project_root)
44 .output()
45 .ok()
46 .filter(|o| o.status.success())
47 .and_then(|o| repo_basename(String::from_utf8_lossy(&o.stdout).trim()))
48 .unwrap_or_else(|| "unknown".into())
49}
50
51fn repo_basename(toplevel: &str) -> Option<String> {
58 Path::new(toplevel)
59 .file_name()
60 .map(|n| n.to_string_lossy().into_owned())
61}
62
63#[derive(Debug)]
70pub(crate) enum ResolveRepoByNameError {
71 ListFailed(Box<dyn std::error::Error>),
72 NotFound { repo_name: String },
73}
74
75pub(crate) async fn resolve_repo_by_name(
80 client: &ApiClient,
81 project_root: &Path,
82) -> Result<RepoListItem, ResolveRepoByNameError> {
83 let repo_name = git_repo_name(project_root);
84 let repos = client
85 .list_repos()
86 .await
87 .map_err(ResolveRepoByNameError::ListFailed)?;
88 repos
89 .into_iter()
90 .find(|r| r.name == repo_name)
91 .ok_or(ResolveRepoByNameError::NotFound { repo_name })
92}
93
94pub(crate) fn codebase_line(
100 name: Option<&str>,
101 normalized_url: &str,
102 clone_status: &str,
103) -> String {
104 format!(
105 "codebase: {} ({})",
106 name.unwrap_or(normalized_url),
107 clone_status
108 )
109}
110
111pub(crate) fn pick_status_line(
116 detail_line: Option<String>,
117 resolved_line: Option<String>,
118 cached_name: Option<&str>,
119) -> Option<String> {
120 detail_line
121 .or(resolved_line)
122 .or_else(|| cached_name.map(|n| format!("codebase: {n}")))
123}
124
125pub async fn resolve_path_to_binding(
129 path: &Path,
130 client: &ApiClient,
131) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
132 let Some(git_url) = git_remote_url(path) else {
133 return Ok(None);
134 };
135 let Some(remote) = client.resolve_remote(&git_url).await? else {
140 return Ok(None);
141 };
142 let repos = client.get_remote_repos(remote.remote_id).await?;
143 let Some(first) = repos.into_iter().min_by_key(|r| r.id) else {
144 return Err(format!(
145 "codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
146 remote.name.as_deref().unwrap_or(&remote.normalized_url)
147 )
148 .into());
149 };
150 Ok(Some(RepoBinding {
151 repo_id: first.id.to_string(),
152 git_url: Some(git_url),
153 remote_id: Some(remote.remote_id),
154 codebase_name: remote.name,
155 updated_at: chrono::Utc::now().to_rfc3339(),
156 }))
157}
158
159pub struct ResolveInputs<'a> {
164 pub repo_flag: Option<RepoBinding>,
165 pub session: &'a SessionState,
166 pub worktree_path: Option<&'a str>,
167 pub bound: Option<RepoBinding>,
168 pub user_default: Option<RepoBinding>,
171}
172
173pub struct ProjectResolveInputs<'a> {
177 pub project_flag: Option<ProjectBinding>,
178 pub session: &'a SessionState,
179 pub worktree_path: Option<&'a str>,
180 pub config_default: Option<ProjectBinding>,
181}
182
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum BindingSource {
186 RepoFlag,
188 Subagent,
190 SessionActive,
192 Bound,
194 UserDefault,
196}
197
198impl std::fmt::Display for BindingSource {
199 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
200 let label = match self {
201 BindingSource::RepoFlag => "--path override",
202 BindingSource::Subagent => "subagent worktree override",
203 BindingSource::SessionActive => "session (repo switch)",
204 BindingSource::Bound => "bound .tracevault/config.toml",
205 BindingSource::UserDefault => "user default (repo switch --user)",
206 };
207 f.write_str(label)
208 }
209}
210
211#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub enum ProjectSource {
214 ProjectFlag,
216 Subagent,
218 SessionActive,
220 ConfigDefault,
222 Deduced,
225 UserDefault,
228}
229
230impl std::fmt::Display for ProjectSource {
231 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232 let label = match self {
233 ProjectSource::ProjectFlag => "--project override",
234 ProjectSource::Subagent => "subagent worktree override",
235 ProjectSource::SessionActive => "session (project switch)",
236 ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
237 ProjectSource::Deduced => "repo deduction",
238 ProjectSource::UserDefault => "user default (project switch --user)",
239 };
240 f.write_str(label)
241 }
242}
243
244pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
248 if let Some(b) = inputs.repo_flag {
249 return Some((b, BindingSource::RepoFlag));
250 }
251 if let Some(wt) = inputs.worktree_path {
252 if let Some(b) = inputs.session.subagents.get(wt) {
253 return Some((b.clone(), BindingSource::Subagent));
254 }
255 }
256 if let Some(b) = &inputs.session.active {
257 return Some((b.clone(), BindingSource::SessionActive));
258 }
259 if let Some(b) = inputs.bound {
260 return Some((b, BindingSource::Bound));
261 }
262 inputs.user_default.map(|b| (b, BindingSource::UserDefault))
263}
264
265pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
273 if let Some(b) = &inputs.project_flag {
274 return Some((b.clone(), ProjectSource::ProjectFlag));
275 }
276 if let Some(wt) = inputs.worktree_path {
277 if let Some(b) = inputs.session.subagent_projects.get(wt) {
278 return Some((b.clone(), ProjectSource::Subagent));
279 }
280 }
281 if let Some(b) = &inputs.session.active_project {
282 return Some((b.clone(), ProjectSource::SessionActive));
283 }
284 inputs
285 .config_default
286 .clone()
287 .map(|b| (b, ProjectSource::ConfigDefault))
288}
289
290pub async fn resolve_effective_project(
303 inputs: &ProjectResolveInputs<'_>,
304 user_default: Option<ProjectBinding>,
305 git_url: Option<&str>,
306 client: &ApiClient,
307) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
308 if let Some(hit) = effective_project(inputs) {
310 return Ok(Some(hit));
311 }
312 if let Some(url) = git_url {
314 match client.resolve_project(url).await? {
315 ResolveProjectOutcome::Resolved(pid) => {
316 eprintln!(
317 "warning: no explicit project set; attributing to the project deduced from this repo ({pid}). Set one with `tracevault project switch <name>` or --project."
318 );
319 return Ok(Some((
320 ProjectBinding {
321 project_id: pid.to_string(),
322 project_name: String::new(), updated_at: String::new(),
324 },
325 ProjectSource::Deduced,
326 )));
327 }
328 ResolveProjectOutcome::Ambiguous => {
329 return Err(
330 "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
331 .to_string()
332 .into(),
333 );
334 }
335 ResolveProjectOutcome::None => { }
336 }
337 }
338 Ok(user_default.map(|b| (b, ProjectSource::UserDefault)))
340}
341
342pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
350 Some(RepoBinding {
351 repo_id: config.repo_id.clone()?,
352 git_url: None,
353 remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
354 codebase_name: config.codebase_name.clone(),
355 updated_at: String::new(),
356 })
357}
358
359#[cfg(test)]
360mod tests {
361 use super::*;
362 use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
363 use std::collections::HashMap;
364 use std::io::{BufRead, BufReader, Write};
365 use std::net::{SocketAddr, TcpListener};
366 use std::thread;
367
368 #[test]
369 fn repo_basename_bare_name() {
370 assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
371 }
372
373 #[test]
374 fn repo_basename_nested_path() {
375 assert_eq!(
376 repo_basename("/home/user/code/myrepo"),
377 Some("myrepo".to_string())
378 );
379 }
380
381 #[test]
382 fn repo_basename_trailing_slash() {
383 assert_eq!(
386 repo_basename("/home/user/code/myrepo/"),
387 Some("myrepo".to_string())
388 );
389 }
390
391 #[test]
392 fn repo_basename_dot_git_suffix_directory() {
393 assert_eq!(
397 repo_basename("/srv/repos/myrepo.git"),
398 Some("myrepo.git".to_string())
399 );
400 }
401
402 #[test]
403 fn repo_basename_root_has_no_basename() {
404 assert_eq!(repo_basename("/"), None);
405 }
406
407 fn spawn_once(
413 status: &'static str,
414 body: &'static str,
415 ) -> (SocketAddr, thread::JoinHandle<()>) {
416 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
417 let addr = listener.local_addr().unwrap();
418 let response = http_200(status, body);
419 let handle = thread::spawn(move || {
420 if let Ok((stream, _)) = listener.accept() {
421 let mut reader = BufReader::new(stream);
422 let mut request_line = String::new();
423 let _ = reader.read_line(&mut request_line);
424 let mut stream = reader.into_inner();
425 let _ = stream.write_all(response.as_bytes());
426 let _ = stream.flush();
427 }
428 });
429 (addr, handle)
430 }
431
432 fn http_200(status: &str, body: &str) -> String {
435 format!(
436 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
437 status,
438 body.len(),
439 body
440 )
441 }
442
443 #[tokio::test]
444 async fn deduction_beats_user_default() {
445 let (addr, _h) = spawn_once(
447 "200 OK",
448 "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
449 );
450 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
451 let ud = ProjectBinding {
452 project_id: "user".into(),
453 project_name: "u".into(),
454 updated_at: "".into(),
455 };
456 let inputs = ProjectResolveInputs {
457 project_flag: None,
458 session: &SessionState::default(),
459 worktree_path: None,
460 config_default: None,
461 };
462 let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
463 .await
464 .unwrap()
465 .unwrap();
466 assert_eq!(src, ProjectSource::Deduced);
467 assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
468 }
469
470 #[tokio::test]
471 async fn ambiguous_deduction_errors_when_no_higher_rung() {
472 let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
473 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
474 let inputs = ProjectResolveInputs {
475 project_flag: None,
476 session: &SessionState::default(),
477 worktree_path: None,
478 config_default: None,
479 };
480 let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
481 .await
482 .unwrap_err();
483 assert!(err.to_string().to_lowercase().contains("--project"));
484 }
485
486 #[tokio::test]
487 async fn user_default_used_when_deduction_404() {
488 let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
492 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
493 let ud = ProjectBinding {
494 project_id: "user".into(),
495 project_name: "u".into(),
496 updated_at: "".into(),
497 };
498 let inputs = ProjectResolveInputs {
499 project_flag: None,
500 session: &SessionState::default(),
501 worktree_path: None,
502 config_default: None,
503 };
504 let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
505 .await
506 .unwrap()
507 .unwrap();
508 assert_eq!(src, ProjectSource::UserDefault);
509 assert_eq!(b.project_id, "user");
510 }
511
512 #[tokio::test]
513 async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
514 let (addr, _h) = spawn_once("404 Not Found", "");
518 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
519 let ud = ProjectBinding {
520 project_id: "user".into(),
521 project_name: "u".into(),
522 updated_at: "".into(),
523 };
524 let inputs = ProjectResolveInputs {
525 project_flag: None,
526 session: &SessionState::default(),
527 worktree_path: None,
528 config_default: None,
529 };
530 let err = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
531 .await
532 .expect_err("a bare 404 must not silently fall through to the user default");
533 assert!(err.to_string().to_lowercase().contains("version mismatch"));
534 }
535
536 #[tokio::test]
537 async fn local_rung_skips_server_call() {
538 let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
540 let cfg = ProjectBinding {
541 project_id: "cfg".into(),
542 project_name: "c".into(),
543 updated_at: "".into(),
544 };
545 let inputs = ProjectResolveInputs {
546 project_flag: None,
547 session: &SessionState::default(),
548 worktree_path: None,
549 config_default: Some(cfg),
550 };
551 let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
552 .await
553 .unwrap()
554 .unwrap();
555 assert_eq!(src, ProjectSource::ConfigDefault);
556 }
557
558 fn binding(id: &str) -> RepoBinding {
559 RepoBinding {
560 repo_id: id.into(),
561 git_url: None,
562 remote_id: None,
563 codebase_name: None,
564 updated_at: "t".into(),
565 }
566 }
567
568 #[test]
569 fn effective_binding_precedence() {
570 let session = SessionState {
571 active: Some(binding("session")),
572 subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
573 ..Default::default()
574 };
575
576 let (b, source) = effective_binding(ResolveInputs {
578 repo_flag: Some(binding("flag")),
579 session: &session,
580 worktree_path: Some("/wt/a"),
581 bound: Some(binding("bound")),
582 user_default: Some(binding("userdef")),
583 })
584 .unwrap();
585 assert_eq!(b.repo_id, "flag");
586 assert_eq!(source, BindingSource::RepoFlag);
587
588 let (b, source) = effective_binding(ResolveInputs {
590 repo_flag: None,
591 session: &session,
592 worktree_path: Some("/wt/a"),
593 bound: Some(binding("bound")),
594 user_default: Some(binding("userdef")),
595 })
596 .unwrap();
597 assert_eq!(b.repo_id, "subagent");
598 assert_eq!(source, BindingSource::Subagent);
599
600 let (b, source) = effective_binding(ResolveInputs {
602 repo_flag: None,
603 session: &session,
604 worktree_path: Some("/wt/other"),
605 bound: Some(binding("bound")),
606 user_default: Some(binding("userdef")),
607 })
608 .unwrap();
609 assert_eq!(b.repo_id, "session");
610 assert_eq!(source, BindingSource::SessionActive);
611
612 let empty = SessionState::default();
614 let (b, source) = effective_binding(ResolveInputs {
615 repo_flag: None,
616 session: &empty,
617 worktree_path: None,
618 bound: Some(binding("bound")),
619 user_default: Some(binding("userdef")),
620 })
621 .unwrap();
622 assert_eq!(b.repo_id, "bound");
623 assert_eq!(source, BindingSource::Bound);
624
625 let (b, source) = effective_binding(ResolveInputs {
627 repo_flag: None,
628 session: &empty,
629 worktree_path: None,
630 bound: None,
631 user_default: Some(binding("userdef")),
632 })
633 .unwrap();
634 assert_eq!(b.repo_id, "userdef");
635 assert_eq!(source, BindingSource::UserDefault);
636
637 let got = effective_binding(ResolveInputs {
639 repo_flag: None,
640 session: &empty,
641 worktree_path: None,
642 bound: None,
643 user_default: None,
644 });
645 assert!(got.is_none());
646 }
647
648 #[test]
649 fn binding_source_display_labels() {
650 assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
651 assert_eq!(
652 BindingSource::Subagent.to_string(),
653 "subagent worktree override"
654 );
655 assert_eq!(
656 BindingSource::SessionActive.to_string(),
657 "session (repo switch)"
658 );
659 assert_eq!(
660 BindingSource::Bound.to_string(),
661 "bound .tracevault/config.toml"
662 );
663 assert_eq!(
664 BindingSource::UserDefault.to_string(),
665 "user default (repo switch --user)"
666 );
667 }
668
669 #[test]
670 fn effective_project_precedence_local_rungs() {
671 let pb = |n: &str| ProjectBinding {
672 project_id: n.into(),
673 project_name: n.into(),
674 updated_at: "".into(),
675 };
676 let mut subagent_projects = HashMap::new();
677 subagent_projects.insert("/wt".into(), pb("subagent"));
678 let session = SessionState {
679 active_project: Some(pb("session")),
680 subagent_projects,
681 ..Default::default()
682 };
683
684 let got = effective_project(&ProjectResolveInputs {
686 project_flag: Some(pb("flag")),
687 session: &session,
688 worktree_path: Some("/wt"),
689 config_default: Some(pb("cfg")),
690 })
691 .unwrap();
692 assert_eq!(got.0.project_id, "flag");
693 assert_eq!(got.1, ProjectSource::ProjectFlag);
694
695 let got = effective_project(&ProjectResolveInputs {
697 project_flag: None,
698 session: &session,
699 worktree_path: Some("/wt"),
700 config_default: Some(pb("cfg")),
701 })
702 .unwrap();
703 assert_eq!(got.1, ProjectSource::Subagent);
704 assert_eq!(got.0.project_id, "subagent");
705
706 let got = effective_project(&ProjectResolveInputs {
708 project_flag: None,
709 session: &session,
710 worktree_path: Some("/other"),
711 config_default: Some(pb("cfg")),
712 })
713 .unwrap();
714 assert_eq!(got.1, ProjectSource::SessionActive);
715
716 let got = effective_project(&ProjectResolveInputs {
718 project_flag: None,
719 session: &SessionState::default(),
720 worktree_path: None,
721 config_default: Some(pb("cfg")),
722 })
723 .unwrap();
724 assert_eq!(got.1, ProjectSource::ConfigDefault);
725
726 assert!(effective_project(&ProjectResolveInputs {
728 project_flag: None,
729 session: &SessionState::default(),
730 worktree_path: None,
731 config_default: None,
732 })
733 .is_none());
734 }
735
736 #[test]
737 fn binding_from_config_carries_remote_id_and_codebase_name() {
738 let uuid = uuid::Uuid::new_v4();
739 let config = crate::config::TracevaultConfig {
740 repo_id: Some("repo-1".into()),
741 remote_id: Some(uuid.to_string()),
742 codebase_name: Some("acme/foo".into()),
743 ..Default::default()
744 };
745 let binding = binding_from_config(&config).expect("repo_id present");
746 assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
747 assert_eq!(binding.remote_id, Some(uuid));
748 }
749
750 #[test]
751 fn codebase_line_formats_name_and_status() {
752 let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
753 assert_eq!(line, "codebase: acme/foo (ready)");
754 let line = codebase_line(None, "github.com/acme/foo", "pending");
755 assert_eq!(line, "codebase: github.com/acme/foo (pending)");
756 }
757
758 #[test]
759 fn pick_status_line_detail_wins_over_resolved_and_cached() {
760 assert_eq!(
761 pick_status_line(
762 Some("codebase: a (ready)".to_string()),
763 Some("codebase: b (pending)".to_string()),
764 Some("c"),
765 ),
766 Some("codebase: a (ready)".to_string())
767 );
768 }
769
770 #[test]
771 fn pick_status_line_resolved_wins_over_cached() {
772 assert_eq!(
773 pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
774 Some("codebase: b (pending)".to_string())
775 );
776 }
777
778 #[test]
779 fn pick_status_line_cached_only_is_name_only() {
780 assert_eq!(
781 pick_status_line(None, None, Some("c")),
782 Some("codebase: c".to_string())
783 );
784 }
785
786 #[test]
787 fn pick_status_line_none_when_nothing_available() {
788 assert_eq!(pick_status_line(None, None, None), None);
789 }
790
791 #[tokio::test]
792 async fn resolve_repo_by_name_ok_when_name_matches() {
793 let tmp = tempfile::tempdir().unwrap();
794 crate::test_helpers::init_git_repo(tmp.path());
795 let repo_name = git_repo_name(tmp.path());
796 let body =
797 format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
798 let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
799 let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
800
801 let repo = resolve_repo_by_name(&client, tmp.path())
802 .await
803 .expect("expected a match");
804 assert_eq!(repo.name, repo_name);
805 }
806
807 #[tokio::test]
808 async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
809 let tmp = tempfile::tempdir().unwrap();
810 crate::test_helpers::init_git_repo(tmp.path());
811 let (addr, _h) = spawn_once(
812 "200 OK",
813 r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
814 );
815 let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
816
817 match resolve_repo_by_name(&client, tmp.path()).await {
818 Err(ResolveRepoByNameError::NotFound { .. }) => {}
819 other => panic!(
820 "expected NotFound, got a different outcome: {}",
821 other.is_ok()
822 ),
823 }
824 }
825
826 #[tokio::test]
827 async fn resolve_repo_by_name_list_failed_on_non_2xx() {
828 let tmp = tempfile::tempdir().unwrap();
834 crate::test_helpers::init_git_repo(tmp.path());
835 let (addr, _h) = spawn_once("500 Internal Server Error", "");
836 let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
837
838 match resolve_repo_by_name(&client, tmp.path()).await {
839 Err(ResolveRepoByNameError::ListFailed(e)) => {
840 assert!(e.to_string().contains("500"), "got: {e}");
841 }
842 other => panic!(
843 "expected ListFailed, got a different outcome: {}",
844 other.is_ok()
845 ),
846 }
847 }
848}