Skip to main content

tracevault_cli/
resolution.rs

1//! Detached/workspace-mode repo resolution: turn a filesystem path into a
2//! `RepoBinding` (via the path's git remote + the server), and pick the
3//! effective binding for an event/command from the precedence chain
4//! (`--path` flag → subagent worktree override → session active → bound
5//! `.tracevault/config.toml`). See design §2/§3/§4.
6
7use std::path::Path;
8use std::process::Command;
9
10use crate::api_client::{
11    ApiClient, RemoteRepoRef, RepoListItem, ResolveProjectOutcome, ResolveRemoteResponse,
12};
13use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
14
15/// `git -C <path> remote get-url origin`, trimmed. `None` if git fails or there
16/// is no origin remote. Shared by every caller that needs a checkout's origin
17/// remote URL (`init`, `sync`, `status`, and this module's own
18/// `resolve_path_to_binding`) — there is exactly one implementation.
19pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
20    let out = std::process::Command::new("git")
21        .arg("-C")
22        .arg(path)
23        .args(["remote", "get-url", "origin"])
24        .output()
25        .ok()?;
26    if !out.status.success() {
27        return None;
28    }
29    let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
30    if url.is_empty() {
31        None
32    } else {
33        Some(url)
34    }
35}
36
37/// Basename of the git repository's toplevel directory — the convention used
38/// as the server-registered repo name by `verify`/`check`/`agent-policies`/
39/// `status`/`init`/`sync`. Falls back to `"unknown"` if git fails (no repo,
40/// not a git checkout, etc.), mirroring what each of those commands' own
41/// now-removed copy of this function did.
42pub(crate) fn git_repo_name(project_root: &Path) -> String {
43    Command::new("git")
44        .args(["rev-parse", "--show-toplevel"])
45        .current_dir(project_root)
46        .output()
47        .ok()
48        .filter(|o| o.status.success())
49        .and_then(|o| repo_basename(String::from_utf8_lossy(&o.stdout).trim()))
50        .unwrap_or_else(|| "unknown".into())
51}
52
53/// The basename of a `git rev-parse --show-toplevel` path. `git` always
54/// emits forward slashes (even on Windows), but `Path::file_name` is the
55/// OS-appropriate way to take the basename — it's also tolerant of a
56/// trailing separator. `None` if the path has no basename component (e.g.
57/// root `/`). Split out from [`git_repo_name`] so the basename logic is
58/// unit-testable without shelling out to git.
59fn repo_basename(toplevel: &str) -> Option<String> {
60    Path::new(toplevel)
61        .file_name()
62        .map(|n| n.to_string_lossy().into_owned())
63}
64
65/// Either half of [`resolve_repo_by_name`]'s failure: the `list_repos` call
66/// itself failed for any reason — network/transport, or any non-2xx status
67/// (401/403/404/500/...), not only a network problem — returned raw so a
68/// caller can add its own actionable wrapping (e.g. `check`'s
69/// `connectivity_message`); or the call succeeded but no repo's name matched
70/// (so callers can phrase their own "not found" message/next-step).
71#[derive(Debug)]
72pub(crate) enum ResolveRepoByNameError {
73    ListFailed(Box<dyn std::error::Error>),
74    NotFound { repo_name: String },
75}
76
77/// Resolve the server-registered repo of `project_root`: the repo its
78/// `.tracevault/config.toml` binds, if the server lists it, else the one named
79/// like its git-toplevel basename ([`git_repo_name`]). Calls `GET /repos`.
80/// The config comes first because `init`/`sync` bind a remote's existing repo
81/// record whatever it is named (VIS-1018), so the checkout's name need not
82/// match. Shared via the `ListFailed`/`NotFound` split so each caller can
83/// phrase its own message for either failure.
84pub(crate) async fn resolve_repo_by_name(
85    client: &ApiClient,
86    project_root: &Path,
87) -> Result<RepoListItem, ResolveRepoByNameError> {
88    let repo_name = git_repo_name(project_root);
89    let repos = client
90        .list_repos()
91        .await
92        .map_err(ResolveRepoByNameError::ListFailed)?;
93    let bound = checkout_config_repo_id(project_root);
94    pick_listed_repo(repos, bound, &repo_name).ok_or(ResolveRepoByNameError::NotFound { repo_name })
95}
96
97/// The listed repo with id `bound`, else the one named `repo_name`. Pure.
98fn pick_listed_repo(
99    repos: Vec<RepoListItem>,
100    bound: Option<uuid::Uuid>,
101    repo_name: &str,
102) -> Option<RepoListItem> {
103    let i = repos
104        .iter()
105        .position(|r| Some(r.id) == bound)
106        .or_else(|| repos.iter().position(|r| r.name == repo_name))?;
107    repos.into_iter().nth(i)
108}
109
110/// Render a human line for a codebase resolved via `resolve_remote` /
111/// `get_remote_detail`: the registered name if the server has one, else the
112/// normalized URL, plus the server-side clone status. Shared by `init`
113/// (after registering) and `repo status` (live tiers) so the format has
114/// exactly one implementation.
115pub(crate) fn codebase_line(
116    name: Option<&str>,
117    normalized_url: &str,
118    clone_status: &str,
119) -> String {
120    format!(
121        "codebase: {} ({})",
122        name.unwrap_or(normalized_url),
123        clone_status
124    )
125}
126
127/// Choose the `repo status` codebase line from the available sources in
128/// priority order: live remote detail, live resolve-by-URL, cached name.
129/// The two live lines are pre-formatted (via `codebase_line`, so they carry
130/// clone status); the cached tier is name-only (no live status).
131pub(crate) fn pick_status_line(
132    detail_line: Option<String>,
133    resolved_line: Option<String>,
134    cached_name: Option<&str>,
135) -> Option<String> {
136    detail_line
137        .or(resolved_line)
138        .or_else(|| cached_name.map(|n| format!("codebase: {n}")))
139}
140
141/// A checkout path resolved to its codebase: the origin URL it was resolved
142/// from, the codebase (git remote) the server deduplicates that URL to, and
143/// the live repo records linked to it.
144#[derive(Debug)]
145pub struct ResolvedCodebase {
146    pub git_url: String,
147    pub remote: ResolveRemoteResponse,
148    /// Never empty from [`resolve_path_to_codebase`], which errors instead.
149    pub repos: Vec<RemoteRepoRef>,
150}
151
152/// Which of a codebase's repos to bind, as decided by [`ResolvedCodebase::choose`].
153#[derive(Debug, Clone, Copy, PartialEq, Eq)]
154pub enum RepoChoice {
155    /// The codebase has a single live repo.
156    Only(uuid::Uuid),
157    /// Several live repos; this one was the first of the preferred ids
158    /// (given by index into that list).
159    Preferred(uuid::Uuid, usize),
160    /// Several live repos and none of them is preferred.
161    Ambiguous,
162}
163
164impl ResolvedCodebase {
165    /// The codebase's display name: its registered name, else its URL.
166    pub fn display_name(&self) -> &str {
167        self.remote
168            .name
169            .as_deref()
170            .unwrap_or(&self.remote.normalized_url)
171    }
172
173    /// Pick the repo to bind: the only one, else the first of `preferred`
174    /// (repo ids, most preferred first) that is one of this codebase's live
175    /// repos, else none.
176    ///
177    /// Sessions are keyed by `(repo_id, session_id)` on the server, so two
178    /// repos of one codebase are NOT interchangeable for ingest: binding a
179    /// session to a different one mid-flight splits it across two session
180    /// rows (VIS-1018). Hence no silent fallback to an arbitrary repo here.
181    pub fn choose(&self, preferred: &[uuid::Uuid]) -> RepoChoice {
182        if let [only] = self.repos.as_slice() {
183            return RepoChoice::Only(only.id);
184        }
185        preferred
186            .iter()
187            .enumerate()
188            .find(|(_, id)| self.repos.iter().any(|r| r.id == **id))
189            .map_or(RepoChoice::Ambiguous, |(i, id)| {
190                RepoChoice::Preferred(*id, i)
191            })
192    }
193
194    /// `name (id)` for each live repo, lowest id first — for messages that
195    /// ask the user to pick one.
196    pub fn repo_list(&self) -> String {
197        let mut repos: Vec<_> = self.repos.iter().collect();
198        repos.sort_by_key(|r| r.id);
199        repos
200            .iter()
201            .map(|r| format!("{} ({})", r.name, r.id))
202            .collect::<Vec<_>>()
203            .join(", ")
204    }
205
206    /// A binding to `repo_id` of this codebase.
207    pub fn binding(&self, repo_id: uuid::Uuid) -> RepoBinding {
208        RepoBinding {
209            repo_id: repo_id.to_string(),
210            git_url: Some(self.git_url.clone()),
211            remote_id: Some(self.remote.remote_id),
212            codebase_name: self.remote.name.clone(),
213            updated_at: chrono::Utc::now().to_rfc3339(),
214        }
215    }
216}
217
218/// Resolve a filesystem path to its codebase and live repos: read its origin
219/// remote URL and ask the server. `Ok(None)` when the path has no remote or
220/// the server has no matching codebase (pre-registered-only); an error when
221/// the codebase is registered but has no live repo.
222pub async fn resolve_path_to_codebase(
223    path: &Path,
224    client: &ApiClient,
225) -> Result<Option<ResolvedCodebase>, Box<dyn std::error::Error>> {
226    let Some(git_url) = git_remote_url(path) else {
227        return Ok(None);
228    };
229    let Some(codebase) = resolve_url_to_codebase(&git_url, client).await? else {
230        return Ok(None);
231    };
232    if codebase.repos.is_empty() {
233        return Err(format!(
234            "codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
235            codebase.display_name()
236        )
237        .into());
238    }
239    Ok(Some(codebase))
240}
241
242/// Resolve an origin URL to its codebase (by NORMALIZED URL, deduped) and
243/// list the codebase's live repos, which may be none. `Ok(None)` when the
244/// server has no matching codebase.
245pub async fn resolve_url_to_codebase(
246    git_url: &str,
247    client: &ApiClient,
248) -> Result<Option<ResolvedCodebase>, Box<dyn std::error::Error>> {
249    let Some(remote) = client.resolve_remote(git_url).await? else {
250        return Ok(None);
251    };
252    let repos = client.get_remote_repos(remote.remote_id).await?;
253    Ok(Some(ResolvedCodebase {
254        git_url: git_url.to_string(),
255        remote,
256        repos,
257    }))
258}
259
260/// What registering a checkout with the server should do, given the repos
261/// its remote's codebase already has. See [`plan_registration`].
262#[derive(Debug)]
263pub enum RegistrationPlan {
264    /// The remote's codebase has no live repo (or is unknown): register one.
265    Register,
266    /// Bind this existing repo of the codebase; register nothing.
267    Existing(ResolvedCodebase, uuid::Uuid),
268    /// The codebase has several live repos and nothing says which one this
269    /// checkout is; register nothing and let the user pick.
270    Ambiguous(ResolvedCodebase),
271}
272
273/// Decide whether `init`/`sync` may register a repo for `git_url`.
274///
275/// Registration upserts by repo NAME (the checkout's directory name), so a
276/// checkout named differently from the remote's existing repo record would
277/// create a second record for the same codebase — and sessions then split
278/// between the two (VIS-1018). So when the codebase already has live repos,
279/// bind one of them: `preferred` (the repo the checkout's config.toml already
280/// names) if the codebase links it, else the one named `repo_name`, else the
281/// only one; several and none of those → [`RegistrationPlan::Ambiguous`].
282pub async fn plan_registration(
283    client: &ApiClient,
284    git_url: &str,
285    repo_name: &str,
286    preferred: Option<uuid::Uuid>,
287) -> Result<RegistrationPlan, Box<dyn std::error::Error>> {
288    let Some(codebase) = resolve_url_to_codebase(git_url, client).await? else {
289        return Ok(RegistrationPlan::Register);
290    };
291    if codebase.repos.is_empty() {
292        return Ok(RegistrationPlan::Register);
293    }
294    let named = codebase
295        .repos
296        .iter()
297        .find(|r| r.name == repo_name)
298        .map(|r| r.id);
299    let pick = match codebase.choose(&preferred.into_iter().chain(named).collect::<Vec<_>>()) {
300        RepoChoice::Only(id) | RepoChoice::Preferred(id, _) => Some(id),
301        RepoChoice::Ambiguous => None,
302    };
303    Ok(match pick {
304        Some(id) => RegistrationPlan::Existing(codebase, id),
305        None => RegistrationPlan::Ambiguous(codebase),
306    })
307}
308/// The repo id a checkout's own `.tracevault/config.toml` binds, if any. `path`
309/// may be anywhere in the checkout, or in one of its linked worktrees.
310pub fn checkout_config_repo_id(path: &Path) -> Option<uuid::Uuid> {
311    let root = crate::paths::resolve_project_root(path).root;
312    crate::config::TracevaultConfig::load(&root)?
313        .repo_id?
314        .parse()
315        .ok()
316}
317
318/// Resolve a filesystem path to a registered-repo binding: read its origin
319/// remote URL and ask the server. `Ok(None)` when the path has no remote or
320/// the server has no matching codebase (pre-registered-only).
321///
322/// When the codebase has several live repos, the one the checkout's own
323/// `.tracevault/config.toml` binds wins — the repo its hooks stream to —
324/// else the lowest id (deterministic). Callers that must not guess (`repo
325/// switch`) use [`resolve_path_to_codebase`] and [`ResolvedCodebase::choose`].
326pub async fn resolve_path_to_binding(
327    path: &Path,
328    client: &ApiClient,
329) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
330    let Some(codebase) = resolve_path_to_codebase(path, client).await? else {
331        return Ok(None);
332    };
333    Ok(pick_binding(&codebase, path))
334}
335
336/// The repo of `codebase` that [`resolve_path_to_binding`] binds the checkout
337/// at `path` to: the only one, else the one the checkout's own config names,
338/// else the lowest id. `None` only when the codebase has no live repo.
339fn pick_binding(codebase: &ResolvedCodebase, path: &Path) -> Option<RepoBinding> {
340    let preferred: Vec<uuid::Uuid> = checkout_config_repo_id(path).into_iter().collect();
341    let repo_id = match codebase.choose(&preferred) {
342        RepoChoice::Only(id) | RepoChoice::Preferred(id, _) => id,
343        RepoChoice::Ambiguous => codebase.repos.iter().map(|r| r.id).min()?,
344    };
345    Some(codebase.binding(repo_id))
346}
347
348/// [`resolve_path_to_binding`] among the repos of project `project_id` only
349/// (VIS-1258): the checkout's codebase, narrowed to the repos the project
350/// holds, then picked the same way. `Ok(None)` when the checkout has no origin
351/// remote, the server has no codebase for it, or none of that codebase's live
352/// repos belongs to the project — a repo outside the project is never
353/// returned, since a send declaring the project with it is refused.
354pub async fn resolve_path_to_project_binding(
355    path: &Path,
356    project_id: uuid::Uuid,
357    client: &ApiClient,
358) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
359    let Some(git_url) = git_remote_url(path) else {
360        return Ok(None);
361    };
362    let Some(mut codebase) = resolve_url_to_codebase(&git_url, client).await? else {
363        return Ok(None);
364    };
365    if codebase.repos.is_empty() {
366        return Ok(None);
367    }
368    let in_project: std::collections::HashSet<uuid::Uuid> = client
369        .get_project(project_id)
370        .await?
371        .repos
372        .into_iter()
373        .map(|r| r.id)
374        .collect();
375    codebase.repos.retain(|r| in_project.contains(&r.id));
376    Ok(pick_binding(&codebase, path))
377}
378
379/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
380/// are resolved by the caller (the `--path` override and the bound
381/// `config.toml`, respectively); `session`/`worktree_path` come from the
382/// per-session state.
383pub struct ResolveInputs<'a> {
384    pub repo_flag: Option<RepoBinding>,
385    pub session: &'a SessionState,
386    pub worktree_path: Option<&'a str>,
387    pub bound: Option<RepoBinding>,
388    /// Lowest-precedence, session-independent default (from `repo switch --user`
389    /// / a no-session switch). Applies when nothing more specific resolves.
390    pub user_default: Option<RepoBinding>,
391}
392
393/// Inputs for the effective-project precedence chain. `project_flag` and
394/// `config_project` are resolved by the caller; `session`/`worktree_path`
395/// come from the per-session state.
396pub struct ProjectResolveInputs<'a> {
397    pub project_flag: Option<ProjectBinding>,
398    /// Parsed from `TRACEVAULT_PROJECT` by the caller, so this module stays
399    /// free of environment reads and remains a pure function of its inputs.
400    pub env_project: Option<ProjectBinding>,
401    pub session: &'a SessionState,
402    pub worktree_path: Option<&'a str>,
403    /// The workspace tier: `.tracevault/config.toml` `project_id`, read by
404    /// [`project_from_config`] — local, never a name lookup.
405    pub config_project: Option<ProjectBinding>,
406}
407
408/// Which precedence tier produced the [`effective_binding`] result.
409#[derive(Debug, Clone, Copy, PartialEq, Eq)]
410pub enum BindingSource {
411    /// A `--path <path>` flag override (on `repo status`).
412    RepoFlag,
413    /// A subagent's per-worktree override.
414    Subagent,
415    /// The session's session-level active binding.
416    SessionActive,
417    /// A pinned `.tracevault/config.toml` (bound mode).
418    Bound,
419    /// A session-independent user-level default (`repo switch --user`).
420    UserDefault,
421}
422
423impl std::fmt::Display for BindingSource {
424    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
425        let label = match self {
426            BindingSource::RepoFlag => "--path override",
427            BindingSource::Subagent => "subagent worktree override",
428            BindingSource::SessionActive => "session (repo switch)",
429            BindingSource::Bound => "bound .tracevault/config.toml",
430            BindingSource::UserDefault => "user default (repo switch --user)",
431        };
432        f.write_str(label)
433    }
434}
435
436/// Which precedence tier produced the [`effective_project`] result.
437#[derive(Debug, Clone, Copy, PartialEq, Eq)]
438pub enum ProjectSource {
439    /// A `--project <id>` flag override.
440    ProjectFlag,
441    /// A subagent's per-worktree override.
442    Subagent,
443    /// The `TRACEVAULT_PROJECT` environment variable — a per-process
444    /// assertion, re-asserted at every launch and never written to disk.
445    /// Outranks every remembered tier so a stale `user_project.toml` or a
446    /// `.tracevault/config.toml` baked into a pod image cannot outrank the
447    /// launcher that started the process.
448    Env,
449    /// The session's project-level active binding.
450    SessionActive,
451    /// The directory's `.tracevault/config.toml` `project_id` (VIS-1256):
452    /// every session started under that directory belongs to this project
453    /// unless something more specific (e.g. a `project switch`) says
454    /// otherwise.
455    Workspace,
456    /// Repo deduction from the git remote, resolved server-side. Produced
457    /// only by the display chain [`resolve_effective_project`], never by the
458    /// capture chain [`capture_project_binding`].
459    Deduced,
460    /// A session-independent user-level default (`project switch --user`).
461    /// Produced by [`capture_project_binding`] and
462    /// [`resolve_effective_project`], not [`effective_project`].
463    UserDefault,
464}
465
466impl ProjectSource {
467    /// The command that rewrites a binding stored by this tier, for a
468    /// warning about a stored `project_id` that is not a valid id.
469    pub fn rewrite_command(self) -> &'static str {
470        match self {
471            ProjectSource::Workspace => "tracevault init --workspace --project <name>",
472            ProjectSource::UserDefault => "tracevault project switch --user <name>",
473            _ => "tracevault project switch <name>",
474        }
475    }
476}
477
478impl std::fmt::Display for ProjectSource {
479    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
480        let label = match self {
481            ProjectSource::ProjectFlag => "--project override",
482            ProjectSource::Subagent => "subagent worktree override",
483            ProjectSource::Env => "TRACEVAULT_PROJECT (environment)",
484            ProjectSource::SessionActive => "session (project switch)",
485            ProjectSource::Workspace => "workspace .tracevault/config.toml",
486            ProjectSource::Deduced => "repo deduction",
487            ProjectSource::UserDefault => "user default (project switch --user)",
488        };
489        f.write_str(label)
490    }
491}
492
493/// The binding that applies, and which tier produced it: `--path` flag →
494/// subagent worktree override → session active → bound config → user
495/// default → none.
496pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
497    if let Some(b) = inputs.repo_flag {
498        return Some((b, BindingSource::RepoFlag));
499    }
500    if let Some(wt) = inputs.worktree_path {
501        if let Some(b) = inputs.session.subagents.get(wt) {
502            return Some((b.clone(), BindingSource::Subagent));
503        }
504    }
505    if let Some(b) = &inputs.session.active {
506        return Some((b.clone(), BindingSource::SessionActive));
507    }
508    if let Some(b) = inputs.bound {
509        return Some((b, BindingSource::Bound));
510    }
511    inputs.user_default.map(|b| (b, BindingSource::UserDefault))
512}
513
514/// The project that applies, and which tier produced it: `--project` flag →
515/// subagent worktree override → `TRACEVAULT_PROJECT` → session active →
516/// workspace config `project_id` → none.
517/// Pure; covers only the local tiers (flag → subagent → env_project →
518/// session.active_project → config_project). `env_project` is supplied BY THE
519/// CALLER — this module never reads the environment — and the capture path
520/// fills it from `commands::stream::env_project_binding`, which honours the
521/// UUID form only. The user-level default (and, in the display chain only,
522/// server-side deduction) are applied afterward by [`capture_project_binding`]
523/// / [`resolve_effective_project`], which call this function first and only
524/// fall through to those tiers when it returns `None`.
525pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
526    if let Some(b) = &inputs.project_flag {
527        return Some((b.clone(), ProjectSource::ProjectFlag));
528    }
529    if let Some(wt) = inputs.worktree_path {
530        if let Some(b) = inputs.session.subagent_projects.get(wt) {
531            return Some((b.clone(), ProjectSource::Subagent));
532        }
533    }
534    if let Some(b) = &inputs.env_project {
535        return Some((b.clone(), ProjectSource::Env));
536    }
537    if let Some(b) = &inputs.session.active_project {
538        return Some((b.clone(), ProjectSource::SessionActive));
539    }
540    inputs
541        .config_project
542        .clone()
543        .map(|b| (b, ProjectSource::Workspace))
544}
545
546/// Inputs to the capture-time project chain. The config tier is the
547/// `.tracevault/config.toml` `project_id` (a UUID, via
548/// [`project_from_config`]); the legacy `default_project` NAME is never an
549/// input — resolving it needs a network call, and the stream hook (which
550/// fires per event) never does one. `init`/`sync` migrate it to `project_id`
551/// (`commands::migrate`).
552pub struct CaptureProjectInputs<'a> {
553    /// `--project` override (only `project status` supplies it; the hook passes `None`).
554    pub project_flag: Option<ProjectBinding>,
555    /// `TRACEVAULT_PROJECT`, UUID form ONLY — parsed by the caller (via
556    /// `commands::stream::env_project_binding`) so this module stays free of
557    /// environment reads. The NAME form is deliberately not a tier here: it
558    /// would need a `list_projects` round trip, and this is the network-free
559    /// chain the per-event hook runs. Both callers fill this field from that
560    /// same reader, so `project status` cannot report a tier ingest ignores.
561    pub env_project: Option<ProjectBinding>,
562    pub session: &'a SessionState,
563    pub worktree_path: Option<&'a str>,
564    /// The workspace tier: [`project_from_config`] of the
565    /// `.tracevault/config.toml` at the event's project root. Passed in so the
566    /// function stays pure.
567    pub config_project: Option<ProjectBinding>,
568    /// `user_project_default::load()` — passed in so the function stays pure.
569    pub user_default: Option<ProjectBinding>,
570}
571
572/// THE capture-time project chain: `--project` flag → subagent worktree
573/// override → `TRACEVAULT_PROJECT` → session `active_project` → workspace
574/// `.tracevault/config.toml` `project_id` → user default → none. Pure, no network. `commands::stream::capture_project` (ingest) and
575/// `commands::project::status` both call this, so they cannot drift.
576pub fn capture_project_binding(
577    inputs: &CaptureProjectInputs<'_>,
578) -> Option<(ProjectBinding, ProjectSource)> {
579    effective_project(&ProjectResolveInputs {
580        project_flag: inputs.project_flag.clone(),
581        env_project: inputs.env_project.clone(),
582        session: inputs.session,
583        worktree_path: inputs.worktree_path,
584        config_project: inputs.config_project.clone(),
585    })
586    .or_else(|| {
587        inputs
588            .user_default
589            .clone()
590            .map(|b| (b, ProjectSource::UserDefault))
591    })
592}
593
594/// The id the hook will actually send for a capture binding: `None` when the
595/// stored `project_id` is not a UUID (a hand-edited or corrupted
596/// `user_project.toml`/session file), in which case ingest treats the binding
597/// as absent and the event goes repo-scoped.
598pub fn capture_project_id(binding: &ProjectBinding) -> Option<uuid::Uuid> {
599    binding.project_id.parse::<uuid::Uuid>().ok()
600}
601
602/// DISPLAY chain for `commands::status`'s "Project" line: `--project` flag →
603/// subagent override → `TRACEVAULT_PROJECT` → session active → config default
604/// (all pure, via [`effective_project`]; no network call) → user-level default
605/// → server-side deduction from the repo's git remote.
606///
607/// The user-level default outranks deduction because that is what ingest
608/// does: the capture chain ([`capture_project_binding`]) applies the user
609/// default and never deduces, so a display chain that ranked deduction above
610/// it would name a project no event is attributed to — exactly in the
611/// orchestrator's configuration (a pod bound via `project switch --user`). The
612/// server is only asked once every local tier, user default included, is empty.
613///
614/// An `Ambiguous` deduction result is an error (the caller can't safely guess
615/// among several candidate projects). This resolver never prints: callers
616/// render the tier via [`ProjectSource`]'s `Display`. Returns `Ok(None)` only
617/// when every tier in the chain is empty. `commands::project::status` does not
618/// use this chain: it reports [`capture_project_binding`] and shows deduction
619/// on a separate line.
620pub async fn resolve_effective_project(
621    inputs: &ProjectResolveInputs<'_>,
622    user_default: Option<ProjectBinding>,
623    git_url: Option<&str>,
624    client: &ApiClient,
625) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
626    // Local tiers: flag → subagent → TRACEVAULT_PROJECT → session active →
627    // config default.
628    if let Some(hit) = effective_project(inputs) {
629        return Ok(Some(hit));
630    }
631    // User-level default: ingest honours it, so it outranks deduction.
632    if let Some(b) = user_default {
633        return Ok(Some((b, ProjectSource::UserDefault)));
634    }
635    // Server-side deduction from the repo's git remote (lowest tier).
636    if let Some(url) = git_url {
637        match client.resolve_project(url).await? {
638            ResolveProjectOutcome::Resolved(pid) => {
639                return Ok(Some((
640                    ProjectBinding {
641                        project_id: pid.to_string(),
642                        project_name: String::new(), // enriched for display by the caller if needed
643                        updated_at: String::new(),
644                        forced_until: None,
645                    },
646                    ProjectSource::Deduced,
647                )));
648            }
649            ResolveProjectOutcome::Ambiguous => {
650                return Err(
651                    "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
652                        .to_string()
653                        .into(),
654                );
655            }
656            ResolveProjectOutcome::None => { /* fall through */ }
657        }
658    }
659    Ok(None)
660}
661
662/// The repo binding a recorded session's events were streamed under, resolved
663/// exactly as the stream hook resolves it — so `check` and `verify-start` work
664/// under the same repo id the session's events went to (VIS-601).
665///
666/// The whole chain runs off `session_dir`, like `flush`'s
667/// `queue_capture_binding`: the session id is its file name (the caller loads
668/// `state` from it), and the subagent worktree override is keyed by the
669/// worktree toplevel the hook recorded in its `origin` marker. `bound` and
670/// `user_default` are the lower tiers the hook also consults.
671///
672/// `here` is the caller's worktree toplevel. When the session ran an event
673/// there (see [`crate::session_state::ran_in`]) the override is keyed by it:
674/// an anchored session's `origin` names only where its LATEST event ran, and
675/// its events in `here` were resolved with `here` (VIS-1257).
676///
677/// A binding whose `repo_id` is not a UUID resolves to `None`, as it does for
678/// the hook (`stream::attribution_for` never sends to it).
679///
680/// A project-only session's events in that worktree went to the repo the
681/// hook inferred for it (VIS-1258), read from the session's cache as the hook
682/// reads it.
683pub(crate) fn recorded_session_binding(
684    session_dir: &Path,
685    here: &str,
686    state: &SessionState,
687    bound: Option<RepoBinding>,
688    user_default: Option<RepoBinding>,
689) -> Option<RepoBinding> {
690    let worktree = if crate::session_state::ran_in(session_dir, here) {
691        Some(here.to_string())
692    } else {
693        std::fs::read_to_string(session_dir.join("origin"))
694            .ok()
695            .map(|s| s.trim().to_string())
696    };
697    let binding = effective_binding(ResolveInputs {
698        repo_flag: None,
699        session: state,
700        worktree_path: worktree.as_deref(),
701        bound,
702        user_default,
703    })
704    .map(|(b, _)| b);
705    match binding {
706        Some(b) => Some(b),
707        None => crate::inferred_repo::recorded_repo(state, worktree.as_deref()?),
708    }
709    .filter(|b| crate::commands::stream::binding_repo_id_is_valid(&b.repo_id))
710}
711
712/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
713/// a repo_id. Pure — caller supplies the already-loaded config.
714/// Carries through the `remote_id`/`codebase_name` `init` persisted (best-effort,
715/// display-only) so bound-mode `status` can print the codebase without an extra
716/// network round-trip; `git_url` stays `None` here — bound mode has no live
717/// origin URL to hand back (that's the older `git_url` fallback's job, covering
718/// bindings that predate `codebase_name`).
719/// The workspace project tier of a `.tracevault/config.toml`: its
720/// `project_id`, with the recorded `project_name` for display. `None` when
721/// the config has no `project_id` — in particular for a config that still
722/// carries only the legacy `default_project` name, which is never resolved
723/// here (VIS-1256: ingest never resolves names). A `project_id` that is not a
724/// UUID is returned as is; the capture path drops it via
725/// [`capture_project_id`], and `project status` warns about it.
726pub fn project_from_config(config: &crate::config::TracevaultConfig) -> Option<ProjectBinding> {
727    let project_id = config.project_id.as_deref()?.trim();
728    if project_id.is_empty() {
729        return None;
730    }
731    Some(ProjectBinding {
732        project_id: project_id.to_string(),
733        project_name: config.project_name.clone().unwrap_or_default(),
734        updated_at: String::new(),
735        forced_until: None,
736    })
737}
738
739pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
740    Some(RepoBinding {
741        repo_id: config.repo_id.clone()?,
742        git_url: None,
743        remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
744        codebase_name: config.codebase_name.clone(),
745        updated_at: String::new(),
746    })
747}
748
749#[cfg(test)]
750mod tests {
751    use super::*;
752    use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
753    use std::collections::HashMap;
754    use std::io::{BufRead, BufReader, Write};
755    use std::net::{SocketAddr, TcpListener};
756    use std::thread;
757
758    #[test]
759    fn repo_basename_bare_name() {
760        assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
761    }
762
763    #[test]
764    fn repo_basename_nested_path() {
765        assert_eq!(
766            repo_basename("/home/user/code/myrepo"),
767            Some("myrepo".to_string())
768        );
769    }
770
771    #[test]
772    fn repo_basename_trailing_slash() {
773        // `Path::file_name` skips a trailing separator rather than treating
774        // it as an empty final component.
775        assert_eq!(
776            repo_basename("/home/user/code/myrepo/"),
777            Some("myrepo".to_string())
778        );
779    }
780
781    #[test]
782    fn repo_basename_dot_git_suffix_directory() {
783        // A checkout directory literally named `myrepo.git` (e.g. a bare
784        // clone) keeps the suffix — `git_repo_name` takes the raw basename,
785        // it does not strip `.git`.
786        assert_eq!(
787            repo_basename("/srv/repos/myrepo.git"),
788            Some("myrepo.git".to_string())
789        );
790    }
791
792    #[test]
793    fn repo_basename_root_has_no_basename() {
794        assert_eq!(repo_basename("/"), None);
795    }
796
797    /// Spawn a one-shot raw-HTTP server that returns a response built from
798    /// `status` (e.g. `"200 OK"`) and `body` to the first request it accepts.
799    /// Mirrors the `spawn_once`/`http_200` shape in `commands::repo`'s test
800    /// module (bind loopback, accept once on a background thread, write the
801    /// raw HTTP response, flush, close).
802    fn spawn_once(
803        status: &'static str,
804        body: &'static str,
805    ) -> (SocketAddr, thread::JoinHandle<()>) {
806        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
807        let addr = listener.local_addr().unwrap();
808        let response = http_200(status, body);
809        let handle = thread::spawn(move || {
810            if let Ok((stream, _)) = listener.accept() {
811                let mut reader = BufReader::new(stream);
812                let mut request_line = String::new();
813                let _ = reader.read_line(&mut request_line);
814                let mut stream = reader.into_inner();
815                let _ = stream.write_all(response.as_bytes());
816                let _ = stream.flush();
817            }
818        });
819        (addr, handle)
820    }
821
822    /// Format a raw HTTP/1.1 response with the given `status` line and a
823    /// correct `Content-Length` for a JSON `body`.
824    fn http_200(status: &str, body: &str) -> String {
825        format!(
826            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
827            status,
828            body.len(),
829            body
830        )
831    }
832
833    #[tokio::test]
834    async fn user_default_beats_deduction() {
835        // Ingest applies the user default and never deduces, so the display
836        // chain must too: with a user default present, NO server request may
837        // be made. The client points at port 0 (nothing listens there), so a
838        // deduction attempt would surface as an Err rather than Ok(UserDefault).
839        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
840        let ud = ProjectBinding {
841            project_id: "user".into(),
842            project_name: "u".into(),
843            updated_at: "".into(),
844            forced_until: None,
845        };
846        let inputs = ProjectResolveInputs {
847            project_flag: None,
848            env_project: None,
849            session: &SessionState::default(),
850            worktree_path: None,
851            config_project: None,
852        };
853        let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
854            .await
855            .expect("a user default must resolve without any network call")
856            .unwrap();
857        assert_eq!(src, ProjectSource::UserDefault);
858        assert_eq!(b.project_id, "user");
859    }
860
861    #[tokio::test]
862    async fn deduction_used_when_no_local_tier_or_user_default() {
863        let (addr, _h) = spawn_once(
864            "200 OK",
865            "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
866        );
867        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
868        let inputs = ProjectResolveInputs {
869            project_flag: None,
870            env_project: None,
871            session: &SessionState::default(),
872            worktree_path: None,
873            config_project: None,
874        };
875        let (b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
876            .await
877            .unwrap()
878            .unwrap();
879        assert_eq!(src, ProjectSource::Deduced);
880        assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
881    }
882
883    #[tokio::test]
884    async fn ambiguous_deduction_errors_when_no_higher_rung() {
885        let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
886        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
887        let inputs = ProjectResolveInputs {
888            project_flag: None,
889            env_project: None,
890            session: &SessionState::default(),
891            worktree_path: None,
892            config_project: None,
893        };
894        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
895            .await
896            .unwrap_err();
897        assert!(err.to_string().to_lowercase().contains("--project"));
898    }
899
900    #[tokio::test]
901    async fn domain_404_deduction_resolves_to_none() {
902        // A domain 404 (server's `{"error": ...}` envelope) — the shape a
903        // real (non-skewed) server sends for "no project" — falls through to
904        // `Ok(None)`, unlike a bare route-404. The user default is `None`
905        // here: a present user default now short-circuits before the
906        // deduction call (see `user_default_beats_deduction`).
907        let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
908        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
909        let inputs = ProjectResolveInputs {
910            project_flag: None,
911            env_project: None,
912            session: &SessionState::default(),
913            worktree_path: None,
914            config_project: None,
915        };
916        let got = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
917            .await
918            .unwrap();
919        assert!(got.is_none(), "got: {got:?}");
920    }
921
922    #[tokio::test]
923    async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
924        // A bare 404 (no JSON error body) is axum's "no route matched"
925        // fallback, not a domain "no project" — it must propagate as an
926        // error instead of silently falling through to `Ok(None)`. No user
927        // default: one would short-circuit before the deduction call.
928        let (addr, _h) = spawn_once("404 Not Found", "");
929        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
930        let inputs = ProjectResolveInputs {
931            project_flag: None,
932            env_project: None,
933            session: &SessionState::default(),
934            worktree_path: None,
935            config_project: None,
936        };
937        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
938            .await
939            .expect_err("a bare 404 must not silently fall through to Ok(None)");
940        assert!(err.to_string().to_lowercase().contains("version mismatch"));
941    }
942
943    #[tokio::test]
944    async fn local_rung_skips_server_call() {
945        // no server spawned; a config_default present must resolve WITHOUT any network call
946        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
947        let cfg = ProjectBinding {
948            project_id: "cfg".into(),
949            project_name: "c".into(),
950            updated_at: "".into(),
951            forced_until: None,
952        };
953        let inputs = ProjectResolveInputs {
954            project_flag: None,
955            env_project: None,
956            session: &SessionState::default(),
957            worktree_path: None,
958            config_project: Some(cfg),
959        };
960        let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
961            .await
962            .unwrap()
963            .unwrap();
964        assert_eq!(src, ProjectSource::Workspace);
965    }
966
967    fn binding(id: &str) -> RepoBinding {
968        RepoBinding {
969            repo_id: id.into(),
970            git_url: None,
971            remote_id: None,
972            codebase_name: None,
973            updated_at: "t".into(),
974        }
975    }
976
977    const REPO_A: &str = "11111111-1111-1111-1111-111111111111";
978    const REPO_B: &str = "22222222-2222-2222-2222-222222222222";
979    const REPO_C: &str = "33333333-3333-3333-3333-333333333333";
980
981    fn session_dir_with_origin(origin: Option<&str>) -> tempfile::TempDir {
982        let dir = tempfile::tempdir().unwrap();
983        if let Some(o) = origin {
984            std::fs::write(dir.path().join("origin"), o).unwrap();
985        }
986        dir
987    }
988
989    /// VIS-1258: `check` and `verify-start` in a checkout where a project-only
990    /// session's events were sent with an inferred repo find that repo — in
991    /// the checkout the session ran in (`worktrees`), not just its latest.
992    #[test]
993    fn recorded_session_binding_finds_the_repo_inferred_for_the_worktree() {
994        let dir = session_dir_with_origin(Some("/umbrella"));
995        std::fs::write(
996            dir.path().join(crate::session_state::WORKTREES_FILE),
997            "/umbrella\n/umbrella/child\n",
998        )
999        .unwrap();
1000        let pid = uuid::Uuid::from_u128(0x1258);
1001        let mut state = SessionState {
1002            active_project: Some(ProjectBinding {
1003                project_id: pid.to_string(),
1004                project_name: "p".into(),
1005                updated_at: "t".into(),
1006                forced_until: None,
1007            }),
1008            ..Default::default()
1009        };
1010        state.inferred_repos.insert(
1011            "/umbrella/child".into(),
1012            crate::session_state::InferredRepo {
1013                project_id: pid.to_string(),
1014                retry_after: None,
1015                repo: Some(binding(REPO_B)),
1016            },
1017        );
1018
1019        let here = recorded_session_binding(dir.path(), "/umbrella/child", &state, None, None);
1020        assert_eq!(here.map(|b| b.repo_id).as_deref(), Some(REPO_B));
1021        // Elsewhere nothing was inferred, and a bound tier still wins.
1022        assert!(recorded_session_binding(dir.path(), "/other", &state, None, None).is_none());
1023        let bound = recorded_session_binding(
1024            dir.path(),
1025            "/umbrella/child",
1026            &state,
1027            Some(binding(REPO_A)),
1028            None,
1029        );
1030        assert_eq!(bound.map(|b| b.repo_id).as_deref(), Some(REPO_A));
1031    }
1032
1033    #[test]
1034    fn recorded_session_binding_prefers_repo_switch_over_config() {
1035        let dir = session_dir_with_origin(Some("/wt/a"));
1036        let state = SessionState {
1037            active: Some(binding(REPO_A)),
1038            ..Default::default()
1039        };
1040        let got =
1041            recorded_session_binding(dir.path(), "", &state, Some(binding(REPO_B)), None).unwrap();
1042        assert_eq!(got.repo_id, REPO_A);
1043    }
1044
1045    #[test]
1046    fn recorded_session_binding_honours_subagent_override_via_origin_marker() {
1047        // The hook writes no trailing newline today; a hand-edited marker with
1048        // one must still key the override.
1049        let dir = session_dir_with_origin(Some("/wt/sub\n"));
1050        let mut state = SessionState {
1051            active: Some(binding(REPO_A)),
1052            ..Default::default()
1053        };
1054        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
1055        let got = recorded_session_binding(dir.path(), "", &state, None, None).unwrap();
1056        assert_eq!(got.repo_id, REPO_C);
1057    }
1058
1059    #[test]
1060    fn recorded_session_binding_unbound_falls_to_config_then_user_default() {
1061        let dir = session_dir_with_origin(None);
1062        let state = SessionState::default();
1063        let got = recorded_session_binding(
1064            dir.path(),
1065            "",
1066            &state,
1067            Some(binding(REPO_B)),
1068            Some(binding(REPO_C)),
1069        )
1070        .unwrap();
1071        assert_eq!(got.repo_id, REPO_B);
1072        let got =
1073            recorded_session_binding(dir.path(), "", &state, None, Some(binding(REPO_C))).unwrap();
1074        assert_eq!(got.repo_id, REPO_C);
1075        assert!(recorded_session_binding(dir.path(), "", &state, None, None).is_none());
1076    }
1077
1078    /// An anchored session that ran in a subagent's worktree and then moved
1079    /// on: from that worktree, its override applies (VIS-1257).
1080    #[test]
1081    fn recorded_session_binding_keys_the_override_by_a_worktree_the_session_ran_in() {
1082        let dir = session_dir_with_origin(Some("/umbrella"));
1083        crate::session_state::record_worktree(dir.path(), "/wt/sub").unwrap();
1084        crate::session_state::record_worktree(dir.path(), "/umbrella").unwrap();
1085        let mut state = SessionState {
1086            active: Some(binding(REPO_A)),
1087            ..Default::default()
1088        };
1089        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
1090        let got = |here| recorded_session_binding(dir.path(), here, &state, None, None);
1091        assert_eq!(got("/wt/sub").unwrap().repo_id, REPO_C);
1092        assert_eq!(got("/umbrella").unwrap().repo_id, REPO_A);
1093        assert_eq!(
1094            got("/never").unwrap().repo_id,
1095            REPO_A,
1096            "falls back to origin"
1097        );
1098    }
1099
1100    #[test]
1101    fn recorded_session_binding_rejects_non_uuid_repo_id() {
1102        let dir = session_dir_with_origin(Some("/wt/a"));
1103        let state = SessionState {
1104            active: Some(binding("../escape")),
1105            ..Default::default()
1106        };
1107        assert!(recorded_session_binding(dir.path(), "", &state, None, None).is_none());
1108    }
1109
1110    /// The same session must resolve to the same repo on the hook side and on
1111    /// the `check`/`verify-start` side — the whole point of VIS-601.
1112    #[test]
1113    fn recorded_session_binding_agrees_with_stream_hook() {
1114        let mut state = SessionState {
1115            active: Some(binding(REPO_A)),
1116            ..Default::default()
1117        };
1118        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
1119        for wt in ["/wt/main", "/wt/sub"] {
1120            let dir = session_dir_with_origin(Some(wt));
1121            let hook = crate::commands::stream::resolve_stream_binding(
1122                &state,
1123                wt,
1124                Some(binding(REPO_B)),
1125                None,
1126            );
1127            let recorded =
1128                recorded_session_binding(dir.path(), "", &state, Some(binding(REPO_B)), None);
1129            assert_eq!(
1130                hook.map(|b| b.repo_id),
1131                recorded.map(|b| b.repo_id),
1132                "worktree {wt}"
1133            );
1134        }
1135    }
1136
1137    #[test]
1138    fn effective_binding_precedence() {
1139        let session = SessionState {
1140            active: Some(binding("session")),
1141            subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
1142            ..Default::default()
1143        };
1144
1145        // 1. repo_flag wins over everything.
1146        let (b, source) = effective_binding(ResolveInputs {
1147            repo_flag: Some(binding("flag")),
1148            session: &session,
1149            worktree_path: Some("/wt/a"),
1150            bound: Some(binding("bound")),
1151            user_default: Some(binding("userdef")),
1152        })
1153        .unwrap();
1154        assert_eq!(b.repo_id, "flag");
1155        assert_eq!(source, BindingSource::RepoFlag);
1156
1157        // 2. subagent override wins over session active + bound + user default.
1158        let (b, source) = effective_binding(ResolveInputs {
1159            repo_flag: None,
1160            session: &session,
1161            worktree_path: Some("/wt/a"),
1162            bound: Some(binding("bound")),
1163            user_default: Some(binding("userdef")),
1164        })
1165        .unwrap();
1166        assert_eq!(b.repo_id, "subagent");
1167        assert_eq!(source, BindingSource::Subagent);
1168
1169        // 3. session active wins over bound + user default.
1170        let (b, source) = effective_binding(ResolveInputs {
1171            repo_flag: None,
1172            session: &session,
1173            worktree_path: Some("/wt/other"),
1174            bound: Some(binding("bound")),
1175            user_default: Some(binding("userdef")),
1176        })
1177        .unwrap();
1178        assert_eq!(b.repo_id, "session");
1179        assert_eq!(source, BindingSource::SessionActive);
1180
1181        // 4. bound wins over user default.
1182        let empty = SessionState::default();
1183        let (b, source) = effective_binding(ResolveInputs {
1184            repo_flag: None,
1185            session: &empty,
1186            worktree_path: None,
1187            bound: Some(binding("bound")),
1188            user_default: Some(binding("userdef")),
1189        })
1190        .unwrap();
1191        assert_eq!(b.repo_id, "bound");
1192        assert_eq!(source, BindingSource::Bound);
1193
1194        // 5. user default is used when nothing more specific resolves.
1195        let (b, source) = effective_binding(ResolveInputs {
1196            repo_flag: None,
1197            session: &empty,
1198            worktree_path: None,
1199            bound: None,
1200            user_default: Some(binding("userdef")),
1201        })
1202        .unwrap();
1203        assert_eq!(b.repo_id, "userdef");
1204        assert_eq!(source, BindingSource::UserDefault);
1205
1206        // 6. nothing at all → None.
1207        let got = effective_binding(ResolveInputs {
1208            repo_flag: None,
1209            session: &empty,
1210            worktree_path: None,
1211            bound: None,
1212            user_default: None,
1213        });
1214        assert!(got.is_none());
1215    }
1216
1217    #[test]
1218    fn binding_source_display_labels() {
1219        assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
1220        assert_eq!(
1221            BindingSource::Subagent.to_string(),
1222            "subagent worktree override"
1223        );
1224        assert_eq!(
1225            BindingSource::SessionActive.to_string(),
1226            "session (repo switch)"
1227        );
1228        assert_eq!(
1229            BindingSource::Bound.to_string(),
1230            "bound .tracevault/config.toml"
1231        );
1232        assert_eq!(
1233            BindingSource::UserDefault.to_string(),
1234            "user default (repo switch --user)"
1235        );
1236    }
1237
1238    #[test]
1239    fn effective_project_precedence_local_rungs() {
1240        let pb = |n: &str| ProjectBinding {
1241            project_id: n.into(),
1242            project_name: n.into(),
1243            updated_at: "".into(),
1244            forced_until: None,
1245        };
1246        let mut subagent_projects = HashMap::new();
1247        subagent_projects.insert("/wt".into(), pb("subagent"));
1248        let session = SessionState {
1249            active_project: Some(pb("session")),
1250            subagent_projects,
1251            ..Default::default()
1252        };
1253
1254        // rung 1: flag wins over everything
1255        let got = effective_project(&ProjectResolveInputs {
1256            project_flag: Some(pb("flag")),
1257            env_project: None,
1258            session: &session,
1259            worktree_path: Some("/wt"),
1260            config_project: Some(pb("cfg")),
1261        })
1262        .unwrap();
1263        assert_eq!(got.0.project_id, "flag");
1264        assert_eq!(got.1, ProjectSource::ProjectFlag);
1265
1266        // rung 2: subagent (worktree) beats session.active
1267        let got = effective_project(&ProjectResolveInputs {
1268            project_flag: None,
1269            env_project: None,
1270            session: &session,
1271            worktree_path: Some("/wt"),
1272            config_project: Some(pb("cfg")),
1273        })
1274        .unwrap();
1275        assert_eq!(got.1, ProjectSource::Subagent);
1276        assert_eq!(got.0.project_id, "subagent");
1277
1278        // rung 3: session.active when no subagent match
1279        let got = effective_project(&ProjectResolveInputs {
1280            project_flag: None,
1281            env_project: None,
1282            session: &session,
1283            worktree_path: Some("/other"),
1284            config_project: Some(pb("cfg")),
1285        })
1286        .unwrap();
1287        assert_eq!(got.1, ProjectSource::SessionActive);
1288
1289        // rung 3b: config_default when session empty
1290        let got = effective_project(&ProjectResolveInputs {
1291            project_flag: None,
1292            env_project: None,
1293            session: &SessionState::default(),
1294            worktree_path: None,
1295            config_project: Some(pb("cfg")),
1296        })
1297        .unwrap();
1298        assert_eq!(got.1, ProjectSource::Workspace);
1299
1300        // none: nothing local
1301        assert!(effective_project(&ProjectResolveInputs {
1302            project_flag: None,
1303            env_project: None,
1304            session: &SessionState::default(),
1305            worktree_path: None,
1306            config_project: None,
1307        })
1308        .is_none());
1309    }
1310
1311    /// Every tier of the capture chain, top to bottom, plus the empty case:
1312    /// flag → subagent → env → session active → workspace config
1313    /// `project_id` → user default. This pins the order `project status` and
1314    /// ingest share (VIS-316, VIS-1256). The struct literals are exhaustive —
1315    /// a new input breaks every one of them, forcing a deliberate decision
1316    /// about its rank here. The legacy `default_project` NAME is not an input
1317    /// at all (see `project_from_config_reads_project_id_never_default_project`).
1318    #[test]
1319    fn capture_project_binding_precedence() {
1320        let pb = |n: &str| ProjectBinding {
1321            project_id: n.into(),
1322            project_name: n.into(),
1323            updated_at: "".into(),
1324            forced_until: None,
1325        };
1326        let mut subagent_projects = HashMap::new();
1327        subagent_projects.insert("/wt".into(), pb("subagent"));
1328        let session = SessionState {
1329            active_project: Some(pb("session")),
1330            subagent_projects,
1331            ..Default::default()
1332        };
1333
1334        // tier 1: flag wins over everything
1335        let got = capture_project_binding(&CaptureProjectInputs {
1336            project_flag: Some(pb("flag")),
1337            env_project: Some(pb("env")),
1338            session: &session,
1339            worktree_path: Some("/wt"),
1340            config_project: Some(pb("config")),
1341            user_default: Some(pb("user")),
1342        })
1343        .unwrap();
1344        assert_eq!(
1345            (got.0.project_id.as_str(), got.1),
1346            ("flag", ProjectSource::ProjectFlag)
1347        );
1348
1349        // tier 2: subagent worktree override beats env and session active
1350        let got = capture_project_binding(&CaptureProjectInputs {
1351            project_flag: None,
1352            env_project: Some(pb("env")),
1353            session: &session,
1354            worktree_path: Some("/wt"),
1355            config_project: Some(pb("config")),
1356            user_default: Some(pb("user")),
1357        })
1358        .unwrap();
1359        assert_eq!(
1360            (got.0.project_id.as_str(), got.1),
1361            ("subagent", ProjectSource::Subagent)
1362        );
1363
1364        // tier 3: TRACEVAULT_PROJECT beats session active and the user default
1365        let got = capture_project_binding(&CaptureProjectInputs {
1366            project_flag: None,
1367            env_project: Some(pb("env")),
1368            session: &session,
1369            worktree_path: Some("/other"),
1370            config_project: Some(pb("config")),
1371            user_default: Some(pb("user")),
1372        })
1373        .unwrap();
1374        assert_eq!(
1375            (got.0.project_id.as_str(), got.1),
1376            ("env", ProjectSource::Env)
1377        );
1378
1379        // tier 4: session active when the worktree has no override and no env
1380        let got = capture_project_binding(&CaptureProjectInputs {
1381            project_flag: None,
1382            env_project: None,
1383            session: &session,
1384            worktree_path: Some("/other"),
1385            config_project: Some(pb("config")),
1386            user_default: Some(pb("user")),
1387        })
1388        .unwrap();
1389        assert_eq!(
1390            (got.0.project_id.as_str(), got.1),
1391            ("session", ProjectSource::SessionActive)
1392        );
1393
1394        // tier 5: the workspace config's project_id when the session has
1395        // nothing — above the user default (VIS-1256)
1396        let got = capture_project_binding(&CaptureProjectInputs {
1397            project_flag: None,
1398            env_project: None,
1399            session: &SessionState::default(),
1400            worktree_path: Some("/wt"),
1401            config_project: Some(pb("config")),
1402            user_default: Some(pb("user")),
1403        })
1404        .unwrap();
1405        assert_eq!(
1406            (got.0.project_id.as_str(), got.1),
1407            ("config", ProjectSource::Workspace)
1408        );
1409
1410        // tier 6: user default when neither the session nor the config has one
1411        let got = capture_project_binding(&CaptureProjectInputs {
1412            project_flag: None,
1413            env_project: None,
1414            session: &SessionState::default(),
1415            worktree_path: Some("/wt"),
1416            config_project: None,
1417            user_default: Some(pb("user")),
1418        })
1419        .unwrap();
1420        assert_eq!(
1421            (got.0.project_id.as_str(), got.1),
1422            ("user", ProjectSource::UserDefault)
1423        );
1424
1425        // none: nothing anywhere
1426        assert!(capture_project_binding(&CaptureProjectInputs {
1427            project_flag: None,
1428            env_project: None,
1429            session: &SessionState::default(),
1430            worktree_path: None,
1431            config_project: None,
1432            user_default: None,
1433        })
1434        .is_none());
1435    }
1436
1437    /// The workspace tier reads `project_id` (+ display `project_name`) and
1438    /// nothing else: a config with only the legacy `default_project` NAME
1439    /// contributes nothing, so ingest never resolves names (VIS-1256).
1440    #[test]
1441    fn project_from_config_reads_project_id_never_default_project() {
1442        let legacy = crate::config::TracevaultConfig {
1443            default_project: Some("visdom".into()),
1444            ..Default::default()
1445        };
1446        assert_eq!(project_from_config(&legacy), None);
1447        let blank = crate::config::TracevaultConfig {
1448            project_id: Some("  ".into()),
1449            ..Default::default()
1450        };
1451        assert_eq!(project_from_config(&blank), None);
1452        let migrated = crate::config::TracevaultConfig {
1453            project_id: Some("00000000-0000-4000-8000-0000000000aa".into()),
1454            project_name: Some("visdom".into()),
1455            default_project: Some("old".into()),
1456            ..Default::default()
1457        };
1458        let got = project_from_config(&migrated).unwrap();
1459        assert_eq!(got.project_id, "00000000-0000-4000-8000-0000000000aa");
1460        assert_eq!(got.project_name, "visdom");
1461    }
1462
1463    #[test]
1464    fn capture_project_id_accepts_uuid_rejects_garbage() {
1465        let pb = |id: &str| ProjectBinding {
1466            project_id: id.into(),
1467            project_name: "n".into(),
1468            updated_at: "".into(),
1469            forced_until: None,
1470        };
1471        let u = uuid::Uuid::from_u128(7);
1472        assert_eq!(capture_project_id(&pb(&u.to_string())), Some(u));
1473        assert_eq!(capture_project_id(&pb("not-a-uuid")), None);
1474        assert_eq!(capture_project_id(&pb("")), None);
1475    }
1476
1477    #[test]
1478    fn env_outranks_remembered_state_but_not_flag_or_subagent() {
1479        let pb = |n: &str| ProjectBinding {
1480            project_id: n.into(),
1481            project_name: n.into(),
1482            updated_at: "".into(),
1483            forced_until: None,
1484        };
1485        let mut subagent_projects = HashMap::new();
1486        subagent_projects.insert("/wt".to_string(), pb("subagent"));
1487        let session = SessionState {
1488            active_project: Some(pb("session")),
1489            subagent_projects,
1490            ..Default::default()
1491        };
1492
1493        // env beats session active and config default
1494        let got = effective_project(&ProjectResolveInputs {
1495            project_flag: None,
1496            env_project: Some(pb("env")),
1497            session: &session,
1498            worktree_path: None,
1499            config_project: Some(pb("config")),
1500        });
1501        assert_eq!(got.unwrap().1, ProjectSource::Env);
1502
1503        // the subagent worktree override still beats env
1504        let got = effective_project(&ProjectResolveInputs {
1505            project_flag: None,
1506            env_project: Some(pb("env")),
1507            session: &session,
1508            worktree_path: Some("/wt"),
1509            config_project: None,
1510        });
1511        assert_eq!(got.unwrap().1, ProjectSource::Subagent);
1512
1513        // --project still beats env
1514        let got = effective_project(&ProjectResolveInputs {
1515            project_flag: Some(pb("flag")),
1516            env_project: Some(pb("env")),
1517            session: &session,
1518            worktree_path: None,
1519            config_project: None,
1520        });
1521        assert_eq!(got.unwrap().1, ProjectSource::ProjectFlag);
1522    }
1523
1524    #[test]
1525    fn binding_from_config_carries_remote_id_and_codebase_name() {
1526        let uuid = uuid::Uuid::new_v4();
1527        let config = crate::config::TracevaultConfig {
1528            repo_id: Some("repo-1".into()),
1529            remote_id: Some(uuid.to_string()),
1530            codebase_name: Some("acme/foo".into()),
1531            ..Default::default()
1532        };
1533        let binding = binding_from_config(&config).expect("repo_id present");
1534        assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
1535        assert_eq!(binding.remote_id, Some(uuid));
1536    }
1537
1538    #[test]
1539    fn codebase_line_formats_name_and_status() {
1540        let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
1541        assert_eq!(line, "codebase: acme/foo (ready)");
1542        let line = codebase_line(None, "github.com/acme/foo", "pending");
1543        assert_eq!(line, "codebase: github.com/acme/foo (pending)");
1544    }
1545
1546    #[test]
1547    fn pick_status_line_detail_wins_over_resolved_and_cached() {
1548        assert_eq!(
1549            pick_status_line(
1550                Some("codebase: a (ready)".to_string()),
1551                Some("codebase: b (pending)".to_string()),
1552                Some("c"),
1553            ),
1554            Some("codebase: a (ready)".to_string())
1555        );
1556    }
1557
1558    #[test]
1559    fn pick_status_line_resolved_wins_over_cached() {
1560        assert_eq!(
1561            pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
1562            Some("codebase: b (pending)".to_string())
1563        );
1564    }
1565
1566    #[test]
1567    fn pick_status_line_cached_only_is_name_only() {
1568        assert_eq!(
1569            pick_status_line(None, None, Some("c")),
1570            Some("codebase: c".to_string())
1571        );
1572    }
1573
1574    #[test]
1575    fn pick_status_line_none_when_nothing_available() {
1576        assert_eq!(pick_status_line(None, None, None), None);
1577    }
1578
1579    #[tokio::test]
1580    async fn resolve_repo_by_name_ok_when_name_matches() {
1581        let tmp = tempfile::tempdir().unwrap();
1582        crate::test_helpers::init_git_repo(tmp.path());
1583        let repo_name = git_repo_name(tmp.path());
1584        let body =
1585            format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
1586        let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
1587        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1588
1589        let repo = resolve_repo_by_name(&client, tmp.path())
1590            .await
1591            .expect("expected a match");
1592        assert_eq!(repo.name, repo_name);
1593    }
1594
1595    #[tokio::test]
1596    async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
1597        let tmp = tempfile::tempdir().unwrap();
1598        crate::test_helpers::init_git_repo(tmp.path());
1599        let (addr, _h) = spawn_once(
1600            "200 OK",
1601            r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
1602        );
1603        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1604
1605        match resolve_repo_by_name(&client, tmp.path()).await {
1606            Err(ResolveRepoByNameError::NotFound { .. }) => {}
1607            other => panic!(
1608                "expected NotFound, got a different outcome: {}",
1609                other.is_ok()
1610            ),
1611        }
1612    }
1613
1614    #[tokio::test]
1615    async fn resolve_repo_by_name_list_failed_on_non_2xx() {
1616        // A `list_repos` failure (401/403/500/... — not necessarily a
1617        // network error, hence `ListFailed` rather than the old `Network`
1618        // name) must be distinguished from `NotFound` so callers like
1619        // `check`'s `connectivity_message` can add their own actionable
1620        // wrapping instead of a bare "not found" message.
1621        let tmp = tempfile::tempdir().unwrap();
1622        crate::test_helpers::init_git_repo(tmp.path());
1623        let (addr, _h) = spawn_once("500 Internal Server Error", "");
1624        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1625
1626        match resolve_repo_by_name(&client, tmp.path()).await {
1627            Err(ResolveRepoByNameError::ListFailed(e)) => {
1628                assert!(e.to_string().contains("500"), "got: {e}");
1629            }
1630            other => panic!(
1631                "expected ListFailed, got a different outcome: {}",
1632                other.is_ok()
1633            ),
1634        }
1635    }
1636
1637    // ── pick_listed_repo: config.toml binding before the checkout name ────────
1638
1639    fn listed(id: u128, name: &str) -> RepoListItem {
1640        RepoListItem {
1641            id: uuid::Uuid::from_u128(id),
1642            name: name.into(),
1643            github_url: None,
1644            clone_status: None,
1645        }
1646    }
1647
1648    /// A checkout bound by `init` to an existing record named differently
1649    /// (VIS-1018) still resolves, via its config.toml repo_id.
1650    #[test]
1651    fn pick_listed_repo_prefers_the_bound_id_over_the_name() {
1652        let repos = vec![listed(1, "tracing"), listed(2, "tracevault")];
1653        let got = pick_listed_repo(repos, Some(uuid::Uuid::from_u128(2)), "tracing").unwrap();
1654        assert_eq!(got.name, "tracevault");
1655    }
1656
1657    #[test]
1658    fn pick_listed_repo_falls_back_to_the_name() {
1659        let repos = vec![listed(1, "tracing"), listed(2, "tracevault")];
1660        let got = pick_listed_repo(repos, Some(uuid::Uuid::from_u128(9)), "tracing").unwrap();
1661        assert_eq!(got.name, "tracing");
1662        assert!(pick_listed_repo(vec![listed(1, "x")], None, "y").is_none());
1663    }
1664}