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::{ApiClient, RepoListItem, ResolveProjectOutcome};
11use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
12
13/// `git -C <path> remote get-url origin`, trimmed. `None` if git fails or there
14/// is no origin remote. Shared by every caller that needs a checkout's origin
15/// remote URL (`init`, `sync`, `status`, and this module's own
16/// `resolve_path_to_binding`) — there is exactly one implementation.
17pub(crate) fn git_remote_url(path: &Path) -> Option<String> {
18    let out = std::process::Command::new("git")
19        .arg("-C")
20        .arg(path)
21        .args(["remote", "get-url", "origin"])
22        .output()
23        .ok()?;
24    if !out.status.success() {
25        return None;
26    }
27    let url = String::from_utf8_lossy(&out.stdout).trim().to_string();
28    if url.is_empty() {
29        None
30    } else {
31        Some(url)
32    }
33}
34
35/// Basename of the git repository's toplevel directory — the convention used
36/// as the server-registered repo name by `verify`/`check`/`agent-policies`/
37/// `status`/`init`/`sync`. Falls back to `"unknown"` if git fails (no repo,
38/// not a git checkout, etc.), mirroring what each of those commands' own
39/// now-removed copy of this function did.
40pub(crate) fn git_repo_name(project_root: &Path) -> String {
41    Command::new("git")
42        .args(["rev-parse", "--show-toplevel"])
43        .current_dir(project_root)
44        .output()
45        .ok()
46        .filter(|o| o.status.success())
47        .and_then(|o| repo_basename(String::from_utf8_lossy(&o.stdout).trim()))
48        .unwrap_or_else(|| "unknown".into())
49}
50
51/// The basename of a `git rev-parse --show-toplevel` path. `git` always
52/// emits forward slashes (even on Windows), but `Path::file_name` is the
53/// OS-appropriate way to take the basename — it's also tolerant of a
54/// trailing separator. `None` if the path has no basename component (e.g.
55/// root `/`). Split out from [`git_repo_name`] so the basename logic is
56/// unit-testable without shelling out to git.
57fn repo_basename(toplevel: &str) -> Option<String> {
58    Path::new(toplevel)
59        .file_name()
60        .map(|n| n.to_string_lossy().into_owned())
61}
62
63/// Either half of [`resolve_repo_by_name`]'s failure: the `list_repos` call
64/// itself failed for any reason — network/transport, or any non-2xx status
65/// (401/403/404/500/...), not only a network problem — returned raw so a
66/// caller can add its own actionable wrapping (e.g. `check`'s
67/// `connectivity_message`); or the call succeeded but no repo's name matched
68/// (so callers can phrase their own "not found" message/next-step).
69#[derive(Debug)]
70pub(crate) enum ResolveRepoByNameError {
71    ListFailed(Box<dyn std::error::Error>),
72    NotFound { repo_name: String },
73}
74
75/// Resolve the server-registered repo matching `project_root`'s git-toplevel
76/// basename: derive the name via [`git_repo_name`], call `GET /repos`, and
77/// find the matching entry. Shared via the `ListFailed`/`NotFound` split so
78/// each caller can phrase its own message for either failure.
79pub(crate) async fn resolve_repo_by_name(
80    client: &ApiClient,
81    project_root: &Path,
82) -> Result<RepoListItem, ResolveRepoByNameError> {
83    let repo_name = git_repo_name(project_root);
84    let repos = client
85        .list_repos()
86        .await
87        .map_err(ResolveRepoByNameError::ListFailed)?;
88    repos
89        .into_iter()
90        .find(|r| r.name == repo_name)
91        .ok_or(ResolveRepoByNameError::NotFound { repo_name })
92}
93
94/// Render a human line for a codebase resolved via `resolve_remote` /
95/// `get_remote_detail`: the registered name if the server has one, else the
96/// normalized URL, plus the server-side clone status. Shared by `init`
97/// (after registering) and `repo status` (live tiers) so the format has
98/// exactly one implementation.
99pub(crate) fn codebase_line(
100    name: Option<&str>,
101    normalized_url: &str,
102    clone_status: &str,
103) -> String {
104    format!(
105        "codebase: {} ({})",
106        name.unwrap_or(normalized_url),
107        clone_status
108    )
109}
110
111/// Choose the `repo status` codebase line from the available sources in
112/// priority order: live remote detail, live resolve-by-URL, cached name.
113/// The two live lines are pre-formatted (via `codebase_line`, so they carry
114/// clone status); the cached tier is name-only (no live status).
115pub(crate) fn pick_status_line(
116    detail_line: Option<String>,
117    resolved_line: Option<String>,
118    cached_name: Option<&str>,
119) -> Option<String> {
120    detail_line
121        .or(resolved_line)
122        .or_else(|| cached_name.map(|n| format!("codebase: {n}")))
123}
124
125/// Resolve a filesystem path to a registered-repo binding: read its origin
126/// remote URL and ask the server. `Ok(None)` when the path has no remote or
127/// the server has no matching codebase (pre-registered-only).
128pub async fn resolve_path_to_binding(
129    path: &Path,
130    client: &ApiClient,
131) -> Result<Option<RepoBinding>, Box<dyn std::error::Error>> {
132    let Some(git_url) = git_remote_url(path) else {
133        return Ok(None);
134    };
135    // Resolve the CODEBASE by normalized URL (deduped), then bind to one of its
136    // repos. Any linked repo works for ingest — every repo-keyed server read
137    // resolves codebase-wide — so the lowest-id linked repo (deterministic) is
138    // fine.
139    let Some(remote) = client.resolve_remote(&git_url).await? else {
140        return Ok(None);
141    };
142    let repos = client.get_remote_repos(remote.remote_id).await?;
143    let Some(first) = repos.into_iter().min_by_key(|r| r.id) else {
144        return Err(format!(
145            "codebase {} is registered but has no tracked repo; run `tracevault init` in a checkout",
146            remote.name.as_deref().unwrap_or(&remote.normalized_url)
147        )
148        .into());
149    };
150    Ok(Some(RepoBinding {
151        repo_id: first.id.to_string(),
152        git_url: Some(git_url),
153        remote_id: Some(remote.remote_id),
154        codebase_name: remote.name,
155        updated_at: chrono::Utc::now().to_rfc3339(),
156    }))
157}
158
159/// Inputs for the effective-binding precedence chain. `repo_flag` and `bound`
160/// are resolved by the caller (the `--path` override and the bound
161/// `config.toml`, respectively); `session`/`worktree_path` come from the
162/// per-session state.
163pub struct ResolveInputs<'a> {
164    pub repo_flag: Option<RepoBinding>,
165    pub session: &'a SessionState,
166    pub worktree_path: Option<&'a str>,
167    pub bound: Option<RepoBinding>,
168    /// Lowest-precedence, session-independent default (from `repo switch --user`
169    /// / a no-session switch). Applies when nothing more specific resolves.
170    pub user_default: Option<RepoBinding>,
171}
172
173/// Inputs for the effective-project precedence chain. `project_flag` and
174/// `config_default` are resolved by the caller; `session`/`worktree_path`
175/// come from the per-session state.
176pub struct ProjectResolveInputs<'a> {
177    pub project_flag: Option<ProjectBinding>,
178    /// Parsed from `TRACEVAULT_PROJECT` by the caller, so this module stays
179    /// free of environment reads and remains a pure function of its inputs.
180    pub env_project: Option<ProjectBinding>,
181    pub session: &'a SessionState,
182    pub worktree_path: Option<&'a str>,
183    pub config_default: Option<ProjectBinding>,
184}
185
186/// Which precedence tier produced the [`effective_binding`] result.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum BindingSource {
189    /// A `--path <path>` flag override (on `repo status`).
190    RepoFlag,
191    /// A subagent's per-worktree override.
192    Subagent,
193    /// The session's session-level active binding.
194    SessionActive,
195    /// A pinned `.tracevault/config.toml` (bound mode).
196    Bound,
197    /// A session-independent user-level default (`repo switch --user`).
198    UserDefault,
199}
200
201impl std::fmt::Display for BindingSource {
202    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
203        let label = match self {
204            BindingSource::RepoFlag => "--path override",
205            BindingSource::Subagent => "subagent worktree override",
206            BindingSource::SessionActive => "session (repo switch)",
207            BindingSource::Bound => "bound .tracevault/config.toml",
208            BindingSource::UserDefault => "user default (repo switch --user)",
209        };
210        f.write_str(label)
211    }
212}
213
214/// Which precedence tier produced the [`effective_project`] result.
215#[derive(Debug, Clone, Copy, PartialEq, Eq)]
216pub enum ProjectSource {
217    /// A `--project <id>` flag override.
218    ProjectFlag,
219    /// A subagent's per-worktree override.
220    Subagent,
221    /// The `TRACEVAULT_PROJECT` environment variable — a per-process
222    /// assertion, re-asserted at every launch and never written to disk.
223    /// Outranks every remembered tier so a stale `user_project.toml` or a
224    /// `.tracevault/config.toml` baked into a pod image cannot outrank the
225    /// launcher that started the process.
226    Env,
227    /// The session's project-level active binding.
228    SessionActive,
229    /// A pinned `.tracevault/config.toml` default_project (bound mode).
230    ConfigDefault,
231    /// Repo deduction from the git remote, resolved server-side. Produced
232    /// only by the display chain [`resolve_effective_project`], never by the
233    /// capture chain [`capture_project_binding`].
234    Deduced,
235    /// A session-independent user-level default (`project switch --user`).
236    /// Produced by [`capture_project_binding`] and
237    /// [`resolve_effective_project`], not [`effective_project`].
238    UserDefault,
239}
240
241impl std::fmt::Display for ProjectSource {
242    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
243        let label = match self {
244            ProjectSource::ProjectFlag => "--project override",
245            ProjectSource::Subagent => "subagent worktree override",
246            ProjectSource::Env => "TRACEVAULT_PROJECT (environment)",
247            ProjectSource::SessionActive => "session (project switch)",
248            ProjectSource::ConfigDefault => "bound .tracevault/config.toml default_project",
249            ProjectSource::Deduced => "repo deduction",
250            ProjectSource::UserDefault => "user default (project switch --user)",
251        };
252        f.write_str(label)
253    }
254}
255
256/// The binding that applies, and which tier produced it: `--path` flag →
257/// subagent worktree override → session active → bound config → user
258/// default → none.
259pub fn effective_binding(inputs: ResolveInputs) -> Option<(RepoBinding, BindingSource)> {
260    if let Some(b) = inputs.repo_flag {
261        return Some((b, BindingSource::RepoFlag));
262    }
263    if let Some(wt) = inputs.worktree_path {
264        if let Some(b) = inputs.session.subagents.get(wt) {
265            return Some((b.clone(), BindingSource::Subagent));
266        }
267    }
268    if let Some(b) = &inputs.session.active {
269        return Some((b.clone(), BindingSource::SessionActive));
270    }
271    if let Some(b) = inputs.bound {
272        return Some((b, BindingSource::Bound));
273    }
274    inputs.user_default.map(|b| (b, BindingSource::UserDefault))
275}
276
277/// The project that applies, and which tier produced it: `--project` flag →
278/// subagent worktree override → `TRACEVAULT_PROJECT` → session active →
279/// config default → none.
280/// Pure; covers only the local tiers (flag → subagent → env_project →
281/// session.active_project → config_default). `env_project` is supplied BY THE
282/// CALLER — this module never reads the environment — and the capture path
283/// fills it from `commands::stream::env_project_binding`, which honours the
284/// UUID form only. The user-level default (and, in the display chain only,
285/// server-side deduction) are applied afterward by [`capture_project_binding`]
286/// / [`resolve_effective_project`], which call this function first and only
287/// fall through to those tiers when it returns `None`.
288pub fn effective_project(inputs: &ProjectResolveInputs) -> Option<(ProjectBinding, ProjectSource)> {
289    if let Some(b) = &inputs.project_flag {
290        return Some((b.clone(), ProjectSource::ProjectFlag));
291    }
292    if let Some(wt) = inputs.worktree_path {
293        if let Some(b) = inputs.session.subagent_projects.get(wt) {
294            return Some((b.clone(), ProjectSource::Subagent));
295        }
296    }
297    if let Some(b) = &inputs.env_project {
298        return Some((b.clone(), ProjectSource::Env));
299    }
300    if let Some(b) = &inputs.session.active_project {
301        return Some((b.clone(), ProjectSource::SessionActive));
302    }
303    inputs
304        .config_default
305        .clone()
306        .map(|b| (b, ProjectSource::ConfigDefault))
307}
308
309/// Inputs to the capture-time project chain. Deliberately has NO
310/// `config_default` field: `.tracevault/config.toml` `default_project` is a
311/// NAME, resolving it needs a network call, and the stream hook (which fires
312/// per event) never does one — so no caller of this chain can feed it in.
313pub struct CaptureProjectInputs<'a> {
314    /// `--project` override (only `project status` supplies it; the hook passes `None`).
315    pub project_flag: Option<ProjectBinding>,
316    /// `TRACEVAULT_PROJECT`, UUID form ONLY — parsed by the caller (via
317    /// `commands::stream::env_project_binding`) so this module stays free of
318    /// environment reads. The NAME form is deliberately not a tier here: it
319    /// would need a `list_projects` round trip, and this is the network-free
320    /// chain the per-event hook runs. Both callers fill this field from that
321    /// same reader, so `project status` cannot report a tier ingest ignores.
322    pub env_project: Option<ProjectBinding>,
323    pub session: &'a SessionState,
324    pub worktree_path: Option<&'a str>,
325    /// `user_project_default::load()` — passed in so the function stays pure.
326    pub user_default: Option<ProjectBinding>,
327}
328
329/// THE capture-time project chain: `--project` flag → subagent worktree
330/// override → `TRACEVAULT_PROJECT` → session `active_project` → user default
331/// → none. Pure, no network. `commands::stream::capture_project` (ingest) and
332/// `commands::project::status` both call this, so they cannot drift.
333pub fn capture_project_binding(
334    inputs: &CaptureProjectInputs<'_>,
335) -> Option<(ProjectBinding, ProjectSource)> {
336    effective_project(&ProjectResolveInputs {
337        project_flag: inputs.project_flag.clone(),
338        env_project: inputs.env_project.clone(),
339        session: inputs.session,
340        worktree_path: inputs.worktree_path,
341        config_default: None,
342    })
343    .or_else(|| {
344        inputs
345            .user_default
346            .clone()
347            .map(|b| (b, ProjectSource::UserDefault))
348    })
349}
350
351/// The id the hook will actually send for a capture binding: `None` when the
352/// stored `project_id` is not a UUID (a hand-edited or corrupted
353/// `user_project.toml`/session file), in which case ingest treats the binding
354/// as absent and the event goes repo-scoped.
355pub fn capture_project_id(binding: &ProjectBinding) -> Option<uuid::Uuid> {
356    binding.project_id.parse::<uuid::Uuid>().ok()
357}
358
359/// DISPLAY chain for `commands::status`'s "Project" line: `--project` flag →
360/// subagent override → `TRACEVAULT_PROJECT` → session active → config default
361/// (all pure, via [`effective_project`]; no network call) → user-level default
362/// → server-side deduction from the repo's git remote.
363///
364/// The user-level default outranks deduction because that is what ingest
365/// does: the capture chain ([`capture_project_binding`]) applies the user
366/// default and never deduces, so a display chain that ranked deduction above
367/// it would name a project no event is attributed to — exactly in the
368/// orchestrator's configuration (a pod bound via `project switch --user`). The
369/// server is only asked once every local tier, user default included, is empty.
370///
371/// An `Ambiguous` deduction result is an error (the caller can't safely guess
372/// among several candidate projects). This resolver never prints: callers
373/// render the tier via [`ProjectSource`]'s `Display`. Returns `Ok(None)` only
374/// when every tier in the chain is empty. `commands::project::status` does not
375/// use this chain: it reports [`capture_project_binding`] and shows deduction
376/// on a separate line.
377pub async fn resolve_effective_project(
378    inputs: &ProjectResolveInputs<'_>,
379    user_default: Option<ProjectBinding>,
380    git_url: Option<&str>,
381    client: &ApiClient,
382) -> Result<Option<(ProjectBinding, ProjectSource)>, Box<dyn std::error::Error>> {
383    // Local tiers: flag → subagent → TRACEVAULT_PROJECT → session active →
384    // config default.
385    if let Some(hit) = effective_project(inputs) {
386        return Ok(Some(hit));
387    }
388    // User-level default: ingest honours it, so it outranks deduction.
389    if let Some(b) = user_default {
390        return Ok(Some((b, ProjectSource::UserDefault)));
391    }
392    // Server-side deduction from the repo's git remote (lowest tier).
393    if let Some(url) = git_url {
394        match client.resolve_project(url).await? {
395            ResolveProjectOutcome::Resolved(pid) => {
396                return Ok(Some((
397                    ProjectBinding {
398                        project_id: pid.to_string(),
399                        project_name: String::new(), // enriched for display by the caller if needed
400                        updated_at: String::new(),
401                        forced_until: None,
402                    },
403                    ProjectSource::Deduced,
404                )));
405            }
406            ResolveProjectOutcome::Ambiguous => {
407                return Err(
408                    "this repo belongs to multiple projects; select one with `tracevault project switch <name>` or the `--project` override"
409                        .to_string()
410                        .into(),
411                );
412            }
413            ResolveProjectOutcome::None => { /* fall through */ }
414        }
415    }
416    Ok(None)
417}
418
419/// The repo binding a recorded session's events were streamed under, resolved
420/// exactly as the stream hook resolves it — so `check` and `verify-start` work
421/// under the same repo id the session's events went to (VIS-601).
422///
423/// The whole chain runs off `session_dir`, like `flush`'s
424/// `queue_capture_binding`: the session id is its file name (the caller loads
425/// `state` from it), and the subagent worktree override is keyed by the
426/// worktree toplevel the hook recorded in its `origin` marker. `bound` and
427/// `user_default` are the lower tiers the hook also consults.
428///
429/// A binding whose `repo_id` is not a UUID resolves to `None`, as it does for
430/// the hook (`stream::attribution_for` never sends to it).
431pub(crate) fn recorded_session_binding(
432    session_dir: &Path,
433    state: &SessionState,
434    bound: Option<RepoBinding>,
435    user_default: Option<RepoBinding>,
436) -> Option<RepoBinding> {
437    let worktree = std::fs::read_to_string(session_dir.join("origin"))
438        .ok()
439        .map(|s| s.trim().to_string());
440    effective_binding(ResolveInputs {
441        repo_flag: None,
442        session: state,
443        worktree_path: worktree.as_deref(),
444        bound,
445        user_default,
446    })
447    .map(|(b, _)| b)
448    .filter(|b| crate::commands::stream::binding_repo_id_is_valid(&b.repo_id))
449}
450
451/// A RepoBinding from a pinned `.tracevault/config.toml` (bound mode), if it has
452/// a repo_id. Pure — caller supplies the already-loaded config.
453/// Carries through the `remote_id`/`codebase_name` `init` persisted (best-effort,
454/// display-only) so bound-mode `status` can print the codebase without an extra
455/// network round-trip; `git_url` stays `None` here — bound mode has no live
456/// origin URL to hand back (that's the older `git_url` fallback's job, covering
457/// bindings that predate `codebase_name`).
458pub fn binding_from_config(config: &crate::config::TracevaultConfig) -> Option<RepoBinding> {
459    Some(RepoBinding {
460        repo_id: config.repo_id.clone()?,
461        git_url: None,
462        remote_id: config.remote_id.as_deref().and_then(|s| s.parse().ok()),
463        codebase_name: config.codebase_name.clone(),
464        updated_at: String::new(),
465    })
466}
467
468#[cfg(test)]
469mod tests {
470    use super::*;
471    use crate::session_state::{ProjectBinding, RepoBinding, SessionState};
472    use std::collections::HashMap;
473    use std::io::{BufRead, BufReader, Write};
474    use std::net::{SocketAddr, TcpListener};
475    use std::thread;
476
477    #[test]
478    fn repo_basename_bare_name() {
479        assert_eq!(repo_basename("myrepo"), Some("myrepo".to_string()));
480    }
481
482    #[test]
483    fn repo_basename_nested_path() {
484        assert_eq!(
485            repo_basename("/home/user/code/myrepo"),
486            Some("myrepo".to_string())
487        );
488    }
489
490    #[test]
491    fn repo_basename_trailing_slash() {
492        // `Path::file_name` skips a trailing separator rather than treating
493        // it as an empty final component.
494        assert_eq!(
495            repo_basename("/home/user/code/myrepo/"),
496            Some("myrepo".to_string())
497        );
498    }
499
500    #[test]
501    fn repo_basename_dot_git_suffix_directory() {
502        // A checkout directory literally named `myrepo.git` (e.g. a bare
503        // clone) keeps the suffix — `git_repo_name` takes the raw basename,
504        // it does not strip `.git`.
505        assert_eq!(
506            repo_basename("/srv/repos/myrepo.git"),
507            Some("myrepo.git".to_string())
508        );
509    }
510
511    #[test]
512    fn repo_basename_root_has_no_basename() {
513        assert_eq!(repo_basename("/"), None);
514    }
515
516    /// Spawn a one-shot raw-HTTP server that returns a response built from
517    /// `status` (e.g. `"200 OK"`) and `body` to the first request it accepts.
518    /// Mirrors the `spawn_once`/`http_200` shape in `commands::repo`'s test
519    /// module (bind loopback, accept once on a background thread, write the
520    /// raw HTTP response, flush, close).
521    fn spawn_once(
522        status: &'static str,
523        body: &'static str,
524    ) -> (SocketAddr, thread::JoinHandle<()>) {
525        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
526        let addr = listener.local_addr().unwrap();
527        let response = http_200(status, body);
528        let handle = thread::spawn(move || {
529            if let Ok((stream, _)) = listener.accept() {
530                let mut reader = BufReader::new(stream);
531                let mut request_line = String::new();
532                let _ = reader.read_line(&mut request_line);
533                let mut stream = reader.into_inner();
534                let _ = stream.write_all(response.as_bytes());
535                let _ = stream.flush();
536            }
537        });
538        (addr, handle)
539    }
540
541    /// Format a raw HTTP/1.1 response with the given `status` line and a
542    /// correct `Content-Length` for a JSON `body`.
543    fn http_200(status: &str, body: &str) -> String {
544        format!(
545            "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
546            status,
547            body.len(),
548            body
549        )
550    }
551
552    #[tokio::test]
553    async fn user_default_beats_deduction() {
554        // Ingest applies the user default and never deduces, so the display
555        // chain must too: with a user default present, NO server request may
556        // be made. The client points at port 0 (nothing listens there), so a
557        // deduction attempt would surface as an Err rather than Ok(UserDefault).
558        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
559        let ud = ProjectBinding {
560            project_id: "user".into(),
561            project_name: "u".into(),
562            updated_at: "".into(),
563            forced_until: None,
564        };
565        let inputs = ProjectResolveInputs {
566            project_flag: None,
567            env_project: None,
568            session: &SessionState::default(),
569            worktree_path: None,
570            config_default: None,
571        };
572        let (b, src) = resolve_effective_project(&inputs, Some(ud), Some("git@x:y.git"), &client)
573            .await
574            .expect("a user default must resolve without any network call")
575            .unwrap();
576        assert_eq!(src, ProjectSource::UserDefault);
577        assert_eq!(b.project_id, "user");
578    }
579
580    #[tokio::test]
581    async fn deduction_used_when_no_local_tier_or_user_default() {
582        let (addr, _h) = spawn_once(
583            "200 OK",
584            "{\"project_id\":\"22222222-2222-2222-2222-222222222222\"}",
585        );
586        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
587        let inputs = ProjectResolveInputs {
588            project_flag: None,
589            env_project: None,
590            session: &SessionState::default(),
591            worktree_path: None,
592            config_default: None,
593        };
594        let (b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
595            .await
596            .unwrap()
597            .unwrap();
598        assert_eq!(src, ProjectSource::Deduced);
599        assert_eq!(b.project_id, "22222222-2222-2222-2222-222222222222");
600    }
601
602    #[tokio::test]
603    async fn ambiguous_deduction_errors_when_no_higher_rung() {
604        let (addr, _h) = spawn_once("409 Conflict", "{\"error\":\"multiple\"}");
605        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
606        let inputs = ProjectResolveInputs {
607            project_flag: None,
608            env_project: None,
609            session: &SessionState::default(),
610            worktree_path: None,
611            config_default: None,
612        };
613        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
614            .await
615            .unwrap_err();
616        assert!(err.to_string().to_lowercase().contains("--project"));
617    }
618
619    #[tokio::test]
620    async fn domain_404_deduction_resolves_to_none() {
621        // A domain 404 (server's `{"error": ...}` envelope) — the shape a
622        // real (non-skewed) server sends for "no project" — falls through to
623        // `Ok(None)`, unlike a bare route-404. The user default is `None`
624        // here: a present user default now short-circuits before the
625        // deduction call (see `user_default_beats_deduction`).
626        let (addr, _h) = spawn_once("404 Not Found", "{\"error\":\"no project\"}");
627        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
628        let inputs = ProjectResolveInputs {
629            project_flag: None,
630            env_project: None,
631            session: &SessionState::default(),
632            worktree_path: None,
633            config_default: None,
634        };
635        let got = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
636            .await
637            .unwrap();
638        assert!(got.is_none(), "got: {got:?}");
639    }
640
641    #[tokio::test]
642    async fn deduction_bare_404_is_version_skew_err_not_fallthrough() {
643        // A bare 404 (no JSON error body) is axum's "no route matched"
644        // fallback, not a domain "no project" — it must propagate as an
645        // error instead of silently falling through to `Ok(None)`. No user
646        // default: one would short-circuit before the deduction call.
647        let (addr, _h) = spawn_once("404 Not Found", "");
648        let client = ApiClient::new(&format!("http://{addr}"), Some("k"));
649        let inputs = ProjectResolveInputs {
650            project_flag: None,
651            env_project: None,
652            session: &SessionState::default(),
653            worktree_path: None,
654            config_default: None,
655        };
656        let err = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
657            .await
658            .expect_err("a bare 404 must not silently fall through to Ok(None)");
659        assert!(err.to_string().to_lowercase().contains("version mismatch"));
660    }
661
662    #[tokio::test]
663    async fn local_rung_skips_server_call() {
664        // no server spawned; a config_default present must resolve WITHOUT any network call
665        let client = ApiClient::new("http://127.0.0.1:0", Some("k"));
666        let cfg = ProjectBinding {
667            project_id: "cfg".into(),
668            project_name: "c".into(),
669            updated_at: "".into(),
670            forced_until: None,
671        };
672        let inputs = ProjectResolveInputs {
673            project_flag: None,
674            env_project: None,
675            session: &SessionState::default(),
676            worktree_path: None,
677            config_default: Some(cfg),
678        };
679        let (_b, src) = resolve_effective_project(&inputs, None, Some("git@x:y.git"), &client)
680            .await
681            .unwrap()
682            .unwrap();
683        assert_eq!(src, ProjectSource::ConfigDefault);
684    }
685
686    fn binding(id: &str) -> RepoBinding {
687        RepoBinding {
688            repo_id: id.into(),
689            git_url: None,
690            remote_id: None,
691            codebase_name: None,
692            updated_at: "t".into(),
693        }
694    }
695
696    const REPO_A: &str = "11111111-1111-1111-1111-111111111111";
697    const REPO_B: &str = "22222222-2222-2222-2222-222222222222";
698    const REPO_C: &str = "33333333-3333-3333-3333-333333333333";
699
700    fn session_dir_with_origin(origin: Option<&str>) -> tempfile::TempDir {
701        let dir = tempfile::tempdir().unwrap();
702        if let Some(o) = origin {
703            std::fs::write(dir.path().join("origin"), o).unwrap();
704        }
705        dir
706    }
707
708    #[test]
709    fn recorded_session_binding_prefers_repo_switch_over_config() {
710        let dir = session_dir_with_origin(Some("/wt/a"));
711        let state = SessionState {
712            active: Some(binding(REPO_A)),
713            ..Default::default()
714        };
715        let got =
716            recorded_session_binding(dir.path(), &state, Some(binding(REPO_B)), None).unwrap();
717        assert_eq!(got.repo_id, REPO_A);
718    }
719
720    #[test]
721    fn recorded_session_binding_honours_subagent_override_via_origin_marker() {
722        // The hook writes no trailing newline today; a hand-edited marker with
723        // one must still key the override.
724        let dir = session_dir_with_origin(Some("/wt/sub\n"));
725        let mut state = SessionState {
726            active: Some(binding(REPO_A)),
727            ..Default::default()
728        };
729        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
730        let got = recorded_session_binding(dir.path(), &state, None, None).unwrap();
731        assert_eq!(got.repo_id, REPO_C);
732    }
733
734    #[test]
735    fn recorded_session_binding_unbound_falls_to_config_then_user_default() {
736        let dir = session_dir_with_origin(None);
737        let state = SessionState::default();
738        let got = recorded_session_binding(
739            dir.path(),
740            &state,
741            Some(binding(REPO_B)),
742            Some(binding(REPO_C)),
743        )
744        .unwrap();
745        assert_eq!(got.repo_id, REPO_B);
746        let got =
747            recorded_session_binding(dir.path(), &state, None, Some(binding(REPO_C))).unwrap();
748        assert_eq!(got.repo_id, REPO_C);
749        assert!(recorded_session_binding(dir.path(), &state, None, None).is_none());
750    }
751
752    #[test]
753    fn recorded_session_binding_rejects_non_uuid_repo_id() {
754        let dir = session_dir_with_origin(Some("/wt/a"));
755        let state = SessionState {
756            active: Some(binding("../escape")),
757            ..Default::default()
758        };
759        assert!(recorded_session_binding(dir.path(), &state, None, None).is_none());
760    }
761
762    /// The same session must resolve to the same repo on the hook side and on
763    /// the `check`/`verify-start` side — the whole point of VIS-601.
764    #[test]
765    fn recorded_session_binding_agrees_with_stream_hook() {
766        let mut state = SessionState {
767            active: Some(binding(REPO_A)),
768            ..Default::default()
769        };
770        state.subagents.insert("/wt/sub".into(), binding(REPO_C));
771        for wt in ["/wt/main", "/wt/sub"] {
772            let dir = session_dir_with_origin(Some(wt));
773            let hook = crate::commands::stream::resolve_stream_binding(
774                &state,
775                wt,
776                Some(binding(REPO_B)),
777                None,
778            );
779            let recorded =
780                recorded_session_binding(dir.path(), &state, Some(binding(REPO_B)), None);
781            assert_eq!(
782                hook.map(|b| b.repo_id),
783                recorded.map(|b| b.repo_id),
784                "worktree {wt}"
785            );
786        }
787    }
788
789    #[test]
790    fn effective_binding_precedence() {
791        let session = SessionState {
792            active: Some(binding("session")),
793            subagents: HashMap::from([("/wt/a".to_string(), binding("subagent"))]),
794            ..Default::default()
795        };
796
797        // 1. repo_flag wins over everything.
798        let (b, source) = effective_binding(ResolveInputs {
799            repo_flag: Some(binding("flag")),
800            session: &session,
801            worktree_path: Some("/wt/a"),
802            bound: Some(binding("bound")),
803            user_default: Some(binding("userdef")),
804        })
805        .unwrap();
806        assert_eq!(b.repo_id, "flag");
807        assert_eq!(source, BindingSource::RepoFlag);
808
809        // 2. subagent override wins over session active + bound + user default.
810        let (b, source) = effective_binding(ResolveInputs {
811            repo_flag: None,
812            session: &session,
813            worktree_path: Some("/wt/a"),
814            bound: Some(binding("bound")),
815            user_default: Some(binding("userdef")),
816        })
817        .unwrap();
818        assert_eq!(b.repo_id, "subagent");
819        assert_eq!(source, BindingSource::Subagent);
820
821        // 3. session active wins over bound + user default.
822        let (b, source) = effective_binding(ResolveInputs {
823            repo_flag: None,
824            session: &session,
825            worktree_path: Some("/wt/other"),
826            bound: Some(binding("bound")),
827            user_default: Some(binding("userdef")),
828        })
829        .unwrap();
830        assert_eq!(b.repo_id, "session");
831        assert_eq!(source, BindingSource::SessionActive);
832
833        // 4. bound wins over user default.
834        let empty = SessionState::default();
835        let (b, source) = effective_binding(ResolveInputs {
836            repo_flag: None,
837            session: &empty,
838            worktree_path: None,
839            bound: Some(binding("bound")),
840            user_default: Some(binding("userdef")),
841        })
842        .unwrap();
843        assert_eq!(b.repo_id, "bound");
844        assert_eq!(source, BindingSource::Bound);
845
846        // 5. user default is used when nothing more specific resolves.
847        let (b, source) = effective_binding(ResolveInputs {
848            repo_flag: None,
849            session: &empty,
850            worktree_path: None,
851            bound: None,
852            user_default: Some(binding("userdef")),
853        })
854        .unwrap();
855        assert_eq!(b.repo_id, "userdef");
856        assert_eq!(source, BindingSource::UserDefault);
857
858        // 6. nothing at all → None.
859        let got = effective_binding(ResolveInputs {
860            repo_flag: None,
861            session: &empty,
862            worktree_path: None,
863            bound: None,
864            user_default: None,
865        });
866        assert!(got.is_none());
867    }
868
869    #[test]
870    fn binding_source_display_labels() {
871        assert_eq!(BindingSource::RepoFlag.to_string(), "--path override");
872        assert_eq!(
873            BindingSource::Subagent.to_string(),
874            "subagent worktree override"
875        );
876        assert_eq!(
877            BindingSource::SessionActive.to_string(),
878            "session (repo switch)"
879        );
880        assert_eq!(
881            BindingSource::Bound.to_string(),
882            "bound .tracevault/config.toml"
883        );
884        assert_eq!(
885            BindingSource::UserDefault.to_string(),
886            "user default (repo switch --user)"
887        );
888    }
889
890    #[test]
891    fn effective_project_precedence_local_rungs() {
892        let pb = |n: &str| ProjectBinding {
893            project_id: n.into(),
894            project_name: n.into(),
895            updated_at: "".into(),
896            forced_until: None,
897        };
898        let mut subagent_projects = HashMap::new();
899        subagent_projects.insert("/wt".into(), pb("subagent"));
900        let session = SessionState {
901            active_project: Some(pb("session")),
902            subagent_projects,
903            ..Default::default()
904        };
905
906        // rung 1: flag wins over everything
907        let got = effective_project(&ProjectResolveInputs {
908            project_flag: Some(pb("flag")),
909            env_project: None,
910            session: &session,
911            worktree_path: Some("/wt"),
912            config_default: Some(pb("cfg")),
913        })
914        .unwrap();
915        assert_eq!(got.0.project_id, "flag");
916        assert_eq!(got.1, ProjectSource::ProjectFlag);
917
918        // rung 2: subagent (worktree) beats session.active
919        let got = effective_project(&ProjectResolveInputs {
920            project_flag: None,
921            env_project: None,
922            session: &session,
923            worktree_path: Some("/wt"),
924            config_default: Some(pb("cfg")),
925        })
926        .unwrap();
927        assert_eq!(got.1, ProjectSource::Subagent);
928        assert_eq!(got.0.project_id, "subagent");
929
930        // rung 3: session.active when no subagent match
931        let got = effective_project(&ProjectResolveInputs {
932            project_flag: None,
933            env_project: None,
934            session: &session,
935            worktree_path: Some("/other"),
936            config_default: Some(pb("cfg")),
937        })
938        .unwrap();
939        assert_eq!(got.1, ProjectSource::SessionActive);
940
941        // rung 3b: config_default when session empty
942        let got = effective_project(&ProjectResolveInputs {
943            project_flag: None,
944            env_project: None,
945            session: &SessionState::default(),
946            worktree_path: None,
947            config_default: Some(pb("cfg")),
948        })
949        .unwrap();
950        assert_eq!(got.1, ProjectSource::ConfigDefault);
951
952        // none: nothing local
953        assert!(effective_project(&ProjectResolveInputs {
954            project_flag: None,
955            env_project: None,
956            session: &SessionState::default(),
957            worktree_path: None,
958            config_default: None,
959        })
960        .is_none());
961    }
962
963    /// Every tier of the capture chain, top to bottom, plus the empty case.
964    ///
965    /// A `.tracevault/config.toml` `default_project` cannot influence this
966    /// chain: `CaptureProjectInputs` has no `config_default` field at all, so
967    /// there is nothing a caller could pass (a negative compile test would
968    /// only restate that). The struct literals below are exhaustive — adding
969    /// such a field would break every one of them, forcing a deliberate
970    /// decision here.
971    #[test]
972    fn capture_project_binding_precedence() {
973        let pb = |n: &str| ProjectBinding {
974            project_id: n.into(),
975            project_name: n.into(),
976            updated_at: "".into(),
977            forced_until: None,
978        };
979        let mut subagent_projects = HashMap::new();
980        subagent_projects.insert("/wt".into(), pb("subagent"));
981        let session = SessionState {
982            active_project: Some(pb("session")),
983            subagent_projects,
984            ..Default::default()
985        };
986
987        // tier 1: flag wins over everything
988        let got = capture_project_binding(&CaptureProjectInputs {
989            project_flag: Some(pb("flag")),
990            env_project: Some(pb("env")),
991            session: &session,
992            worktree_path: Some("/wt"),
993            user_default: Some(pb("user")),
994        })
995        .unwrap();
996        assert_eq!(
997            (got.0.project_id.as_str(), got.1),
998            ("flag", ProjectSource::ProjectFlag)
999        );
1000
1001        // tier 2: subagent worktree override beats env and session active
1002        let got = capture_project_binding(&CaptureProjectInputs {
1003            project_flag: None,
1004            env_project: Some(pb("env")),
1005            session: &session,
1006            worktree_path: Some("/wt"),
1007            user_default: Some(pb("user")),
1008        })
1009        .unwrap();
1010        assert_eq!(
1011            (got.0.project_id.as_str(), got.1),
1012            ("subagent", ProjectSource::Subagent)
1013        );
1014
1015        // tier 3: TRACEVAULT_PROJECT beats session active and the user default
1016        let got = capture_project_binding(&CaptureProjectInputs {
1017            project_flag: None,
1018            env_project: Some(pb("env")),
1019            session: &session,
1020            worktree_path: Some("/other"),
1021            user_default: Some(pb("user")),
1022        })
1023        .unwrap();
1024        assert_eq!(
1025            (got.0.project_id.as_str(), got.1),
1026            ("env", ProjectSource::Env)
1027        );
1028
1029        // tier 4: session active when the worktree has no override and no env
1030        let got = capture_project_binding(&CaptureProjectInputs {
1031            project_flag: None,
1032            env_project: None,
1033            session: &session,
1034            worktree_path: Some("/other"),
1035            user_default: Some(pb("user")),
1036        })
1037        .unwrap();
1038        assert_eq!(
1039            (got.0.project_id.as_str(), got.1),
1040            ("session", ProjectSource::SessionActive)
1041        );
1042
1043        // tier 5: user default when the session has nothing
1044        let got = capture_project_binding(&CaptureProjectInputs {
1045            project_flag: None,
1046            env_project: None,
1047            session: &SessionState::default(),
1048            worktree_path: Some("/wt"),
1049            user_default: Some(pb("user")),
1050        })
1051        .unwrap();
1052        assert_eq!(
1053            (got.0.project_id.as_str(), got.1),
1054            ("user", ProjectSource::UserDefault)
1055        );
1056
1057        // none: nothing anywhere
1058        assert!(capture_project_binding(&CaptureProjectInputs {
1059            project_flag: None,
1060            env_project: None,
1061            session: &SessionState::default(),
1062            worktree_path: None,
1063            user_default: None,
1064        })
1065        .is_none());
1066    }
1067
1068    #[test]
1069    fn capture_project_id_accepts_uuid_rejects_garbage() {
1070        let pb = |id: &str| ProjectBinding {
1071            project_id: id.into(),
1072            project_name: "n".into(),
1073            updated_at: "".into(),
1074            forced_until: None,
1075        };
1076        let u = uuid::Uuid::from_u128(7);
1077        assert_eq!(capture_project_id(&pb(&u.to_string())), Some(u));
1078        assert_eq!(capture_project_id(&pb("not-a-uuid")), None);
1079        assert_eq!(capture_project_id(&pb("")), None);
1080    }
1081
1082    #[test]
1083    fn env_outranks_remembered_state_but_not_flag_or_subagent() {
1084        let pb = |n: &str| ProjectBinding {
1085            project_id: n.into(),
1086            project_name: n.into(),
1087            updated_at: "".into(),
1088            forced_until: None,
1089        };
1090        let mut subagent_projects = HashMap::new();
1091        subagent_projects.insert("/wt".to_string(), pb("subagent"));
1092        let session = SessionState {
1093            active_project: Some(pb("session")),
1094            subagent_projects,
1095            ..Default::default()
1096        };
1097
1098        // env beats session active and config default
1099        let got = effective_project(&ProjectResolveInputs {
1100            project_flag: None,
1101            env_project: Some(pb("env")),
1102            session: &session,
1103            worktree_path: None,
1104            config_default: Some(pb("config")),
1105        });
1106        assert_eq!(got.unwrap().1, ProjectSource::Env);
1107
1108        // the subagent worktree override still beats env
1109        let got = effective_project(&ProjectResolveInputs {
1110            project_flag: None,
1111            env_project: Some(pb("env")),
1112            session: &session,
1113            worktree_path: Some("/wt"),
1114            config_default: None,
1115        });
1116        assert_eq!(got.unwrap().1, ProjectSource::Subagent);
1117
1118        // --project still beats env
1119        let got = effective_project(&ProjectResolveInputs {
1120            project_flag: Some(pb("flag")),
1121            env_project: Some(pb("env")),
1122            session: &session,
1123            worktree_path: None,
1124            config_default: None,
1125        });
1126        assert_eq!(got.unwrap().1, ProjectSource::ProjectFlag);
1127    }
1128
1129    #[test]
1130    fn binding_from_config_carries_remote_id_and_codebase_name() {
1131        let uuid = uuid::Uuid::new_v4();
1132        let config = crate::config::TracevaultConfig {
1133            repo_id: Some("repo-1".into()),
1134            remote_id: Some(uuid.to_string()),
1135            codebase_name: Some("acme/foo".into()),
1136            ..Default::default()
1137        };
1138        let binding = binding_from_config(&config).expect("repo_id present");
1139        assert_eq!(binding.codebase_name, Some("acme/foo".to_string()));
1140        assert_eq!(binding.remote_id, Some(uuid));
1141    }
1142
1143    #[test]
1144    fn codebase_line_formats_name_and_status() {
1145        let line = codebase_line(Some("acme/foo"), "github.com/acme/foo", "ready");
1146        assert_eq!(line, "codebase: acme/foo (ready)");
1147        let line = codebase_line(None, "github.com/acme/foo", "pending");
1148        assert_eq!(line, "codebase: github.com/acme/foo (pending)");
1149    }
1150
1151    #[test]
1152    fn pick_status_line_detail_wins_over_resolved_and_cached() {
1153        assert_eq!(
1154            pick_status_line(
1155                Some("codebase: a (ready)".to_string()),
1156                Some("codebase: b (pending)".to_string()),
1157                Some("c"),
1158            ),
1159            Some("codebase: a (ready)".to_string())
1160        );
1161    }
1162
1163    #[test]
1164    fn pick_status_line_resolved_wins_over_cached() {
1165        assert_eq!(
1166            pick_status_line(None, Some("codebase: b (pending)".to_string()), Some("c"),),
1167            Some("codebase: b (pending)".to_string())
1168        );
1169    }
1170
1171    #[test]
1172    fn pick_status_line_cached_only_is_name_only() {
1173        assert_eq!(
1174            pick_status_line(None, None, Some("c")),
1175            Some("codebase: c".to_string())
1176        );
1177    }
1178
1179    #[test]
1180    fn pick_status_line_none_when_nothing_available() {
1181        assert_eq!(pick_status_line(None, None, None), None);
1182    }
1183
1184    #[tokio::test]
1185    async fn resolve_repo_by_name_ok_when_name_matches() {
1186        let tmp = tempfile::tempdir().unwrap();
1187        crate::test_helpers::init_git_repo(tmp.path());
1188        let repo_name = git_repo_name(tmp.path());
1189        let body =
1190            format!(r#"[{{"id":"11111111-1111-1111-1111-111111111111","name":"{repo_name}"}}]"#);
1191        let (addr, _h) = spawn_once("200 OK", Box::leak(body.into_boxed_str()));
1192        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1193
1194        let repo = resolve_repo_by_name(&client, tmp.path())
1195            .await
1196            .expect("expected a match");
1197        assert_eq!(repo.name, repo_name);
1198    }
1199
1200    #[tokio::test]
1201    async fn resolve_repo_by_name_not_found_when_list_has_no_match() {
1202        let tmp = tempfile::tempdir().unwrap();
1203        crate::test_helpers::init_git_repo(tmp.path());
1204        let (addr, _h) = spawn_once(
1205            "200 OK",
1206            r#"[{"id":"11111111-1111-1111-1111-111111111111","name":"some-other-repo"}]"#,
1207        );
1208        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1209
1210        match resolve_repo_by_name(&client, tmp.path()).await {
1211            Err(ResolveRepoByNameError::NotFound { .. }) => {}
1212            other => panic!(
1213                "expected NotFound, got a different outcome: {}",
1214                other.is_ok()
1215            ),
1216        }
1217    }
1218
1219    #[tokio::test]
1220    async fn resolve_repo_by_name_list_failed_on_non_2xx() {
1221        // A `list_repos` failure (401/403/500/... — not necessarily a
1222        // network error, hence `ListFailed` rather than the old `Network`
1223        // name) must be distinguished from `NotFound` so callers like
1224        // `check`'s `connectivity_message` can add their own actionable
1225        // wrapping instead of a bare "not found" message.
1226        let tmp = tempfile::tempdir().unwrap();
1227        crate::test_helpers::init_git_repo(tmp.path());
1228        let (addr, _h) = spawn_once("500 Internal Server Error", "");
1229        let client = ApiClient::new(&format!("http://{addr}"), Some("tok"));
1230
1231        match resolve_repo_by_name(&client, tmp.path()).await {
1232            Err(ResolveRepoByNameError::ListFailed(e)) => {
1233                assert!(e.to_string().contains("500"), "got: {e}");
1234            }
1235            other => panic!(
1236                "expected ListFailed, got a different outcome: {}",
1237                other.is_ok()
1238            ),
1239        }
1240    }
1241}