1use std::path::Path;
8
9use crate::api_client::{ApiClient, ResolveProjectOutcome};
10use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
11
12pub fn org_slug_precedence(
15 env: Option<String>,
16 creds: Option<String>,
17 bound: Option<String>,
18) -> Option<String> {
19 env.or(creds).or(bound)
20}
21
22pub fn org_slug_for(project_root: &Path) -> Option<String> {
25 let env = std::env::var("TRACEVAULT_ORG_SLUG")
26 .ok()
27 .filter(|s| !s.is_empty());
28 let creds = crate::credentials::Credentials::load().and_then(|c| c.org_slug);
29 let bound = crate::config::TracevaultConfig::load(project_root).and_then(|c| c.org_slug);
30 org_slug_precedence(env, creds, bound)
31}
32
33pub fn org_slug_from_slugs(slugs: &[String]) -> Result<String, String> {
42 let mut unique: Vec<&str> = slugs.iter().map(String::as_str).collect();
43 unique.sort_unstable();
44 unique.dedup();
45 match unique.as_slice() {
46 [] => Err(
47 "could not derive an org from this credential: it has no org membership \
48 (org-scoped API keys are not supported here); set TRACEVAULT_ORG_SLUG"
49 .to_string(),
50 ),
51 [one] => Ok((*one).to_string()),
52 many => Err(format!(
53 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: {}",
54 many.join(", ")
55 )),
56 }
57}
58
59pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
64 let out = std::process::Command::new("git")
65 .arg("-C")
66 .arg(path)
67 .args(["remote", "get-url", "origin"])
68 .output()
69 .ok()?;
70 if !out.status.success() {
71 return None;
72 }
73 let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
74 if url.is_empty() {
75 None
76 } else {
77 Some(url)
78 }
79}
80
81pub(crate) fn codebase_line(
87 name: Option<&str>,
88 normalized_url: &str,
89 clone_status: &str,
90) -> String {
91 format!(
92 "codebase: {} ({})",
93 name.unwrap_or(normalized_url),
94 clone_status
95 )
96}
97
98pub(crate) fn pick_status_line(
103 detail_line: Option<String>,
104 resolved_line: Option<String>,
105 cached_name: Option<&str>,
106) -> Option<String> {
107 detail_line
108 .or(resolved_line)
109 .or_else(|| cached_name.map(|n| format!("codebase: {n}")))
110}
111
112pub async fn resolve_path_to_binding(
116 path: &Path,
117 org_slug: &str,
118 client: &ApiClient,
119) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
120 let Some(git_url) = git_remote_url(path) else {
121 return Ok(None);
122 };
123 let Some(remote) = client.resolve_remote(org_slug, &git_url).await? else {
128 return Ok(None);
129 };
130 let repos = client.get_remote_repos(org_slug, remote.remote_id).await?;
131 let Some(first) = repos.into_iter().min_by_key(|r| r.id) else {
132 return Err(format!(
133 "codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
134 remote.name.as_deref().unwrap_or(&remote.normalized_url)
135 )
136 .into());
137 };
138 Ok(Some(RepoBinding {
139 org_slug: org_slug.to_string(),
140 repo_id: first.id.to_string(),
141 git_url: Some(git_url),
142 remote_id: Some(remote.remote_id),
143 codebase_name: remote.name,
144 updated_at: chrono::Utc::now().to_rfc3339(),
145 }))
146}
147
148pub struct ResolveInputs<'a> {
153 pub repo_flag: Option<RepoBinding>,
154 pub session: &'a SessionState,
155 pub worktree_path: Option<&'a str>,
156 pub bound: Option<RepoBinding>,
157 pub user_default: Option<RepoBinding>,
160}
161
162pub struct ProjectResolveInputs<'a> {
166 pub project_flag: Option<ProjectBinding>,
167 pub session: &'a SessionState,
168 pub worktree_path: Option<&'a str>,
169 pub config_default: Option<ProjectBinding>,
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
174pub enum BindingSource {
175 RepoFlag,
177 Subagent,
179 SessionActive,
181 Bound,
183 UserDefault,
185}
186
187impl std::fmt::Display for BindingSource {
188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189 let label = match self {
190 BindingSource::RepoFlag => "--path override",
191 BindingSource::Subagent => "subagent worktree override",
192 BindingSource::SessionActive => "session (repo switch)",
193 BindingSource::Bound => "bound .tracevault/config.toml",
194 BindingSource::UserDefault => "user default (repo switch --user)",
195 };
196 f.write_str(label)
197 }
198}
199
200#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202pub enum ProjectSource {
203 ProjectFlag,
205 Subagent,
207 SessionActive,
209 ConfigDefault,
211 Deduced,
214 UserDefault,
217}
218
219impl std::fmt::Display for ProjectSource {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 let label = match self {
222 ProjectSource::ProjectFlag => "--project override",
223 ProjectSource::Subagent => "subagent worktree override",
224 ProjectSource::SessionActive => "session (project switch)",
225 ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
226 ProjectSource::Deduced => "repo deduction",
227 ProjectSource::UserDefault => "user default (project switch --user)",
228 };
229 f.write_str(label)
230 }
231}
232
233pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
237 if let Some(b) = inputs.repo_flag {
238 return Some((b, BindingSource::RepoFlag));
239 }
240 if let Some(wt) = inputs.worktree_path {
241 if let Some(b) = inputs.session.subagents.get(wt) {
242 return Some((b.clone(), BindingSource::Subagent));
243 }
244 }
245 if let Some(b) = &inputs.session.active {
246 return Some((b.clone(), BindingSource::SessionActive));
247 }
248 if let Some(b) = inputs.bound {
249 return Some((b, BindingSource::Bound));
250 }
251 inputs.user_default.map(|b| (b, BindingSource::UserDefault))
252}
253
254pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
262 if let Some(b) = &inputs.project_flag {
263 return Some((b.clone(), ProjectSource::ProjectFlag));
264 }
265 if let Some(wt) = inputs.worktree_path {
266 if let Some(b) = inputs.session.subagent_projects.get(wt) {
267 return Some((b.clone(), ProjectSource::Subagent));
268 }
269 }
270 if let Some(b) = &inputs.session.active_project {
271 return Some((b.clone(), ProjectSource::SessionActive));
272 }
273 inputs
274 .config_default
275 .clone()
276 .map(|b| (b, ProjectSource::ConfigDefault))
277}
278
279pub async fn resolve_effective_project(
292 inputs: &ProjectResolveInputs<'_>,
293 user_default: Option<ProjectBinding>,
294 org_slug: &str,
295 git_url: Option<&str>,
296 client: &ApiClient,
297) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
298 if let Some(hit) = effective_project(inputs) {
300 return Ok(Some(hit));
301 }
302 if let Some(url) = git_url {
304 match client.resolve_project(org_slug, url).await? {
305 ResolveProjectOutcome::Resolved(pid) => {
306 eprintln!(
307 "warning: no explicit project set; attributing to the project deduced from this repo ({pid}). Set one with `tracevault project switch <name>` or --project."
308 );
309 return Ok(Some((
310 ProjectBinding {
311 org_slug: org_slug.to_string(),
312 project_id: pid.to_string(),
313 project_name: String::new(), updated_at: String::new(),
315 },
316 ProjectSource::Deduced,
317 )));
318 }
319 ResolveProjectOutcome::Ambiguous => {
320 return Err(format!(
321 "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override (org {org_slug})"
322 )
323 .into());
324 }
325 ResolveProjectOutcome::None => { }
326 }
327 }
328 Ok(user_default.map(|b| (b, ProjectSource::UserDefault)))
330}
331
332pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
340 Some(RepoBinding {
341 org_slug: config.org_slug.clone()?,
342 repo_id: config.repo_id.clone()?,
343 git_url: None,
344 remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
345 codebase_name: config.codebase_name.clone(),
346 updated_at: String::new(),
347 })
348}
349
350#[cfg(test)]
351mod tests {
352 use super::*;
353 use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
354 use std::collections::HashMap;
355 use std::io::{BufRead, BufReader, Write};
356 use std::net::{SocketAddr, TcpListener};
357 use std::thread;
358
359 fn spawn_once(
365 status: &'static str,
366 body: &'static str,
367 ) -> (SocketAddr, thread::JoinHandle<()>) {
368 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
369 let addr = listener.local_addr().unwrap();
370 let response = http_200(status, body);
371 let handle = thread::spawn(move || {
372 if let Ok((stream, _)) = listener.accept() {
373 let mut reader = BufReader::new(stream);
374 let mut request_line = String::new();
375 let _ = reader.read_line(&mut request_line);
376 let mut stream = reader.into_inner();
377 let _ = stream.write_all(response.as_bytes());
378 let _ = stream.flush();
379 }
380 });
381 (addr, handle)
382 }
383
384 fn http_200(status: &str, body: &str) -> String {
387 format!(
388 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
389 status,
390 body.len(),
391 body
392 )
393 }
394
395 #[tokio::test]
396 async fn deduction_beats_user_default() {
397 let (addr, _h) = spawn_once(
399 "200 OK",
400 "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
401 );
402 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
403 let ud = ProjectBinding {
404 org_slug: "o".into(),
405 project_id: "user".into(),
406 project_name: "u".into(),
407 updated_at: "".into(),
408 };
409 let inputs = ProjectResolveInputs {
410 project_flag: None,
411 session: &SessionState::default(),
412 worktree_path: None,
413 config_default: None,
414 };
415 let (b, src) =
416 resolve_effective_project(&inputs, Some(ud), "org", Some("git@x:y.git"), &client)
417 .await
418 .unwrap()
419 .unwrap();
420 assert_eq!(src, ProjectSource::Deduced);
421 assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
422 }
423
424 #[tokio::test]
425 async fn ambiguous_deduction_errors_when_no_higher_rung() {
426 let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
427 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
428 let inputs = ProjectResolveInputs {
429 project_flag: None,
430 session: &SessionState::default(),
431 worktree_path: None,
432 config_default: None,
433 };
434 let err = resolve_effective_project(&inputs, None, "org", Some("git@x:y.git"), &client)
435 .await
436 .unwrap_err();
437 assert!(err.to_string().to_lowercase().contains("--project"));
438 }
439
440 #[tokio::test]
441 async fn user_default_used_when_deduction_404() {
442 let (addr, _h) = spawn_once("404 Not Found", "{}");
443 let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
444 let ud = ProjectBinding {
445 org_slug: "o".into(),
446 project_id: "user".into(),
447 project_name: "u".into(),
448 updated_at: "".into(),
449 };
450 let inputs = ProjectResolveInputs {
451 project_flag: None,
452 session: &SessionState::default(),
453 worktree_path: None,
454 config_default: None,
455 };
456 let (b, src) =
457 resolve_effective_project(&inputs, Some(ud), "org", Some("git@x:y.git"), &client)
458 .await
459 .unwrap()
460 .unwrap();
461 assert_eq!(src, ProjectSource::UserDefault);
462 assert_eq!(b.project_id, "user");
463 }
464
465 #[tokio::test]
466 async fn local_rung_skips_server_call() {
467 let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
469 let cfg = ProjectBinding {
470 org_slug: "o".into(),
471 project_id: "cfg".into(),
472 project_name: "c".into(),
473 updated_at: "".into(),
474 };
475 let inputs = ProjectResolveInputs {
476 project_flag: None,
477 session: &SessionState::default(),
478 worktree_path: None,
479 config_default: Some(cfg),
480 };
481 let (_b, src) =
482 resolve_effective_project(&inputs, None, "org", Some("git@x:y.git"), &client)
483 .await
484 .unwrap()
485 .unwrap();
486 assert_eq!(src, ProjectSource::ConfigDefault);
487 }
488
489 fn binding(id: &str) -> RepoBinding {
490 RepoBinding {
491 org_slug: "org".into(),
492 repo_id: id.into(),
493 git_url: None,
494 remote_id: None,
495 codebase_name: None,
496 updated_at: "t".into(),
497 }
498 }
499
500 #[test]
501 fn effective_binding_precedence() {
502 let session = SessionState {
503 active: Some(binding("session")),
504 subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
505 ..Default::default()
506 };
507
508 let (b, source) = effective_binding(ResolveInputs {
510 repo_flag: Some(binding("flag")),
511 session: &session,
512 worktree_path: Some("/wt/a"),
513 bound: Some(binding("bound")),
514 user_default: Some(binding("userdef")),
515 })
516 .unwrap();
517 assert_eq!(b.repo_id, "flag");
518 assert_eq!(source, BindingSource::RepoFlag);
519
520 let (b, source) = effective_binding(ResolveInputs {
522 repo_flag: None,
523 session: &session,
524 worktree_path: Some("/wt/a"),
525 bound: Some(binding("bound")),
526 user_default: Some(binding("userdef")),
527 })
528 .unwrap();
529 assert_eq!(b.repo_id, "subagent");
530 assert_eq!(source, BindingSource::Subagent);
531
532 let (b, source) = effective_binding(ResolveInputs {
534 repo_flag: None,
535 session: &session,
536 worktree_path: Some("/wt/other"),
537 bound: Some(binding("bound")),
538 user_default: Some(binding("userdef")),
539 })
540 .unwrap();
541 assert_eq!(b.repo_id, "session");
542 assert_eq!(source, BindingSource::SessionActive);
543
544 let empty = SessionState::default();
546 let (b, source) = effective_binding(ResolveInputs {
547 repo_flag: None,
548 session: &empty,
549 worktree_path: None,
550 bound: Some(binding("bound")),
551 user_default: Some(binding("userdef")),
552 })
553 .unwrap();
554 assert_eq!(b.repo_id, "bound");
555 assert_eq!(source, BindingSource::Bound);
556
557 let (b, source) = effective_binding(ResolveInputs {
559 repo_flag: None,
560 session: &empty,
561 worktree_path: None,
562 bound: None,
563 user_default: Some(binding("userdef")),
564 })
565 .unwrap();
566 assert_eq!(b.repo_id, "userdef");
567 assert_eq!(source, BindingSource::UserDefault);
568
569 let got = effective_binding(ResolveInputs {
571 repo_flag: None,
572 session: &empty,
573 worktree_path: None,
574 bound: None,
575 user_default: None,
576 });
577 assert!(got.is_none());
578 }
579
580 #[test]
581 fn binding_source_display_labels() {
582 assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
583 assert_eq!(
584 BindingSource::Subagent.to_string(),
585 "subagent worktree override"
586 );
587 assert_eq!(
588 BindingSource::SessionActive.to_string(),
589 "session (repo switch)"
590 );
591 assert_eq!(
592 BindingSource::Bound.to_string(),
593 "bound .tracevault/config.toml"
594 );
595 assert_eq!(
596 BindingSource::UserDefault.to_string(),
597 "user default (repo switch --user)"
598 );
599 }
600
601 #[test]
602 fn effective_project_precedence_local_rungs() {
603 let pb = |n: &str| ProjectBinding {
604 org_slug: "o".into(),
605 project_id: n.into(),
606 project_name: n.into(),
607 updated_at: "".into(),
608 };
609 let mut subagent_projects = HashMap::new();
610 subagent_projects.insert("/wt".into(), pb("subagent"));
611 let session = SessionState {
612 active_project: Some(pb("session")),
613 subagent_projects,
614 ..Default::default()
615 };
616
617 let got = effective_project(&ProjectResolveInputs {
619 project_flag: Some(pb("flag")),
620 session: &session,
621 worktree_path: Some("/wt"),
622 config_default: Some(pb("cfg")),
623 })
624 .unwrap();
625 assert_eq!(got.0.project_id, "flag");
626 assert_eq!(got.1, ProjectSource::ProjectFlag);
627
628 let got = effective_project(&ProjectResolveInputs {
630 project_flag: None,
631 session: &session,
632 worktree_path: Some("/wt"),
633 config_default: Some(pb("cfg")),
634 })
635 .unwrap();
636 assert_eq!(got.1, ProjectSource::Subagent);
637 assert_eq!(got.0.project_id, "subagent");
638
639 let got = effective_project(&ProjectResolveInputs {
641 project_flag: None,
642 session: &session,
643 worktree_path: Some("/other"),
644 config_default: Some(pb("cfg")),
645 })
646 .unwrap();
647 assert_eq!(got.1, ProjectSource::SessionActive);
648
649 let got = effective_project(&ProjectResolveInputs {
651 project_flag: None,
652 session: &SessionState::default(),
653 worktree_path: None,
654 config_default: Some(pb("cfg")),
655 })
656 .unwrap();
657 assert_eq!(got.1, ProjectSource::ConfigDefault);
658
659 assert!(effective_project(&ProjectResolveInputs {
661 project_flag: None,
662 session: &SessionState::default(),
663 worktree_path: None,
664 config_default: None,
665 })
666 .is_none());
667 }
668
669 #[test]
670 fn org_slug_precedence_order() {
671 assert_eq!(
672 org_slug_precedence(
673 Some("envorg".into()),
674 Some("creds".into()),
675 Some("bound".into())
676 ),
677 Some("envorg".into())
678 );
679 assert_eq!(
680 org_slug_precedence(None, Some("creds".into()), Some("bound".into())),
681 Some("creds".into())
682 );
683 assert_eq!(
684 org_slug_precedence(None, None, Some("bound".into())),
685 Some("bound".into())
686 );
687 assert_eq!(org_slug_precedence(None, None, None), None);
688 }
691
692 #[test]
693 fn org_slug_from_slugs_single() {
694 assert_eq!(
695 org_slug_from_slugs(&["acme".to_string()]),
696 Ok("acme".to_string())
697 );
698 }
699
700 #[test]
701 fn org_slug_from_slugs_none_errors() {
702 let err = org_slug_from_slugs(&[]).unwrap_err();
703 assert_eq!(
704 err,
705 "could not derive an org from this credential: it has no org membership \
706 (org-scoped API keys are not supported here); set TRACEVAULT_ORG_SLUG"
707 );
708 }
709
710 #[test]
711 fn org_slug_from_slugs_multiple_lists_them() {
712 let err = org_slug_from_slugs(&["acme".to_string(), "globex".to_string()]).unwrap_err();
713 assert_eq!(
714 err,
715 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: acme, globex"
716 );
717 }
718
719 #[test]
720 fn org_slug_from_slugs_single_org_duplicated_is_not_multi() {
721 assert_eq!(
723 org_slug_from_slugs(&["acme".to_string(), "acme".to_string()]),
724 Ok("acme".to_string())
725 );
726 }
727
728 #[test]
729 fn binding_from_config_carries_remote_id_and_codebase_name() {
730 let uuid = uuid::Uuid::new_v4();
731 let config = crate::config::TracevaultConfig {
732 org_slug: Some("acme".into()),
733 repo_id: Some("repo-1".into()),
734 remote_id: Some(uuid.to_string()),
735 codebase_name: Some("acme/foo".into()),
736 ..Default::default()
737 };
738 let binding = binding_from_config(&config).expect("org_slug + repo_id present");
739 assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
740 assert_eq!(binding.remote_id, Some(uuid));
741 }
742
743 #[test]
744 fn codebase_line_formats_name_and_status() {
745 let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
746 assert_eq!(line, "codebase: acme/foo (ready)");
747 let line = codebase_line(None, "github.com/acme/foo", "pending");
748 assert_eq!(line, "codebase: github.com/acme/foo (pending)");
749 }
750
751 #[test]
752 fn pick_status_line_detail_wins_over_resolved_and_cached() {
753 assert_eq!(
754 pick_status_line(
755 Some("codebase: a (ready)".to_string()),
756 Some("codebase: b (pending)".to_string()),
757 Some("c"),
758 ),
759 Some("codebase: a (ready)".to_string())
760 );
761 }
762
763 #[test]
764 fn pick_status_line_resolved_wins_over_cached() {
765 assert_eq!(
766 pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
767 Some("codebase: b (pending)".to_string())
768 );
769 }
770
771 #[test]
772 fn pick_status_line_cached_only_is_name_only() {
773 assert_eq!(
774 pick_status_line(None, None, Some("c")),
775 Some("codebase: c".to_string())
776 );
777 }
778
779 #[test]
780 fn pick_status_line_none_when_nothing_available() {
781 assert_eq!(pick_status_line(None, None, None), None);
782 }
783
784 #[test]
785 fn org_slug_from_slugs_multiple_sorted_and_deduped() {
786 let err = org_slug_from_slugs(&[
788 "globex".to_string(),
789 "acme".to_string(),
790 "globex".to_string(),
791 ])
792 .unwrap_err();
793 assert_eq!(
794 err,
795 "credential belongs to multiple orgs; set TRACEVAULT_ORG_SLUG to one of: acme, globex"
796 );
797 }
798}