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    let preferred: Vec<uuid::Uuid> = checkout_config_repo_id(path).into_iter().collect();
334    let repo_id = match codebase.choose(&preferred) {
335        RepoChoice::Only(id) | RepoChoice::Preferred(id, _) => id,
336        RepoChoice::Ambiguous => codebase
337            .repos
338            .iter()
339            .map(|r| r.id)
340            .min()
341            .expect("resolve_path_to_codebase never returns an empty repo list"),
342    };
343    Ok(Some(codebase.binding(repo_id)))
344}
345
346/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
347/// are resolved by the caller (the `--path` override and the bound
348/// `config.toml`, respectively); `session`/`worktree_path` come from the
349/// per-session state.
350pub struct ResolveInputs<'a> {
351    pub repo_flag: Option<RepoBinding>,
352    pub session: &'a SessionState,
353    pub worktree_path: Option<&'a str>,
354    pub bound: Option<RepoBinding>,
355    /// Lowest-precedence, session-independent default (from `repo switch --user`
356    /// / a no-session switch). Applies when nothing more specific resolves.
357    pub user_default: Option<RepoBinding>,
358}
359
360/// Inputs for the effective-project precedence chain. `project_flag` and
361/// `config_default` are resolved by the caller; `session`/`worktree_path`
362/// come from the per-session state.
363pub struct ProjectResolveInputs<'a> {
364    pub project_flag: Option<ProjectBinding>,
365    /// Parsed from `TRACEVAULT_PROJECT` by the caller, so this module stays
366    /// free of environment reads and remains a pure function of its inputs.
367    pub env_project: Option<ProjectBinding>,
368    pub session: &'a SessionState,
369    pub worktree_path: Option<&'a str>,
370    pub config_default: Option<ProjectBinding>,
371}
372
373/// Which precedence tier produced the [`effective_binding`] result.
374#[derive(Debug, Clone, Copy, PartialEq, Eq)]
375pub enum BindingSource {
376    /// A `--path <path>` flag override (on `repo status`).
377    RepoFlag,
378    /// A subagent's per-worktree override.
379    Subagent,
380    /// The session's session-level active binding.
381    SessionActive,
382    /// A pinned `.tracevault/config.toml` (bound mode).
383    Bound,
384    /// A session-independent user-level default (`repo switch --user`).
385    UserDefault,
386}
387
388impl std::fmt::Display for BindingSource {
389    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
390        let label = match self {
391            BindingSource::RepoFlag => "--path override",
392            BindingSource::Subagent => "subagent worktree override",
393            BindingSource::SessionActive => "session (repo switch)",
394            BindingSource::Bound => "bound .tracevault/config.toml",
395            BindingSource::UserDefault => "user default (repo switch --user)",
396        };
397        f.write_str(label)
398    }
399}
400
401/// Which precedence tier produced the [`effective_project`] result.
402#[derive(Debug, Clone, Copy, PartialEq, Eq)]
403pub enum ProjectSource {
404    /// A `--project <id>` flag override.
405    ProjectFlag,
406    /// A subagent's per-worktree override.
407    Subagent,
408    /// The `TRACEVAULT_PROJECT` environment variable — a per-process
409    /// assertion, re-asserted at every launch and never written to disk.
410    /// Outranks every remembered tier so a stale `user_project.toml` or a
411    /// `.tracevault/config.toml` baked into a pod image cannot outrank the
412    /// launcher that started the process.
413    Env,
414    /// The session's project-level active binding.
415    SessionActive,
416    /// A pinned `.tracevault/config.toml` default_project (bound mode).
417    ConfigDefault,
418    /// Repo deduction from the git remote, resolved server-side. Produced
419    /// only by the display chain [`resolve_effective_project`], never by the
420    /// capture chain [`capture_project_binding`].
421    Deduced,
422    /// A session-independent user-level default (`project switch --user`).
423    /// Produced by [`capture_project_binding`] and
424    /// [`resolve_effective_project`], not [`effective_project`].
425    UserDefault,
426}
427
428impl std::fmt::Display for ProjectSource {
429    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
430        let label = match self {
431            ProjectSource::ProjectFlag => "--project override",
432            ProjectSource::Subagent => "subagent worktree override",
433            ProjectSource::Env => "TRACEVAULT_PROJECT (environment)",
434            ProjectSource::SessionActive => "session (project switch)",
435            ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
436            ProjectSource::Deduced => "repo deduction",
437            ProjectSource::UserDefault => "user default (project switch --user)",
438        };
439        f.write_str(label)
440    }
441}
442
443/// The binding that applies, and which tier produced it: `--path` flag →
444/// subagent worktree override → session active → bound config → user
445/// default → none.
446pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
447    if let Some(b) = inputs.repo_flag {
448        return Some((b, BindingSource::RepoFlag));
449    }
450    if let Some(wt) = inputs.worktree_path {
451        if let Some(b) = inputs.session.subagents.get(wt) {
452            return Some((b.clone(), BindingSource::Subagent));
453        }
454    }
455    if let Some(b) = &inputs.session.active {
456        return Some((b.clone(), BindingSource::SessionActive));
457    }
458    if let Some(b) = inputs.bound {
459        return Some((b, BindingSource::Bound));
460    }
461    inputs.user_default.map(|b| (b, BindingSource::UserDefault))
462}
463
464/// The project that applies, and which tier produced it: `--project` flag →
465/// subagent worktree override → `TRACEVAULT_PROJECT` → session active →
466/// config default → none.
467/// Pure; covers only the local tiers (flag → subagent → env_project →
468/// session.active_project → config_default). `env_project` is supplied BY THE
469/// CALLER — this module never reads the environment — and the capture path
470/// fills it from `commands::stream::env_project_binding`, which honours the
471/// UUID form only. The user-level default (and, in the display chain only,
472/// server-side deduction) are applied afterward by [`capture_project_binding`]
473/// / [`resolve_effective_project`], which call this function first and only
474/// fall through to those tiers when it returns `None`.
475pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
476    if let Some(b) = &inputs.project_flag {
477        return Some((b.clone(), ProjectSource::ProjectFlag));
478    }
479    if let Some(wt) = inputs.worktree_path {
480        if let Some(b) = inputs.session.subagent_projects.get(wt) {
481            return Some((b.clone(), ProjectSource::Subagent));
482        }
483    }
484    if let Some(b) = &inputs.env_project {
485        return Some((b.clone(), ProjectSource::Env));
486    }
487    if let Some(b) = &inputs.session.active_project {
488        return Some((b.clone(), ProjectSource::SessionActive));
489    }
490    inputs
491        .config_default
492        .clone()
493        .map(|b| (b, ProjectSource::ConfigDefault))
494}
495
496/// Inputs to the capture-time project chain. Deliberately has NO
497/// `config_default` field: `.tracevault/config.toml` `default_project` is a
498/// NAME, resolving it needs a network call, and the stream hook (which fires
499/// per event) never does one — so no caller of this chain can feed it in.
500pub struct CaptureProjectInputs<'a> {
501    /// `--project` override (only `project status` supplies it; the hook passes `None`).
502    pub project_flag: Option<ProjectBinding>,
503    /// `TRACEVAULT_PROJECT`, UUID form ONLY — parsed by the caller (via
504    /// `commands::stream::env_project_binding`) so this module stays free of
505    /// environment reads. The NAME form is deliberately not a tier here: it
506    /// would need a `list_projects` round trip, and this is the network-free
507    /// chain the per-event hook runs. Both callers fill this field from that
508    /// same reader, so `project status` cannot report a tier ingest ignores.
509    pub env_project: Option<ProjectBinding>,
510    pub session: &'a SessionState,
511    pub worktree_path: Option<&'a str>,
512    /// `user_project_default::load()` — passed in so the function stays pure.
513    pub user_default: Option<ProjectBinding>,
514}
515
516/// THE capture-time project chain: `--project` flag → subagent worktree
517/// override → `TRACEVAULT_PROJECT` → session `active_project` → user default
518/// → none. Pure, no network. `commands::stream::capture_project` (ingest) and
519/// `commands::project::status` both call this, so they cannot drift.
520pub fn capture_project_binding(
521    inputs: &CaptureProjectInputs<'_>,
522) -> Option<(ProjectBinding, ProjectSource)> {
523    effective_project(&ProjectResolveInputs {
524        project_flag: inputs.project_flag.clone(),
525        env_project: inputs.env_project.clone(),
526        session: inputs.session,
527        worktree_path: inputs.worktree_path,
528        config_default: None,
529    })
530    .or_else(|| {
531        inputs
532            .user_default
533            .clone()
534            .map(|b| (b, ProjectSource::UserDefault))
535    })
536}
537
538/// The id the hook will actually send for a capture binding: `None` when the
539/// stored `project_id` is not a UUID (a hand-edited or corrupted
540/// `user_project.toml`/session file), in which case ingest treats the binding
541/// as absent and the event goes repo-scoped.
542pub fn capture_project_id(binding: &ProjectBinding) -> Option<uuid::Uuid> {
543    binding.project_id.parse::<uuid::Uuid>().ok()
544}
545
546/// DISPLAY chain for `commands::status`'s "Project" line: `--project` flag →
547/// subagent override → `TRACEVAULT_PROJECT` → session active → config default
548/// (all pure, via [`effective_project`]; no network call) → user-level default
549/// → server-side deduction from the repo's git remote.
550///
551/// The user-level default outranks deduction because that is what ingest
552/// does: the capture chain ([`capture_project_binding`]) applies the user
553/// default and never deduces, so a display chain that ranked deduction above
554/// it would name a project no event is attributed to — exactly in the
555/// orchestrator's configuration (a pod bound via `project switch --user`). The
556/// server is only asked once every local tier, user default included, is empty.
557///
558/// An `Ambiguous` deduction result is an error (the caller can't safely guess
559/// among several candidate projects). This resolver never prints: callers
560/// render the tier via [`ProjectSource`]'s `Display`. Returns `Ok(None)` only
561/// when every tier in the chain is empty. `commands::project::status` does not
562/// use this chain: it reports [`capture_project_binding`] and shows deduction
563/// on a separate line.
564pub async fn resolve_effective_project(
565    inputs: &ProjectResolveInputs<'_>,
566    user_default: Option<ProjectBinding>,
567    git_url: Option<&str>,
568    client: &ApiClient,
569) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
570    // Local tiers: flag → subagent → TRACEVAULT_PROJECT → session active →
571    // config default.
572    if let Some(hit) = effective_project(inputs) {
573        return Ok(Some(hit));
574    }
575    // User-level default: ingest honours it, so it outranks deduction.
576    if let Some(b) = user_default {
577        return Ok(Some((b, ProjectSource::UserDefault)));
578    }
579    // Server-side deduction from the repo's git remote (lowest tier).
580    if let Some(url) = git_url {
581        match client.resolve_project(url).await? {
582            ResolveProjectOutcome::Resolved(pid) => {
583                return Ok(Some((
584                    ProjectBinding {
585                        project_id: pid.to_string(),
586                        project_name: String::new(), // enriched for display by the caller if needed
587                        updated_at: String::new(),
588                        forced_until: None,
589                    },
590                    ProjectSource::Deduced,
591                )));
592            }
593            ResolveProjectOutcome::Ambiguous => {
594                return Err(
595                    "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
596                        .to_string()
597                        .into(),
598                );
599            }
600            ResolveProjectOutcome::None => { /* fall through */ }
601        }
602    }
603    Ok(None)
604}
605
606/// The repo binding a recorded session's events were streamed under, resolved
607/// exactly as the stream hook resolves it — so `check` and `verify-start` work
608/// under the same repo id the session's events went to (VIS-601).
609///
610/// The whole chain runs off `session_dir`, like `flush`'s
611/// `queue_capture_binding`: the session id is its file name (the caller loads
612/// `state` from it), and the subagent worktree override is keyed by the
613/// worktree toplevel the hook recorded in its `origin` marker. `bound` and
614/// `user_default` are the lower tiers the hook also consults.
615///
616/// A binding whose `repo_id` is not a UUID resolves to `None`, as it does for
617/// the hook (`stream::attribution_for` never sends to it).
618pub(crate) fn recorded_session_binding(
619    session_dir: &Path,
620    state: &SessionState,
621    bound: Option<RepoBinding>,
622    user_default: Option<RepoBinding>,
623) -> Option<RepoBinding> {
624    let worktree = std::fs::read_to_string(session_dir.join("origin"))
625        .ok()
626        .map(|s| s.trim().to_string());
627    effective_binding(ResolveInputs {
628        repo_flag: None,
629        session: state,
630        worktree_path: worktree.as_deref(),
631        bound,
632        user_default,
633    })
634    .map(|(b, _)| b)
635    .filter(|b| crate::commands::stream::binding_repo_id_is_valid(&b.repo_id))
636}
637
638/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
639/// a repo_id. Pure — caller supplies the already-loaded config.
640/// Carries through the `remote_id`/`codebase_name` `init` persisted (best-effort,
641/// display-only) so bound-mode `status` can print the codebase without an extra
642/// network round-trip; `git_url` stays `None` here — bound mode has no live
643/// origin URL to hand back (that's the older `git_url` fallback's job, covering
644/// bindings that predate `codebase_name`).
645pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
646    Some(RepoBinding {
647        repo_id: config.repo_id.clone()?,
648        git_url: None,
649        remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
650        codebase_name: config.codebase_name.clone(),
651        updated_at: String::new(),
652    })
653}
654
655#[cfg(test)]
656mod tests {
657    use super::*;
658    use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
659    use std::collections::HashMap;
660    use std::io::{BufRead, BufReader, Write};
661    use std::net::{SocketAddr, TcpListener};
662    use std::thread;
663
664    #[test]
665    fn repo_basename_bare_name() {
666        assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
667    }
668
669    #[test]
670    fn repo_basename_nested_path() {
671        assert_eq!(
672            repo_basename("/home/user/code/myrepo"),
673            Some("myrepo".to_string())
674        );
675    }
676
677    #[test]
678    fn repo_basename_trailing_slash() {
679        // `Path::file_name` skips a trailing separator rather than treating
680        // it as an empty final component.
681        assert_eq!(
682            repo_basename("/home/user/code/myrepo/"),
683            Some("myrepo".to_string())
684        );
685    }
686
687    #[test]
688    fn repo_basename_dot_git_suffix_directory() {
689        // A checkout directory literally named `myrepo.git` (e.g. a bare
690        // clone) keeps the suffix — `git_repo_name` takes the raw basename,
691        // it does not strip `.git`.
692        assert_eq!(
693            repo_basename("/srv/repos/myrepo.git"),
694            Some("myrepo.git".to_string())
695        );
696    }
697
698    #[test]
699    fn repo_basename_root_has_no_basename() {
700        assert_eq!(repo_basename("/"), None);
701    }
702
703    /// Spawn a one-shot raw-HTTP server that returns a response built from
704    /// `status` (e.g. `"200 OK"`) and `body` to the first request it accepts.
705    /// Mirrors the `spawn_once`/`http_200` shape in `commands::repo`'s test
706    /// module (bind loopback, accept once on a background thread, write the
707    /// raw HTTP response, flush, close).
708    fn spawn_once(
709        status: &'static str,
710        body: &'static str,
711    ) -> (SocketAddr, thread::JoinHandle<()>) {
712        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
713        let addr = listener.local_addr().unwrap();
714        let response = http_200(status, body);
715        let handle = thread::spawn(move || {
716            if let Ok((stream, _)) = listener.accept() {
717                let mut reader = BufReader::new(stream);
718                let mut request_line = String::new();
719                let _ = reader.read_line(&mut request_line);
720                let mut stream = reader.into_inner();
721                let _ = stream.write_all(response.as_bytes());
722                let _ = stream.flush();
723            }
724        });
725        (addr, handle)
726    }
727
728    /// Format a raw HTTP/1.1 response with the given `status` line and a
729    /// correct `Content-Length` for a JSON `body`.
730    fn http_200(status: &str, body: &str) -> String {
731        format!(
732            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
733            status,
734            body.len(),
735            body
736        )
737    }
738
739    #[tokio::test]
740    async fn user_default_beats_deduction() {
741        // Ingest applies the user default and never deduces, so the display
742        // chain must too: with a user default present, NO server request may
743        // be made. The client points at port 0 (nothing listens there), so a
744        // deduction attempt would surface as an Err rather than Ok(UserDefault).
745        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
746        let ud = ProjectBinding {
747            project_id: "user".into(),
748            project_name: "u".into(),
749            updated_at: "".into(),
750            forced_until: None,
751        };
752        let inputs = ProjectResolveInputs {
753            project_flag: None,
754            env_project: None,
755            session: &SessionState::default(),
756            worktree_path: None,
757            config_default: None,
758        };
759        let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
760            .await
761            .expect("a user default must resolve without any network call")
762            .unwrap();
763        assert_eq!(src, ProjectSource::UserDefault);
764        assert_eq!(b.project_id, "user");
765    }
766
767    #[tokio::test]
768    async fn deduction_used_when_no_local_tier_or_user_default() {
769        let (addr, _h) = spawn_once(
770            "200 OK",
771            "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
772        );
773        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
774        let inputs = ProjectResolveInputs {
775            project_flag: None,
776            env_project: None,
777            session: &SessionState::default(),
778            worktree_path: None,
779            config_default: None,
780        };
781        let (b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
782            .await
783            .unwrap()
784            .unwrap();
785        assert_eq!(src, ProjectSource::Deduced);
786        assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
787    }
788
789    #[tokio::test]
790    async fn ambiguous_deduction_errors_when_no_higher_rung() {
791        let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
792        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
793        let inputs = ProjectResolveInputs {
794            project_flag: None,
795            env_project: None,
796            session: &SessionState::default(),
797            worktree_path: None,
798            config_default: None,
799        };
800        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
801            .await
802            .unwrap_err();
803        assert!(err.to_string().to_lowercase().contains("--project"));
804    }
805
806    #[tokio::test]
807    async fn domain_404_deduction_resolves_to_none() {
808        // A domain 404 (server's `{"error": ...}` envelope) — the shape a
809        // real (non-skewed) server sends for "no project" — falls through to
810        // `Ok(None)`, unlike a bare route-404. The user default is `None`
811        // here: a present user default now short-circuits before the
812        // deduction call (see `user_default_beats_deduction`).
813        let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
814        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
815        let inputs = ProjectResolveInputs {
816            project_flag: None,
817            env_project: None,
818            session: &SessionState::default(),
819            worktree_path: None,
820            config_default: None,
821        };
822        let got = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
823            .await
824            .unwrap();
825        assert!(got.is_none(), "got: {got:?}");
826    }
827
828    #[tokio::test]
829    async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
830        // A bare 404 (no JSON error body) is axum's "no route matched"
831        // fallback, not a domain "no project" — it must propagate as an
832        // error instead of silently falling through to `Ok(None)`. No user
833        // default: one would short-circuit before the deduction call.
834        let (addr, _h) = spawn_once("404 Not Found", "");
835        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
836        let inputs = ProjectResolveInputs {
837            project_flag: None,
838            env_project: None,
839            session: &SessionState::default(),
840            worktree_path: None,
841            config_default: None,
842        };
843        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
844            .await
845            .expect_err("a bare 404 must not silently fall through to Ok(None)");
846        assert!(err.to_string().to_lowercase().contains("version mismatch"));
847    }
848
849    #[tokio::test]
850    async fn local_rung_skips_server_call() {
851        // no server spawned; a config_default present must resolve WITHOUT any network call
852        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
853        let cfg = ProjectBinding {
854            project_id: "cfg".into(),
855            project_name: "c".into(),
856            updated_at: "".into(),
857            forced_until: None,
858        };
859        let inputs = ProjectResolveInputs {
860            project_flag: None,
861            env_project: None,
862            session: &SessionState::default(),
863            worktree_path: None,
864            config_default: Some(cfg),
865        };
866        let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
867            .await
868            .unwrap()
869            .unwrap();
870        assert_eq!(src, ProjectSource::ConfigDefault);
871    }
872
873    fn binding(id: &str) -> RepoBinding {
874        RepoBinding {
875            repo_id: id.into(),
876            git_url: None,
877            remote_id: None,
878            codebase_name: None,
879            updated_at: "t".into(),
880        }
881    }
882
883    const REPO_A: &str = "11111111-1111-1111-1111-111111111111";
884    const REPO_B: &str = "22222222-2222-2222-2222-222222222222";
885    const REPO_C: &str = "33333333-3333-3333-3333-333333333333";
886
887    fn session_dir_with_origin(origin: Option<&str>) -> tempfile::TempDir {
888        let dir = tempfile::tempdir().unwrap();
889        if let Some(o) = origin {
890            std::fs::write(dir.path().join("origin"), o).unwrap();
891        }
892        dir
893    }
894
895    #[test]
896    fn recorded_session_binding_prefers_repo_switch_over_config() {
897        let dir = session_dir_with_origin(Some("/wt/a"));
898        let state = SessionState {
899            active: Some(binding(REPO_A)),
900            ..Default::default()
901        };
902        let got =
903            recorded_session_binding(dir.path(), &state, Some(binding(REPO_B)), None).unwrap();
904        assert_eq!(got.repo_id, REPO_A);
905    }
906
907    #[test]
908    fn recorded_session_binding_honours_subagent_override_via_origin_marker() {
909        // The hook writes no trailing newline today; a hand-edited marker with
910        // one must still key the override.
911        let dir = session_dir_with_origin(Some("/wt/sub\n"));
912        let mut state = SessionState {
913            active: Some(binding(REPO_A)),
914            ..Default::default()
915        };
916        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
917        let got = recorded_session_binding(dir.path(), &state, None, None).unwrap();
918        assert_eq!(got.repo_id, REPO_C);
919    }
920
921    #[test]
922    fn recorded_session_binding_unbound_falls_to_config_then_user_default() {
923        let dir = session_dir_with_origin(None);
924        let state = SessionState::default();
925        let got = recorded_session_binding(
926            dir.path(),
927            &state,
928            Some(binding(REPO_B)),
929            Some(binding(REPO_C)),
930        )
931        .unwrap();
932        assert_eq!(got.repo_id, REPO_B);
933        let got =
934            recorded_session_binding(dir.path(), &state, None, Some(binding(REPO_C))).unwrap();
935        assert_eq!(got.repo_id, REPO_C);
936        assert!(recorded_session_binding(dir.path(), &state, None, None).is_none());
937    }
938
939    #[test]
940    fn recorded_session_binding_rejects_non_uuid_repo_id() {
941        let dir = session_dir_with_origin(Some("/wt/a"));
942        let state = SessionState {
943            active: Some(binding("../escape")),
944            ..Default::default()
945        };
946        assert!(recorded_session_binding(dir.path(), &state, None, None).is_none());
947    }
948
949    /// The same session must resolve to the same repo on the hook side and on
950    /// the `check`/`verify-start` side — the whole point of VIS-601.
951    #[test]
952    fn recorded_session_binding_agrees_with_stream_hook() {
953        let mut state = SessionState {
954            active: Some(binding(REPO_A)),
955            ..Default::default()
956        };
957        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
958        for wt in ["/wt/main", "/wt/sub"] {
959            let dir = session_dir_with_origin(Some(wt));
960            let hook = crate::commands::stream::resolve_stream_binding(
961                &state,
962                wt,
963                Some(binding(REPO_B)),
964                None,
965            );
966            let recorded =
967                recorded_session_binding(dir.path(), &state, Some(binding(REPO_B)), None);
968            assert_eq!(
969                hook.map(|b| b.repo_id),
970                recorded.map(|b| b.repo_id),
971                "worktree {wt}"
972            );
973        }
974    }
975
976    #[test]
977    fn effective_binding_precedence() {
978        let session = SessionState {
979            active: Some(binding("session")),
980            subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
981            ..Default::default()
982        };
983
984        // 1. repo_flag wins over everything.
985        let (b, source) = effective_binding(ResolveInputs {
986            repo_flag: Some(binding("flag")),
987            session: &session,
988            worktree_path: Some("/wt/a"),
989            bound: Some(binding("bound")),
990            user_default: Some(binding("userdef")),
991        })
992        .unwrap();
993        assert_eq!(b.repo_id, "flag");
994        assert_eq!(source, BindingSource::RepoFlag);
995
996        // 2. subagent override wins over session active + bound + user default.
997        let (b, source) = effective_binding(ResolveInputs {
998            repo_flag: None,
999            session: &session,
1000            worktree_path: Some("/wt/a"),
1001            bound: Some(binding("bound")),
1002            user_default: Some(binding("userdef")),
1003        })
1004        .unwrap();
1005        assert_eq!(b.repo_id, "subagent");
1006        assert_eq!(source, BindingSource::Subagent);
1007
1008        // 3. session active wins over bound + user default.
1009        let (b, source) = effective_binding(ResolveInputs {
1010            repo_flag: None,
1011            session: &session,
1012            worktree_path: Some("/wt/other"),
1013            bound: Some(binding("bound")),
1014            user_default: Some(binding("userdef")),
1015        })
1016        .unwrap();
1017        assert_eq!(b.repo_id, "session");
1018        assert_eq!(source, BindingSource::SessionActive);
1019
1020        // 4. bound wins over user default.
1021        let empty = SessionState::default();
1022        let (b, source) = effective_binding(ResolveInputs {
1023            repo_flag: None,
1024            session: &empty,
1025            worktree_path: None,
1026            bound: Some(binding("bound")),
1027            user_default: Some(binding("userdef")),
1028        })
1029        .unwrap();
1030        assert_eq!(b.repo_id, "bound");
1031        assert_eq!(source, BindingSource::Bound);
1032
1033        // 5. user default is used when nothing more specific resolves.
1034        let (b, source) = effective_binding(ResolveInputs {
1035            repo_flag: None,
1036            session: &empty,
1037            worktree_path: None,
1038            bound: None,
1039            user_default: Some(binding("userdef")),
1040        })
1041        .unwrap();
1042        assert_eq!(b.repo_id, "userdef");
1043        assert_eq!(source, BindingSource::UserDefault);
1044
1045        // 6. nothing at all → None.
1046        let got = effective_binding(ResolveInputs {
1047            repo_flag: None,
1048            session: &empty,
1049            worktree_path: None,
1050            bound: None,
1051            user_default: None,
1052        });
1053        assert!(got.is_none());
1054    }
1055
1056    #[test]
1057    fn binding_source_display_labels() {
1058        assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
1059        assert_eq!(
1060            BindingSource::Subagent.to_string(),
1061            "subagent worktree override"
1062        );
1063        assert_eq!(
1064            BindingSource::SessionActive.to_string(),
1065            "session (repo switch)"
1066        );
1067        assert_eq!(
1068            BindingSource::Bound.to_string(),
1069            "bound .tracevault/config.toml"
1070        );
1071        assert_eq!(
1072            BindingSource::UserDefault.to_string(),
1073            "user default (repo switch --user)"
1074        );
1075    }
1076
1077    #[test]
1078    fn effective_project_precedence_local_rungs() {
1079        let pb = |n: &str| ProjectBinding {
1080            project_id: n.into(),
1081            project_name: n.into(),
1082            updated_at: "".into(),
1083            forced_until: None,
1084        };
1085        let mut subagent_projects = HashMap::new();
1086        subagent_projects.insert("/wt".into(), pb("subagent"));
1087        let session = SessionState {
1088            active_project: Some(pb("session")),
1089            subagent_projects,
1090            ..Default::default()
1091        };
1092
1093        // rung 1: flag wins over everything
1094        let got = effective_project(&ProjectResolveInputs {
1095            project_flag: Some(pb("flag")),
1096            env_project: None,
1097            session: &session,
1098            worktree_path: Some("/wt"),
1099            config_default: Some(pb("cfg")),
1100        })
1101        .unwrap();
1102        assert_eq!(got.0.project_id, "flag");
1103        assert_eq!(got.1, ProjectSource::ProjectFlag);
1104
1105        // rung 2: subagent (worktree) beats session.active
1106        let got = effective_project(&ProjectResolveInputs {
1107            project_flag: None,
1108            env_project: None,
1109            session: &session,
1110            worktree_path: Some("/wt"),
1111            config_default: Some(pb("cfg")),
1112        })
1113        .unwrap();
1114        assert_eq!(got.1, ProjectSource::Subagent);
1115        assert_eq!(got.0.project_id, "subagent");
1116
1117        // rung 3: session.active when no subagent match
1118        let got = effective_project(&ProjectResolveInputs {
1119            project_flag: None,
1120            env_project: None,
1121            session: &session,
1122            worktree_path: Some("/other"),
1123            config_default: Some(pb("cfg")),
1124        })
1125        .unwrap();
1126        assert_eq!(got.1, ProjectSource::SessionActive);
1127
1128        // rung 3b: config_default when session empty
1129        let got = effective_project(&ProjectResolveInputs {
1130            project_flag: None,
1131            env_project: None,
1132            session: &SessionState::default(),
1133            worktree_path: None,
1134            config_default: Some(pb("cfg")),
1135        })
1136        .unwrap();
1137        assert_eq!(got.1, ProjectSource::ConfigDefault);
1138
1139        // none: nothing local
1140        assert!(effective_project(&ProjectResolveInputs {
1141            project_flag: None,
1142            env_project: None,
1143            session: &SessionState::default(),
1144            worktree_path: None,
1145            config_default: None,
1146        })
1147        .is_none());
1148    }
1149
1150    /// Every tier of the capture chain, top to bottom, plus the empty case.
1151    ///
1152    /// A `.tracevault/config.toml` `default_project` cannot influence this
1153    /// chain: `CaptureProjectInputs` has no `config_default` field at all, so
1154    /// there is nothing a caller could pass (a negative compile test would
1155    /// only restate that). The struct literals below are exhaustive — adding
1156    /// such a field would break every one of them, forcing a deliberate
1157    /// decision here.
1158    #[test]
1159    fn capture_project_binding_precedence() {
1160        let pb = |n: &str| ProjectBinding {
1161            project_id: n.into(),
1162            project_name: n.into(),
1163            updated_at: "".into(),
1164            forced_until: None,
1165        };
1166        let mut subagent_projects = HashMap::new();
1167        subagent_projects.insert("/wt".into(), pb("subagent"));
1168        let session = SessionState {
1169            active_project: Some(pb("session")),
1170            subagent_projects,
1171            ..Default::default()
1172        };
1173
1174        // tier 1: flag wins over everything
1175        let got = capture_project_binding(&CaptureProjectInputs {
1176            project_flag: Some(pb("flag")),
1177            env_project: Some(pb("env")),
1178            session: &session,
1179            worktree_path: Some("/wt"),
1180            user_default: Some(pb("user")),
1181        })
1182        .unwrap();
1183        assert_eq!(
1184            (got.0.project_id.as_str(), got.1),
1185            ("flag", ProjectSource::ProjectFlag)
1186        );
1187
1188        // tier 2: subagent worktree override beats env and session active
1189        let got = capture_project_binding(&CaptureProjectInputs {
1190            project_flag: None,
1191            env_project: Some(pb("env")),
1192            session: &session,
1193            worktree_path: Some("/wt"),
1194            user_default: Some(pb("user")),
1195        })
1196        .unwrap();
1197        assert_eq!(
1198            (got.0.project_id.as_str(), got.1),
1199            ("subagent", ProjectSource::Subagent)
1200        );
1201
1202        // tier 3: TRACEVAULT_PROJECT beats session active and the user default
1203        let got = capture_project_binding(&CaptureProjectInputs {
1204            project_flag: None,
1205            env_project: Some(pb("env")),
1206            session: &session,
1207            worktree_path: Some("/other"),
1208            user_default: Some(pb("user")),
1209        })
1210        .unwrap();
1211        assert_eq!(
1212            (got.0.project_id.as_str(), got.1),
1213            ("env", ProjectSource::Env)
1214        );
1215
1216        // tier 4: session active when the worktree has no override and no env
1217        let got = capture_project_binding(&CaptureProjectInputs {
1218            project_flag: None,
1219            env_project: None,
1220            session: &session,
1221            worktree_path: Some("/other"),
1222            user_default: Some(pb("user")),
1223        })
1224        .unwrap();
1225        assert_eq!(
1226            (got.0.project_id.as_str(), got.1),
1227            ("session", ProjectSource::SessionActive)
1228        );
1229
1230        // tier 5: user default when the session has nothing
1231        let got = capture_project_binding(&CaptureProjectInputs {
1232            project_flag: None,
1233            env_project: None,
1234            session: &SessionState::default(),
1235            worktree_path: Some("/wt"),
1236            user_default: Some(pb("user")),
1237        })
1238        .unwrap();
1239        assert_eq!(
1240            (got.0.project_id.as_str(), got.1),
1241            ("user", ProjectSource::UserDefault)
1242        );
1243
1244        // none: nothing anywhere
1245        assert!(capture_project_binding(&CaptureProjectInputs {
1246            project_flag: None,
1247            env_project: None,
1248            session: &SessionState::default(),
1249            worktree_path: None,
1250            user_default: None,
1251        })
1252        .is_none());
1253    }
1254
1255    #[test]
1256    fn capture_project_id_accepts_uuid_rejects_garbage() {
1257        let pb = |id: &str| ProjectBinding {
1258            project_id: id.into(),
1259            project_name: "n".into(),
1260            updated_at: "".into(),
1261            forced_until: None,
1262        };
1263        let u = uuid::Uuid::from_u128(7);
1264        assert_eq!(capture_project_id(&pb(&u.to_string())), Some(u));
1265        assert_eq!(capture_project_id(&pb("not-a-uuid")), None);
1266        assert_eq!(capture_project_id(&pb("")), None);
1267    }
1268
1269    #[test]
1270    fn env_outranks_remembered_state_but_not_flag_or_subagent() {
1271        let pb = |n: &str| ProjectBinding {
1272            project_id: n.into(),
1273            project_name: n.into(),
1274            updated_at: "".into(),
1275            forced_until: None,
1276        };
1277        let mut subagent_projects = HashMap::new();
1278        subagent_projects.insert("/wt".to_string(), pb("subagent"));
1279        let session = SessionState {
1280            active_project: Some(pb("session")),
1281            subagent_projects,
1282            ..Default::default()
1283        };
1284
1285        // env beats session active and config default
1286        let got = effective_project(&ProjectResolveInputs {
1287            project_flag: None,
1288            env_project: Some(pb("env")),
1289            session: &session,
1290            worktree_path: None,
1291            config_default: Some(pb("config")),
1292        });
1293        assert_eq!(got.unwrap().1, ProjectSource::Env);
1294
1295        // the subagent worktree override still beats env
1296        let got = effective_project(&ProjectResolveInputs {
1297            project_flag: None,
1298            env_project: Some(pb("env")),
1299            session: &session,
1300            worktree_path: Some("/wt"),
1301            config_default: None,
1302        });
1303        assert_eq!(got.unwrap().1, ProjectSource::Subagent);
1304
1305        // --project still beats env
1306        let got = effective_project(&ProjectResolveInputs {
1307            project_flag: Some(pb("flag")),
1308            env_project: Some(pb("env")),
1309            session: &session,
1310            worktree_path: None,
1311            config_default: None,
1312        });
1313        assert_eq!(got.unwrap().1, ProjectSource::ProjectFlag);
1314    }
1315
1316    #[test]
1317    fn binding_from_config_carries_remote_id_and_codebase_name() {
1318        let uuid = uuid::Uuid::new_v4();
1319        let config = crate::config::TracevaultConfig {
1320            repo_id: Some("repo-1".into()),
1321            remote_id: Some(uuid.to_string()),
1322            codebase_name: Some("acme/foo".into()),
1323            ..Default::default()
1324        };
1325        let binding = binding_from_config(&config).expect("repo_id present");
1326        assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
1327        assert_eq!(binding.remote_id, Some(uuid));
1328    }
1329
1330    #[test]
1331    fn codebase_line_formats_name_and_status() {
1332        let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
1333        assert_eq!(line, "codebase: acme/foo (ready)");
1334        let line = codebase_line(None, "github.com/acme/foo", "pending");
1335        assert_eq!(line, "codebase: github.com/acme/foo (pending)");
1336    }
1337
1338    #[test]
1339    fn pick_status_line_detail_wins_over_resolved_and_cached() {
1340        assert_eq!(
1341            pick_status_line(
1342                Some("codebase: a (ready)".to_string()),
1343                Some("codebase: b (pending)".to_string()),
1344                Some("c"),
1345            ),
1346            Some("codebase: a (ready)".to_string())
1347        );
1348    }
1349
1350    #[test]
1351    fn pick_status_line_resolved_wins_over_cached() {
1352        assert_eq!(
1353            pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
1354            Some("codebase: b (pending)".to_string())
1355        );
1356    }
1357
1358    #[test]
1359    fn pick_status_line_cached_only_is_name_only() {
1360        assert_eq!(
1361            pick_status_line(None, None, Some("c")),
1362            Some("codebase: c".to_string())
1363        );
1364    }
1365
1366    #[test]
1367    fn pick_status_line_none_when_nothing_available() {
1368        assert_eq!(pick_status_line(None, None, None), None);
1369    }
1370
1371    #[tokio::test]
1372    async fn resolve_repo_by_name_ok_when_name_matches() {
1373        let tmp = tempfile::tempdir().unwrap();
1374        crate::test_helpers::init_git_repo(tmp.path());
1375        let repo_name = git_repo_name(tmp.path());
1376        let body =
1377            format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
1378        let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
1379        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1380
1381        let repo = resolve_repo_by_name(&client, tmp.path())
1382            .await
1383            .expect("expected a match");
1384        assert_eq!(repo.name, repo_name);
1385    }
1386
1387    #[tokio::test]
1388    async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
1389        let tmp = tempfile::tempdir().unwrap();
1390        crate::test_helpers::init_git_repo(tmp.path());
1391        let (addr, _h) = spawn_once(
1392            "200 OK",
1393            r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
1394        );
1395        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1396
1397        match resolve_repo_by_name(&client, tmp.path()).await {
1398            Err(ResolveRepoByNameError::NotFound { .. }) => {}
1399            other => panic!(
1400                "expected NotFound, got a different outcome: {}",
1401                other.is_ok()
1402            ),
1403        }
1404    }
1405
1406    #[tokio::test]
1407    async fn resolve_repo_by_name_list_failed_on_non_2xx() {
1408        // A `list_repos` failure (401/403/500/... — not necessarily a
1409        // network error, hence `ListFailed` rather than the old `Network`
1410        // name) must be distinguished from `NotFound` so callers like
1411        // `check`'s `connectivity_message` can add their own actionable
1412        // wrapping instead of a bare "not found" message.
1413        let tmp = tempfile::tempdir().unwrap();
1414        crate::test_helpers::init_git_repo(tmp.path());
1415        let (addr, _h) = spawn_once("500 Internal Server Error", "");
1416        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1417
1418        match resolve_repo_by_name(&client, tmp.path()).await {
1419            Err(ResolveRepoByNameError::ListFailed(e)) => {
1420                assert!(e.to_string().contains("500"), "got: {e}");
1421            }
1422            other => panic!(
1423                "expected ListFailed, got a different outcome: {}",
1424                other.is_ok()
1425            ),
1426        }
1427    }
1428
1429    // ── pick_listed_repo: config.toml binding before the checkout name ────────
1430
1431    fn listed(id: u128, name: &str) -> RepoListItem {
1432        RepoListItem {
1433            id: uuid::Uuid::from_u128(id),
1434            name: name.into(),
1435            github_url: None,
1436            clone_status: None,
1437        }
1438    }
1439
1440    /// A checkout bound by `init` to an existing record named differently
1441    /// (VIS-1018) still resolves, via its config.toml repo_id.
1442    #[test]
1443    fn pick_listed_repo_prefers_the_bound_id_over_the_name() {
1444        let repos = vec![listed(1, "tracing"), listed(2, "tracevault")];
1445        let got = pick_listed_repo(repos, Some(uuid::Uuid::from_u128(2)), "tracing").unwrap();
1446        assert_eq!(got.name, "tracevault");
1447    }
1448
1449    #[test]
1450    fn pick_listed_repo_falls_back_to_the_name() {
1451        let repos = vec![listed(1, "tracing"), listed(2, "tracevault")];
1452        let got = pick_listed_repo(repos, Some(uuid::Uuid::from_u128(9)), "tracing").unwrap();
1453        assert_eq!(got.name, "tracing");
1454        assert!(pick_listed_repo(vec![listed(1, "x")], None, "y").is_none());
1455    }
1456}