1use std::collections::HashSet;
6use std::path::Path;
7
8use crate::api_client::{resolve_client, ApiClient, ProjectListItem};
9use crate::resolution::{
10 effective_project, git_remote_url, resolve_effective_project, ProjectResolveInputs,
11 ProjectSource,
12};
13use crate::session_state::{self, ProjectBinding, SessionState};
14
15#[derive(clap::Subcommand)]
17pub enum ProjectCmd {
18 Switch {
21 name: String,
23 #[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)]
42 project: Option<String>,
43 },
44}
45
46pub async fn run(
47 cmd: ProjectCmd,
48 project_root: &Path,
49 cwd: &Path,
50) -> Result<(), Box<dyn std::error::Error>> {
51 match cmd {
52 ProjectCmd::Switch {
53 name,
54 user,
55 session_id,
56 } => switch(&name, user, session_id.as_deref(), project_root, cwd).await,
57 ProjectCmd::Status {
58 session_id,
59 project,
60 } => status(session_id.as_deref(), project.as_deref(), project_root, cwd).await,
61 }
62}
63
64fn resolve_project_name<'a>(
66 items: &'a [ProjectListItem],
67 name: &str,
68) -> Result<&'a ProjectListItem, String> {
69 items.iter().find(|p| p.name == name).ok_or_else(|| {
70 let mut names: Vec<&str> = items.iter().map(|p| p.name.as_str()).collect();
71 names.sort_unstable();
72 format!(
73 "project '{name}' not found. Available: {}",
74 names.join(", ")
75 )
76 })
77}
78
79async fn resolve_switch_project(
86 name: &str,
87 client: &ApiClient,
88 check_codebase: bool,
89 cwd: &Path,
90) -> Result<ProjectBinding, Box<dyn std::error::Error>> {
91 let items = client.list_projects().await?;
92 let matched = resolve_project_name(&items, name)
93 .map_err(|e| -> Box<dyn std::error::Error> { e.into() })?;
94 let project_id = matched.id;
95 let project_name = matched.name.clone();
96
97 if check_codebase {
98 if let Some(git_url) = git_remote_url(cwd) {
99 if let Some(remote) = client.resolve_remote(&git_url).await? {
100 let codebase_repo_ids: HashSet<uuid::Uuid> = client
101 .get_remote_repos(remote.remote_id)
102 .await?
103 .into_iter()
104 .map(|r| r.id)
105 .collect();
106 let project_repo_ids: HashSet<uuid::Uuid> = client
107 .get_project(project_id)
108 .await?
109 .repos
110 .into_iter()
111 .map(|r| r.id)
112 .collect();
113 if codebase_repo_ids.is_disjoint(&project_repo_ids) {
114 return Err(
115 format!("project '{name}' does not contain the current codebase").into(),
116 );
117 }
118 }
119 }
123 }
126
127 Ok(ProjectBinding {
128 project_id: project_id.to_string(),
129 project_name,
130 updated_at: chrono::Utc::now().to_rfc3339(),
131 })
132}
133
134#[derive(Debug)]
138enum SwitchDest {
139 Session(String),
140 UserDefault,
141}
142
143fn switch_destination(user: bool, session_id: Option<String>) -> SwitchDest {
144 if user {
145 return SwitchDest::UserDefault;
146 }
147 match session_id {
148 Some(id) => SwitchDest::Session(id),
149 None => SwitchDest::UserDefault,
150 }
151}
152
153async fn switch(
154 name: &str,
155 user: bool,
156 session_id: Option<&str>,
157 project_root: &Path,
158 cwd: &Path,
159) -> Result<(), Box<dyn std::error::Error>> {
160 let client = resolve_client(project_root)?;
161 let session = crate::commands::repo::resolve_session_id(session_id).ok();
162 let dest = switch_destination(user, session);
163 let check_codebase = matches!(dest, SwitchDest::Session(_));
164 let binding = resolve_switch_project(name, &client, check_codebase, cwd).await?;
165
166 match dest {
167 SwitchDest::Session(id) => {
168 let mut state = session_state::load(&id);
169 state.active_project = Some(binding.clone());
170 session_state::save(&id, &state)?;
171 println!("bound session {id} to project {}", binding.project_name);
172 }
173 SwitchDest::UserDefault => {
174 crate::user_project_default::save(&binding)?;
175 println!(
176 "set user-level default project {}; applies to new sessions without their own binding (the current session, if any, is unchanged — omit --user to bind this session)",
177 binding.project_name
178 );
179 }
180 }
181 Ok(())
182}
183
184fn enrich_deduced_name(
192 effective: Option<(ProjectBinding, ProjectSource)>,
193 items: Option<&[ProjectListItem]>,
194) -> Option<(ProjectBinding, ProjectSource)> {
195 effective.map(|(mut binding, source)| {
196 if source == ProjectSource::Deduced && binding.project_name.is_empty() {
197 if let Some(items) = items {
198 if let Ok(id) = binding.project_id.parse::<uuid::Uuid>() {
199 if let Some(matched) = items.iter().find(|p| p.id == id) {
200 binding.project_name = matched.name.clone();
201 }
202 }
203 }
204 }
205 (binding, source)
206 })
207}
208
209fn format_status(effective: Option<(&ProjectBinding, ProjectSource)>) -> String {
215 match effective {
216 Some((b, source)) => {
217 let label = if b.project_name.is_empty() {
218 &b.project_id
219 } else {
220 &b.project_name
221 };
222 format!("project: {label} via {source}")
223 }
224 None => "no project bound".to_string(),
225 }
226}
227
228async fn status(
229 session_id: Option<&str>,
230 project_flag_name: Option<&str>,
231 project_root: &Path,
232 cwd: &Path,
233) -> Result<(), Box<dyn std::error::Error>> {
234 let session = match crate::commands::repo::resolve_session_id(session_id) {
237 Ok(id) => session_state::load(&id),
238 Err(_) => {
239 eprintln!(
240 "warning: no session id (pass --session-id or set TRACEVAULT_SESSION_ID); \
241 showing binding without session context"
242 );
243 SessionState::default()
244 }
245 };
246 let worktree = crate::paths::worktree_toplevel(cwd);
247 let config_default_name =
248 crate::config::TracevaultConfig::load(project_root).and_then(|c| c.default_project);
249 let user_default = crate::user_project_default::load();
250 let git_url = git_remote_url(cwd);
251
252 let effective = match resolve_client(project_root) {
258 Ok(client) => {
259 let items = if project_flag_name.is_some() || config_default_name.is_some() {
260 client.list_projects().await.ok()
261 } else {
262 None
263 };
264 let to_binding = |name: &str| -> Option<ProjectBinding> {
265 let matched = items
266 .as_ref()
267 .and_then(|items| resolve_project_name(items, name).ok())?;
268 Some(ProjectBinding {
269 project_id: matched.id.to_string(),
270 project_name: matched.name.clone(),
271 updated_at: chrono::Utc::now().to_rfc3339(),
272 })
273 };
274
275 let project_flag = project_flag_name.and_then(to_binding);
276 if let Some(name) = project_flag_name {
277 if project_flag.is_none() {
278 eprintln!(
279 "warning: --project '{name}' could not be resolved; ignoring the override"
280 );
281 }
282 }
283 let config_default = config_default_name.as_deref().and_then(to_binding);
284 if let Some(name) = config_default_name.as_deref() {
285 if config_default.is_none() {
286 eprintln!(
287 "warning: configured default_project '{name}' could not be resolved; ignoring it"
288 );
289 }
290 }
291
292 let inputs = ProjectResolveInputs {
293 project_flag,
294 session: &session,
295 worktree_path: Some(&worktree),
296 config_default,
297 };
298 let resolved =
306 match resolve_effective_project(&inputs, user_default, git_url.as_deref(), &client)
307 .await
308 {
309 Ok(effective) => effective,
310 Err(e) => {
311 println!("project: unresolved — {e}");
312 return Ok(());
313 }
314 };
315 enrich_deduced_name(resolved, items.as_deref())
316 }
317 Err(e) => {
318 eprintln!("warning: could not resolve credentials ({e}); showing local status only");
319 let inputs = ProjectResolveInputs {
320 project_flag: None,
321 session: &session,
322 worktree_path: Some(&worktree),
323 config_default: None,
324 };
325 effective_project(&inputs)
326 }
327 };
328
329 println!(
330 "{}",
331 format_status(effective.as_ref().map(|(b, s)| (b, *s)))
332 );
333 Ok(())
334}
335
336#[cfg(test)]
337mod tests {
338 use super::*;
339 use std::io::{BufRead, BufReader, Write};
340 use std::net::TcpListener;
341 use std::thread;
342
343 #[test]
344 fn resolve_project_name_exact_match_and_miss() {
345 let items = vec![
346 ProjectListItem {
347 id: uuid::Uuid::nil(),
348 name: "payments".into(),
349 },
350 ProjectListItem {
351 id: uuid::Uuid::from_u128(2),
352 name: "web".into(),
353 },
354 ];
355 let ok = resolve_project_name(&items, "web").unwrap();
356 assert_eq!(ok.id, uuid::Uuid::from_u128(2));
357 let err = resolve_project_name(&items, "Web").unwrap_err(); assert!(err.contains("payments") && err.contains("web")); }
360
361 #[test]
362 fn switch_destination_user_flag_forces_user_default() {
363 assert!(matches!(
364 switch_destination(true, Some("sess-1".to_string())),
365 SwitchDest::UserDefault
366 ));
367 assert!(matches!(
368 switch_destination(true, None),
369 SwitchDest::UserDefault
370 ));
371 }
372
373 #[test]
374 fn switch_destination_session_when_present_and_no_user_flag() {
375 assert!(matches!(
376 switch_destination(false, Some("sess-1".to_string())),
377 SwitchDest::Session(id) if id == "sess-1"
378 ));
379 }
380
381 #[test]
382 fn switch_destination_user_default_when_no_session() {
383 assert!(matches!(
384 switch_destination(false, None),
385 SwitchDest::UserDefault
386 ));
387 }
388
389 fn pb(name: &str) -> ProjectBinding {
390 ProjectBinding {
391 project_id: format!("id-{name}"),
392 project_name: name.into(),
393 updated_at: "t".into(),
394 }
395 }
396
397 #[test]
398 fn format_status_none() {
399 assert_eq!(format_status(None), "no project bound");
400 }
401
402 #[test]
403 fn format_status_project_flag() {
404 let b = pb("web");
405 assert_eq!(
406 format_status(Some((&b, ProjectSource::ProjectFlag))),
407 "project: web via --project override"
408 );
409 }
410
411 #[test]
412 fn format_status_session_active() {
413 let b = pb("payments");
414 assert_eq!(
415 format_status(Some((&b, ProjectSource::SessionActive))),
416 "project: payments via session (project switch)"
417 );
418 }
419
420 #[test]
421 fn format_status_deduced_falls_back_to_id_when_name_empty() {
422 let b = ProjectBinding {
423 project_id: "deduced-id".into(),
424 project_name: String::new(),
425 updated_at: "".into(),
426 };
427 assert_eq!(
428 format_status(Some((&b, ProjectSource::Deduced))),
429 "project: deduced-id via repo deduction"
430 );
431 }
432
433 #[test]
434 fn format_status_user_default() {
435 let b = pb("payments");
436 assert_eq!(
437 format_status(Some((&b, ProjectSource::UserDefault))),
438 "project: payments via user default (project switch --user)"
439 );
440 }
441
442 fn spawn_once(response: String) -> String {
445 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
446 let addr = listener.local_addr().unwrap();
447 let response: &'static str = Box::leak(response.into_boxed_str());
448 thread::spawn(move || {
449 if let Ok((stream, _)) = listener.accept() {
450 let mut reader = BufReader::new(stream);
451 let mut request_line = String::new();
452 let _ = reader.read_line(&mut request_line);
453 let mut stream = reader.into_inner();
454 let _ = stream.write_all(response.as_bytes());
455 let _ = stream.flush();
456 }
457 });
458 format!("http://{addr}")
459 }
460
461 fn spawn_n(responses: Vec<String>) -> String {
465 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
466 let addr = listener.local_addr().unwrap();
467 thread::spawn(move || {
468 for response in responses {
469 let response: &'static str = Box::leak(response.into_boxed_str());
470 if let Ok((stream, _)) = listener.accept() {
471 let mut reader = BufReader::new(stream);
472 let mut request_line = String::new();
473 let _ = reader.read_line(&mut request_line);
474 let mut stream = reader.into_inner();
475 let _ = stream.write_all(response.as_bytes());
476 let _ = stream.flush();
477 }
478 }
479 });
480 format!("http://{addr}")
481 }
482
483 fn http_200(body: &str) -> String {
484 format!(
485 "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
486 body.len(),
487 body
488 )
489 }
490
491 #[tokio::test]
498 async fn project_switch_happy_path_writes_active_project_to_session_file() {
499 let tmp = tempfile::tempdir().unwrap();
500 crate::test_helpers::init_git_repo(tmp.path()); let state_tmp = tempfile::tempdir().unwrap();
513 let mut _guard = crate::test_helpers::EnvVarGuard::new();
514 _guard.set("XDG_STATE_HOME", state_tmp.path());
515
516 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"},{"id":"22222222-2222-4222-8222-222222222222","name":"web"}]"#;
517 let base = spawn_once(http_200(list));
518 let client = ApiClient::new(&base, Some("tok"));
519
520 let binding = resolve_switch_project("web", &client, true, tmp.path())
521 .await
522 .expect("expected Ok binding");
523 assert_eq!(binding.project_id, "22222222-2222-4222-8222-222222222222");
524 assert_eq!(binding.project_name, "web");
525
526 let session_id = format!("project-switch-test-{}", uuid::Uuid::new_v4());
527 let mut state = session_state::load(&session_id);
528 state.active_project = Some(binding.clone());
529 session_state::save(&session_id, &state).expect("save must succeed");
530
531 let sessions_dir = session_state::sessions_dir().expect("sessions dir must resolve");
532 assert!(sessions_dir.starts_with(state_tmp.path()));
533 let loaded = session_state::load_from(&sessions_dir, &session_id);
534 assert_eq!(loaded.active_project, Some(binding));
535 }
536
537 #[tokio::test]
538 async fn project_switch_errors_when_name_not_found() {
539 let list = r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#;
540 let base = spawn_once(http_200(list));
541 let client = ApiClient::new(&base, Some("tok"));
542
543 let err = resolve_switch_project("web", &client, false, Path::new("/nonexistent"))
544 .await
545 .expect_err("expected Err for an unknown project name");
546 let msg = err.to_string();
547 assert!(msg.contains("not found"), "got: {msg}");
548 assert!(msg.contains("payments"), "got: {msg}");
549 }
550
551 #[tokio::test]
552 async fn project_switch_errors_when_project_does_not_contain_codebase() {
553 let tmp = tempfile::tempdir().unwrap();
554 crate::test_helpers::init_git_repo(tmp.path());
555 let ok = std::process::Command::new("git")
556 .args([
557 "-C",
558 &tmp.path().to_string_lossy(),
559 "remote",
560 "add",
561 "origin",
562 "git@github.com:org/repo.git",
563 ])
564 .status()
565 .expect("git remote add failed")
566 .success();
567 assert!(ok, "git remote add must succeed");
568
569 let list =
570 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
571 let remote_id = "44000761-8d22-4256-bd2c-27a0ba278c6f";
572 let remote = format!(
573 r#"{{"remote_id":"{remote_id}","name":"repo","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
574 );
575 let codebase_repo_id = "55555555-5555-4555-8555-555555555555";
576 let detail = format!(
577 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":"{codebase_repo_id}","name":"repo"}}]}}"#
578 );
579 let project_detail = r#"{"repos":[{"id":"66666666-6666-4666-8666-666666666666"}]}"#;
580 let base = spawn_n(vec![
581 http_200(&list),
582 http_200(&remote),
583 http_200(&detail),
584 http_200(project_detail),
585 ]);
586 let client = ApiClient::new(&base, Some("tok"));
587
588 let err = resolve_switch_project("payments", &client, true, tmp.path())
589 .await
590 .expect_err("expected Err: project doesn't contain the current codebase");
591 assert!(
592 err.to_string()
593 .contains("does not contain the current codebase"),
594 "got: {err}"
595 );
596 }
597
598 #[tokio::test]
632 async fn switch_without_session_or_user_flag_skips_codebase_check() {
633 let _env_lock = crate::test_helpers::lock_env_mutation().await;
634 let tmp = tempfile::tempdir().unwrap();
635 crate::test_helpers::init_git_repo(tmp.path());
636 let ok = std::process::Command::new("git")
637 .args([
638 "-C",
639 &tmp.path().to_string_lossy(),
640 "remote",
641 "add",
642 "origin",
643 "git@github.com:org/repo.git",
644 ])
645 .status()
646 .expect("git remote add failed")
647 .success();
648 assert!(ok, "git remote add must succeed");
649
650 let list =
651 r#"[{"id":"11111111-1111-4111-8111-111111111111","name":"payments"}]"#.to_string();
652 let base = spawn_once(http_200(&list));
653
654 let config_dir = tmp.path().join(".tracevault");
655 std::fs::create_dir_all(&config_dir).unwrap();
656 std::fs::write(
657 config_dir.join("config.toml"),
658 format!("agent = \"claude-code\"\nserver_url = \"{base}\"\napi_key = \"tok\"\n"),
659 )
660 .unwrap();
661
662 let mut _guard = crate::test_helpers::EnvVarGuard::new();
677 _guard.remove("TRACEVAULT_SESSION_ID");
678 _guard.set("XDG_CONFIG_HOME", tmp.path());
679 _guard.set("TRACEVAULT_SERVER_URL", &base);
680 _guard.set("TRACEVAULT_API_KEY", "tok");
681
682 let result = switch("payments", false, None, tmp.path(), tmp.path()).await;
683 assert!(
684 result.is_ok(),
685 "expected a no-session, non-`--user` switch to skip the codebase check: {result:?}"
686 );
687
688 let saved = crate::user_project_default::load();
689 assert_eq!(
690 saved.map(|b| b.project_name),
691 Some("payments".to_string()),
692 "no-session switch must fall back to the user-level default binding"
693 );
694 }
695
696 fn items() -> Vec<ProjectListItem> {
697 vec![
698 ProjectListItem {
699 id: uuid::Uuid::from_u128(1),
700 name: "payments".into(),
701 },
702 ProjectListItem {
703 id: uuid::Uuid::from_u128(2),
704 name: "web".into(),
705 },
706 ]
707 }
708
709 fn deduced(id: uuid::Uuid) -> (ProjectBinding, ProjectSource) {
710 (
711 ProjectBinding {
712 project_id: id.to_string(),
713 project_name: String::new(),
714 updated_at: "".into(),
715 },
716 ProjectSource::Deduced,
717 )
718 }
719
720 #[test]
721 fn enrich_deduced_name_fills_in_name_when_id_found_in_list() {
722 let effective = Some(deduced(uuid::Uuid::from_u128(2)));
723 let (b, source) = enrich_deduced_name(effective, Some(&items())).unwrap();
724 assert_eq!(b.project_name, "web");
725 assert_eq!(source, ProjectSource::Deduced);
726 }
727
728 #[test]
729 fn enrich_deduced_name_leaves_empty_when_no_list_available() {
730 let effective = Some(deduced(uuid::Uuid::from_u128(2)));
731 let (b, _source) = enrich_deduced_name(effective, None).unwrap();
732 assert_eq!(b.project_name, "");
733 }
734
735 #[test]
736 fn enrich_deduced_name_leaves_empty_when_id_not_in_list() {
737 let effective = Some(deduced(uuid::Uuid::from_u128(999)));
738 let (b, _source) = enrich_deduced_name(effective, Some(&items())).unwrap();
739 assert_eq!(b.project_name, "");
740 }
741
742 #[test]
743 fn enrich_deduced_name_leaves_non_deduced_sources_untouched() {
744 let b = pb("payments");
747 let effective = Some((b.clone(), ProjectSource::SessionActive));
748 let (out, source) = enrich_deduced_name(effective, Some(&items())).unwrap();
749 assert_eq!(out, b);
750 assert_eq!(source, ProjectSource::SessionActive);
751 }
752
753 #[test]
754 fn enrich_deduced_name_passes_through_none() {
755 assert!(enrich_deduced_name(None, Some(&items())).is_none());
756 }
757
758 #[tokio::test]
766 async fn status_reports_ambiguous_deduction_as_informational_not_fatal() {
767 let _env_lock = crate::test_helpers::lock_env_mutation().await;
768 let tmp = tempfile::tempdir().unwrap();
769 crate::test_helpers::init_git_repo(tmp.path());
770 let ok = std::process::Command::new("git")
771 .args([
772 "-C",
773 &tmp.path().to_string_lossy(),
774 "remote",
775 "add",
776 "origin",
777 "git@github.com:org/repo.git",
778 ])
779 .status()
780 .expect("git remote add failed")
781 .success();
782 assert!(ok, "git remote add must succeed");
783
784 let base = spawn_once(
785 "HTTP/1.1 409 Conflict\r\nContent-Type: application/json\r\nContent-Length: 20\r\nConnection: close\r\n\r\n{\"error\":\"multiple\"}"
786 .to_string(),
787 );
788
789 let mut _guard = crate::test_helpers::EnvVarGuard::new();
799 _guard.set("TRACEVAULT_SERVER_URL", &base);
800 _guard.set("TRACEVAULT_API_KEY", "tok");
801
802 let result = status(None, None, tmp.path(), tmp.path()).await;
803
804 assert!(
805 result.is_ok(),
806 "status must degrade gracefully on an ambiguous deduction, not propagate the error: {result:?}"
807 );
808 }
809}