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