Skip to main content

tracevault_cli/
api_client.rs

1use serde::{Deserialize, Serialize};
2use std::error::Error;
3use std::path::Path;
4use url::Url;
5
6pub struct ApiClient {
7    base_url: String,
8    api_key: Option<String>,
9    client: reqwest::Client,
10}
11
12#[derive(Serialize)]
13pub struct RegisterRepoRequest {
14    pub repo_name: String,
15    pub github_url: Option<String>,
16}
17
18#[derive(Deserialize)]
19pub struct RegisterRepoResponse {
20    pub repo_id: uuid::Uuid,
21}
22
23#[derive(Deserialize)]
24pub struct ResolveRemoteResponse {
25    pub remote_id: uuid::Uuid,
26    #[serde(default)]
27    pub name: Option<String>,
28    pub normalized_url: String,
29    pub clone_status: String,
30}
31
32#[derive(Deserialize)]
33pub struct RemoteRepoRef {
34    pub id: uuid::Uuid,
35    // Reserved for display (e.g. a future `repo status`/error message listing
36    // a codebase's linked repos by name); not read by any caller yet.
37    #[allow(dead_code)]
38    pub name: String,
39}
40
41// The server's RemoteDetailResponse flattens the remote fields at top level and
42// adds a `repos` array; serde ignores any other top-level fields.
43#[derive(Deserialize)]
44pub struct RemoteDetail {
45    #[serde(default)]
46    pub name: Option<String>,
47    pub normalized_url: String,
48    pub clone_status: String,
49    pub repos: Vec<RemoteRepoRef>,
50}
51
52#[derive(Deserialize)]
53pub struct DeviceAuthResponse {
54    pub token: String,
55}
56
57#[derive(Deserialize)]
58pub struct DeviceStatusResponse {
59    pub status: String,
60    pub token: Option<String>,
61    pub email: Option<String>,
62}
63
64#[derive(Debug, Serialize)]
65pub struct CheckPoliciesRequest {
66    pub sessions: Vec<SessionCheckData>,
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub commit_sha: Option<String>,
69}
70
71#[derive(Debug, Serialize)]
72pub struct SessionCheckData {
73    pub session_id: String,
74    pub tool_calls: Option<serde_json::Value>,
75    pub files_modified: Option<Vec<String>>,
76    pub total_tool_calls: Option<i32>,
77}
78
79#[derive(Debug, Deserialize)]
80pub struct CheckPoliciesResponse {
81    pub passed: bool,
82    pub results: Vec<CheckResultItem>,
83    pub blocked: bool,
84}
85
86#[derive(Debug, Deserialize)]
87pub struct CheckResultItem {
88    pub rule_name: String,
89    pub result: String,
90    pub action: String,
91    pub severity: String,
92    pub details: String,
93}
94
95#[derive(Debug, Deserialize)]
96pub struct RepoListItem {
97    pub id: uuid::Uuid,
98    pub name: String,
99    #[serde(default)]
100    pub github_url: Option<String>,
101    #[serde(default)]
102    pub clone_status: Option<String>,
103}
104
105/// Response shape for the `policies/agent-instructions` endpoint.
106#[derive(Debug, Clone, Deserialize)]
107pub struct AgentInstructionsResponse {
108    #[allow(dead_code)]
109    pub format: String,
110    pub content: String,
111}
112
113#[derive(Debug, Deserialize)]
114pub struct MeResponse {
115    #[allow(dead_code)]
116    pub user_id: uuid::Uuid,
117    pub email: String,
118    pub name: Option<String>,
119}
120
121/// One org the authenticated credential belongs to. `org_name` is the org
122/// slug (`orgs.name` server-side) used in URL paths; `display_name` is the
123/// human label. Wire shape of `GET /api/v1/me/orgs`.
124// Full GET /api/v1/me/orgs wire shape; only org_name (the slug) is consumed.
125// Unused fields kept for the contract, allowed like MeResponse::user_id.
126#[derive(Debug, Deserialize)]
127pub struct OrgMembership {
128    #[allow(dead_code)]
129    pub org_id: uuid::Uuid,
130    pub org_name: String,
131    #[allow(dead_code)]
132    pub display_name: Option<String>,
133    #[allow(dead_code)]
134    pub role: String,
135}
136
137#[derive(Debug)]
138pub enum GetMeError {
139    /// 401 — token is missing or invalid.
140    Unauthorized,
141    /// Transport-level failure (DNS, TCP, TLS, timeout).
142    Network(String),
143    /// HTTP ≥ 400 other than 401, or malformed JSON.
144    Server(String),
145}
146
147impl std::fmt::Display for GetMeError {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        match self {
150            Self::Unauthorized => write!(f, "unauthorized (token invalid or expired)"),
151            Self::Network(m) => write!(f, "network error: {m}"),
152            Self::Server(m) => write!(f, "server error: {m}"),
153        }
154    }
155}
156
157impl std::error::Error for GetMeError {}
158
159#[derive(Debug, Serialize)]
160pub struct CiVerifyRequest {
161    pub commits: Vec<String>,
162}
163
164#[derive(Debug, Deserialize)]
165pub struct CiVerifyResponse {
166    pub status: String,
167    pub total_commits: usize,
168    pub registered_commits: usize,
169    pub sealed_commits: usize,
170    pub policy_passed_commits: usize,
171    pub results: Vec<CommitVerifyResult>,
172}
173
174#[derive(Debug, Deserialize)]
175pub struct CommitVerifyResult {
176    pub commit_sha: String,
177    pub status: String,
178    pub registered: bool,
179    pub sealed: bool,
180    pub signature_valid: bool,
181    pub chain_valid: bool,
182    pub policy_results: Vec<CiPolicyResult>,
183}
184
185#[derive(Debug, Deserialize)]
186pub struct CiPolicyResult {
187    pub rule_name: String,
188    pub result: String,
189    pub action: String,
190    pub severity: String,
191    pub details: String,
192}
193
194/// One project in `GET /api/v1/orgs/{org}/projects`. Server sends more
195/// fields; only these two are consumed today.
196#[derive(Debug, Deserialize)]
197pub struct ProjectListItem {
198    pub id: uuid::Uuid,
199    pub name: String,
200}
201
202/// A repo linked to a project (member of `ProjectDetail::repos`).
203#[derive(Debug, Deserialize)]
204pub struct ProjectRepoRef {
205    pub id: uuid::Uuid,
206}
207
208/// Full detail for a project. Server sends more fields; only `repos` is
209/// consumed today.
210#[derive(Debug, Deserialize)]
211pub struct ProjectDetail {
212    pub repos: Vec<ProjectRepoRef>,
213}
214
215/// Outcome of `ApiClient::resolve_project`, distinguishing "no project"
216/// (404) from "ambiguous, multiple candidates" (409) — unlike
217/// `resolve_remote`, which only distinguishes found/not-found.
218#[derive(Debug)]
219pub enum ResolveProjectOutcome {
220    Resolved(uuid::Uuid),
221    None,
222    Ambiguous,
223}
224
225/// Wire shape of a successful `resolve_project` response.
226#[derive(Deserialize)]
227struct ResolveProjectResponse {
228    project_id: uuid::Uuid,
229}
230
231impl ApiClient {
232    pub fn new(base_url: &str, api_key: Option<&str>) -> Self {
233        Self {
234            base_url: base_url.trim_end_matches('/').to_string(),
235            api_key: api_key.map(String::from),
236            client: reqwest::Client::builder()
237                .timeout(std::time::Duration::from_secs(60))
238                .build()
239                .unwrap_or_default(),
240        }
241    }
242
243    pub async fn register_repo(
244        &self,
245        org_slug: &str,
246        req: RegisterRepoRequest,
247    ) -> Result<RegisterRepoResponse, Box<dyn Error>> {
248        let mut builder = self
249            .client
250            .post(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
251
252        if let Some(key) = &self.api_key {
253            builder = builder.header("Authorization", format!("Bearer {key}"));
254        }
255
256        let resp = builder.json(&req).send().await?;
257
258        if !resp.status().is_success() {
259            let status = resp.status();
260            let body = resp.text().await.unwrap_or_default();
261            return Err(format!("Server returned {status}: {body}").into());
262        }
263
264        Ok(resp.json().await?)
265    }
266
267    pub async fn device_start(&self) -> Result<DeviceAuthResponse, Box<dyn Error>> {
268        let resp = self
269            .client
270            // Send an explicit `Content-Length: 0`. reqwest/hyper omit the header
271            // entirely for a bodyless POST, and strict frontends (e.g. Google
272            // Front End) reject such requests with `411 Length Required`.
273            .post(format!("{}/api/v1/auth/device", self.base_url))
274            .header(reqwest::header::CONTENT_LENGTH, "0")
275            .send()
276            .await?;
277
278        if !resp.status().is_success() {
279            let status = resp.status();
280            let body = resp.text().await.unwrap_or_default();
281            return Err(format!("Server returned {status}: {body}").into());
282        }
283
284        Ok(resp.json().await?)
285    }
286
287    pub async fn device_status(&self, token: &str) -> Result<DeviceStatusResponse, Box<dyn Error>> {
288        let resp = self
289            .client
290            .get(format!(
291                "{}/api/v1/auth/device/{token}/status",
292                self.base_url
293            ))
294            .send()
295            .await?;
296
297        if !resp.status().is_success() {
298            let status = resp.status();
299            let body = resp.text().await.unwrap_or_default();
300            return Err(format!("Server returned {status}: {body}").into());
301        }
302
303        Ok(resp.json().await?)
304    }
305
306    pub async fn logout(&self) -> Result<(), Box<dyn Error>> {
307        let mut builder = self
308            .client
309            .post(format!("{}/api/v1/auth/logout", self.base_url));
310        if let Some(key) = &self.api_key {
311            builder = builder.header("Authorization", format!("Bearer {key}"));
312        }
313        // Explicit `Content-Length: 0` (see `device_start`): reqwest/hyper omit it
314        // for a bodyless POST, which strict frontends reject with 411.
315        let resp = builder
316            .header(reqwest::header::CONTENT_LENGTH, "0")
317            .send()
318            .await?;
319        if !resp.status().is_success() {
320            let status = resp.status();
321            let body = resp.text().await.unwrap_or_default();
322            return Err(format!("Server returned {status}: {body}").into());
323        }
324        Ok(())
325    }
326
327    /// GET `{base}{path}` with the bearer token, mapping failures into
328    /// `GetMeError` (401 → `Unauthorized`, transport → `Network`, other
329    /// non-2xx or bad JSON → `Server`). Shared by the credential-scoped GETs
330    /// so auth/error handling lives in one place.
331    async fn authed_get_json<T: serde::de::DeserializeOwned>(
332        &self,
333        path: &str,
334    ) -> Result<T, GetMeError> {
335        let mut builder = self.client.get(format!("{}{}", self.base_url, path));
336        if let Some(key) = &self.api_key {
337            builder = builder.header("Authorization", format!("Bearer {key}"));
338        }
339
340        let resp = builder
341            .send()
342            .await
343            .map_err(|e| GetMeError::Network(e.to_string()))?;
344
345        let status = resp.status();
346        if status == reqwest::StatusCode::UNAUTHORIZED {
347            return Err(GetMeError::Unauthorized);
348        }
349        if !status.is_success() {
350            let body = resp.text().await.unwrap_or_default();
351            return Err(GetMeError::Server(format!("{status}: {body}")));
352        }
353
354        resp.json::<T>()
355            .await
356            .map_err(|e| GetMeError::Server(e.to_string()))
357    }
358
359    /// GET /api/v1/auth/me — validates the bearer token and returns user
360    /// identity. Used by `tracevault status` to distinguish "logged out",
361    /// "expired token", and "server unreachable".
362    pub async fn get_me(&self) -> Result<MeResponse, GetMeError> {
363        self.authed_get_json("/api/v1/auth/me").await
364    }
365
366    /// List the orgs the authenticated credential belongs to.
367    /// `GET /api/v1/me/orgs`. For a service-account key this is the service
368    /// user's memberships; for a user session, the user's orgs; for an
369    /// org-scoped key, an empty list.
370    pub async fn list_my_orgs(&self) -> Result<Vec<OrgMembership>, GetMeError> {
371        self.authed_get_json("/api/v1/me/orgs").await
372    }
373
374    pub async fn list_repos(&self, org_slug: &str) -> Result<Vec<RepoListItem>, Box<dyn Error>> {
375        let mut builder = self
376            .client
377            .get(format!("{}/api/v1/orgs/{}/repos", self.base_url, org_slug));
378        if let Some(key) = &self.api_key {
379            builder = builder.header("Authorization", format!("Bearer {key}"));
380        }
381
382        let resp = builder.send().await?;
383
384        if !resp.status().is_success() {
385            let status = resp.status();
386            let body = resp.text().await.unwrap_or_default();
387            return Err(format!("Failed to list repos ({status}): {body}").into());
388        }
389
390        let repos: Vec<RepoListItem> = resp.json().await?;
391        Ok(repos)
392    }
393
394    pub async fn get_agent_instructions(
395        &self,
396        org_slug: &str,
397        repo_id: &uuid::Uuid,
398    ) -> Result<AgentInstructionsResponse, Box<dyn Error>> {
399        let mut builder = self.client.get(format!(
400            "{}/api/v1/orgs/{}/repos/{}/policies/agent-instructions",
401            self.base_url, org_slug, repo_id
402        ));
403        if let Some(key) = &self.api_key {
404            builder = builder.header("Authorization", format!("Bearer {key}"));
405        }
406
407        let resp = builder.send().await?;
408        if !resp.status().is_success() {
409            let status = resp.status();
410            let body = resp.text().await.unwrap_or_default();
411            return Err(format!("Failed to fetch agent instructions ({status}): {body}").into());
412        }
413        Ok(resp.json().await?)
414    }
415
416    pub async fn verify_commits(
417        &self,
418        org_slug: &str,
419        repo_id: &uuid::Uuid,
420        req: CiVerifyRequest,
421    ) -> Result<CiVerifyResponse, Box<dyn Error>> {
422        let mut builder = self.client.post(format!(
423            "{}/api/v1/orgs/{}/repos/{}/ci/verify",
424            self.base_url, org_slug, repo_id
425        ));
426        if let Some(key) = &self.api_key {
427            builder = builder.header("Authorization", format!("Bearer {key}"));
428        }
429
430        let resp = builder.json(&req).send().await?;
431
432        if !resp.status().is_success() {
433            let status = resp.status();
434            let body = resp.text().await.unwrap_or_default();
435            return Err(format!("CI verify failed ({status}): {body}").into());
436        }
437
438        Ok(resp.json().await?)
439    }
440
441    pub async fn push_commit(
442        &self,
443        org_slug: &str,
444        repo_id: &str,
445        req: &tracevault_protocol::streaming::CommitPushRequest,
446    ) -> Result<tracevault_protocol::streaming::CommitPushResponse, Box<dyn Error>> {
447        let mut builder = self.client.post(format!(
448            "{}/api/v1/orgs/{}/repos/{}/commits",
449            self.base_url, org_slug, repo_id
450        ));
451        if let Some(key) = &self.api_key {
452            builder = builder.header("Authorization", format!("Bearer {key}"));
453        }
454        let resp = builder.json(req).send().await?;
455        if !resp.status().is_success() {
456            let status = resp.status();
457            let body = resp.text().await.unwrap_or_default();
458            return Err(format!("Commit push failed ({status}): {body}").into());
459        }
460        Ok(resp.json().await?)
461    }
462
463    pub async fn stream_event(
464        &self,
465        org_slug: &str,
466        repo_id: &str,
467        req: &tracevault_protocol::streaming::StreamEventRequest,
468    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
469        let mut builder = self.client.post(format!(
470            "{}/api/v1/orgs/{}/repos/{}/stream",
471            self.base_url, org_slug, repo_id
472        ));
473        if let Some(key) = &self.api_key {
474            builder = builder.header("Authorization", format!("Bearer {key}"));
475        }
476        let resp = builder.json(req).send().await?;
477        if !resp.status().is_success() {
478            let status = resp.status();
479            let body = resp.text().await.unwrap_or_default();
480            return Err(format!("Stream failed ({status}): {body}").into());
481        }
482        Ok(resp.json().await?)
483    }
484
485    /// Project-scoped variant of `stream_event`: posts to the project's
486    /// stream endpoint with `repo_id` as a query param instead of a path
487    /// segment. The query is built with `Url::query_pairs_mut`, mirroring
488    /// `resolve_project`'s `?git_url=`, so `repo_id` is percent-encoded
489    /// rather than string-interpolated into the URL.
490    ///
491    /// Called from `commands::stream::send_stream_event` when a local
492    /// project binding resolves for the capturing event.
493    pub async fn stream_event_for_project(
494        &self,
495        org_slug: &str,
496        project_id: uuid::Uuid,
497        repo_id: &str,
498        req: &tracevault_protocol::streaming::StreamEventRequest,
499    ) -> Result<tracevault_protocol::streaming::StreamEventResponse, Box<dyn Error>> {
500        let mut url = Url::parse(&format!(
501            "{}/api/v1/orgs/{}/projects/{}/stream",
502            self.base_url, org_slug, project_id
503        ))?;
504        url.query_pairs_mut().append_pair("repo_id", repo_id);
505        let mut builder = self.client.post(url);
506        if let Some(key) = &self.api_key {
507            builder = builder.header("Authorization", format!("Bearer {key}"));
508        }
509        let resp = builder.json(req).send().await?;
510        if !resp.status().is_success() {
511            let status = resp.status();
512            let body = resp.text().await.unwrap_or_default();
513            return Err(format!("Project stream failed ({status}): {body}").into());
514        }
515        Ok(resp.json().await?)
516    }
517
518    pub async fn check_policies(
519        &self,
520        org_slug: &str,
521        repo_id: &uuid::Uuid,
522        req: CheckPoliciesRequest,
523    ) -> Result<CheckPoliciesResponse, Box<dyn Error>> {
524        let mut builder = self.client.post(format!(
525            "{}/api/v1/orgs/{}/repos/{}/policies/check",
526            self.base_url, org_slug, repo_id
527        ));
528        if let Some(key) = &self.api_key {
529            builder = builder.header("Authorization", format!("Bearer {key}"));
530        }
531
532        let resp = builder.json(&req).send().await?;
533
534        if !resp.status().is_success() {
535            let status = resp.status();
536            let body = resp.text().await.unwrap_or_default();
537            return Err(format!("Policy check failed ({status}): {body}").into());
538        }
539
540        let result: CheckPoliciesResponse = resp.json().await?;
541        Ok(result)
542    }
543
544    /// Resolve a git URL to its codebase (git remote) by NORMALIZED URL —
545    /// deduped, unlike an exact `github_url` match. `Ok(None)` if the
546    /// codebase isn't tracked (404).
547    pub async fn resolve_remote(
548        &self,
549        org_slug: &str,
550        git_url: &str,
551    ) -> Result<Option<ResolveRemoteResponse>, Box<dyn std::error::Error>> {
552        let mut url = Url::parse(&format!(
553            "{}/api/v1/orgs/{}/remotes/resolve",
554            self.base_url, org_slug
555        ))?;
556        url.query_pairs_mut().append_pair("git_url", git_url);
557        let mut builder = self.client.get(url);
558        if let Some(key) = &self.api_key {
559            builder = builder.header("Authorization", format!("Bearer {key}"));
560        }
561        let resp = builder.send().await?;
562        if resp.status() == reqwest::StatusCode::NOT_FOUND {
563            return Ok(None);
564        }
565        if !resp.status().is_success() {
566            let status = resp.status();
567            let body = resp.text().await.unwrap_or_default();
568            return Err(format!("resolve_remote failed ({status}): {body}").into());
569        }
570        let parsed: ResolveRemoteResponse = resp.json().await?;
571        Ok(Some(parsed))
572    }
573
574    /// Full detail for a remote (codebase): its display name, normalized URL,
575    /// clone status, and linked repos.
576    pub async fn get_remote_detail(
577        &self,
578        org_slug: &str,
579        remote_id: uuid::Uuid,
580    ) -> Result<RemoteDetail, Box<dyn std::error::Error>> {
581        let mut builder = self.client.get(format!(
582            "{}/api/v1/orgs/{}/remotes/{}",
583            self.base_url, org_slug, remote_id
584        ));
585        if let Some(key) = &self.api_key {
586            builder = builder.header("Authorization", format!("Bearer {key}"));
587        }
588        let resp = builder.send().await?;
589        if !resp.status().is_success() {
590            let status = resp.status();
591            let body = resp.text().await.unwrap_or_default();
592            return Err(format!("get_remote_detail failed ({status}): {body}").into());
593        }
594        let detail: RemoteDetail = resp.json().await?;
595        Ok(detail)
596    }
597
598    /// The repos linked to a remote (the codebase's members).
599    pub async fn get_remote_repos(
600        &self,
601        org_slug: &str,
602        remote_id: uuid::Uuid,
603    ) -> Result<Vec<RemoteRepoRef>, Box<dyn std::error::Error>> {
604        Ok(self.get_remote_detail(org_slug, remote_id).await?.repos)
605    }
606
607    /// List the projects in an org. `GET /api/v1/orgs/{org}/projects`.
608    pub async fn list_projects(
609        &self,
610        org_slug: &str,
611    ) -> Result<Vec<ProjectListItem>, Box<dyn Error>> {
612        let mut builder = self.client.get(format!(
613            "{}/api/v1/orgs/{}/projects",
614            self.base_url, org_slug
615        ));
616        if let Some(key) = &self.api_key {
617            builder = builder.header("Authorization", format!("Bearer {key}"));
618        }
619
620        let resp = builder.send().await?;
621
622        if !resp.status().is_success() {
623            let status = resp.status();
624            let body = resp.text().await.unwrap_or_default();
625            return Err(format!("Failed to list projects ({status}): {body}").into());
626        }
627
628        let projects: Vec<ProjectListItem> = resp.json().await?;
629        Ok(projects)
630    }
631
632    /// Full detail for a project. `GET /api/v1/orgs/{org}/projects/{id}`.
633    pub async fn get_project(
634        &self,
635        org_slug: &str,
636        id: uuid::Uuid,
637    ) -> Result<ProjectDetail, Box<dyn Error>> {
638        let mut builder = self.client.get(format!(
639            "{}/api/v1/orgs/{}/projects/{}",
640            self.base_url, org_slug, id
641        ));
642        if let Some(key) = &self.api_key {
643            builder = builder.header("Authorization", format!("Bearer {key}"));
644        }
645
646        let resp = builder.send().await?;
647
648        if !resp.status().is_success() {
649            let status = resp.status();
650            let body = resp.text().await.unwrap_or_default();
651            return Err(format!("Failed to get project ({status}): {body}").into());
652        }
653
654        let detail: ProjectDetail = resp.json().await?;
655        Ok(detail)
656    }
657
658    /// Resolve a git URL to its project, distinguishing "no project" (404)
659    /// from "ambiguous, multiple candidate projects" (409).
660    /// `GET /api/v1/orgs/{org}/projects/resolve?git_url=`.
661    pub async fn resolve_project(
662        &self,
663        org_slug: &str,
664        git_url: &str,
665    ) -> Result<ResolveProjectOutcome, Box<dyn std::error::Error>> {
666        let mut url = Url::parse(&format!(
667            "{}/api/v1/orgs/{}/projects/resolve",
668            self.base_url, org_slug
669        ))?;
670        url.query_pairs_mut().append_pair("git_url", git_url);
671        let mut builder = self.client.get(url);
672        if let Some(key) = &self.api_key {
673            builder = builder.header("Authorization", format!("Bearer {key}"));
674        }
675        let resp = builder.send().await?;
676        let status = resp.status();
677        if status == reqwest::StatusCode::NOT_FOUND {
678            return Ok(ResolveProjectOutcome::None);
679        }
680        if status == reqwest::StatusCode::CONFLICT {
681            return Ok(ResolveProjectOutcome::Ambiguous);
682        }
683        if !status.is_success() {
684            let body = resp.text().await.unwrap_or_default();
685            return Err(format!("resolve_project failed ({status}): {body}").into());
686        }
687        let parsed: ResolveProjectResponse = resp.json().await?;
688        Ok(ResolveProjectOutcome::Resolved(parsed.project_id))
689    }
690}
691
692/// Resolve server URL and auth token from multiple sources.
693/// Priority: env var > credentials file > project config.toml
694/// Returns (server_url, auth_token).
695pub fn resolve_credentials(project_root: &Path) -> (Option<String>, Option<String>) {
696    use crate::credentials::Credentials;
697
698    // 1. Env var API key
699    let env_key = std::env::var("TRACEVAULT_API_KEY").ok();
700
701    // 2. Credentials file
702    let creds = Credentials::load();
703
704    // 3. Project config
705    let config_path = crate::config::TracevaultConfig::config_path(project_root);
706    let config_content = std::fs::read_to_string(&config_path).unwrap_or_default();
707
708    let config_server_url = config_content
709        .lines()
710        .find(|l| l.starts_with("server_url"))
711        .and_then(|l| l.split('=').nth(1))
712        .map(|s| s.trim().trim_matches('"').to_string());
713
714    let config_api_key = config_content
715        .lines()
716        .find(|l| l.starts_with("api_key"))
717        .and_then(|l| l.split('=').nth(1))
718        .map(|s| s.trim().trim_matches('"').to_string());
719
720    // Resolve server URL: env > creds > config
721    let server_url = std::env::var("TRACEVAULT_SERVER_URL")
722        .ok()
723        .or_else(|| creds.as_ref().map(|c| c.server_url.clone()))
724        .or(config_server_url);
725
726    // Resolve token: env api key > creds token > config api key
727    let token = env_key
728        .or_else(|| creds.map(|c| c.token))
729        .or(config_api_key);
730
731    (server_url, token)
732}
733
734#[cfg(test)]
735mod tests {
736    use super::*;
737
738    #[test]
739    fn org_membership_deserializes_and_exposes_slug() {
740        let body = r#"[
741            {"org_id":"00000000-0000-0000-0000-000000000001","org_name":"acme","display_name":"Acme Inc","role":"admin"},
742            {"org_id":"00000000-0000-0000-0000-000000000002","org_name":"globex","display_name":null,"role":"member"}
743        ]"#;
744        let orgs: Vec<OrgMembership> = serde_json::from_str(body).unwrap();
745        assert_eq!(orgs.len(), 2);
746        // org_name is the slug used in URL paths.
747        assert_eq!(orgs[0].org_name, "acme");
748        assert_eq!(orgs[1].org_name, "globex");
749        assert_eq!(orgs[1].display_name, None);
750    }
751}