Skip to main content

tracevault_cli/commands/
verification_phase.rs

1use crate::program::{CLI, ENV, TOP};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use tracevault_protocol::streaming::{StreamEventRequest, StreamEventType};
6
7use crate::config::TracevaultConfig;
8
9/// Send a VerificationPhaseStart event to the server, recording the current
10/// timestamp as the start of the verification phase for this session.
11///
12/// Only the most recent call per session matters — calling this again simply
13/// moves the phase cursor forward, discarding events from the previous phase.
14///
15/// `project_root` — the git-resolved PRIMARY worktree root (from
16///   `paths::resolve_project_root`). Used to locate `.visdom/`.
17/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used to
18///   determine the current worktree toplevel for session disambiguation. In a
19///   sibling linked worktree `cwd` differs from `project_root`, so both are
20///   needed.
21/// `explicit_session_id` — when Some, targets that session directly.
22/// `env_session_id` — `$TRACEVAULT_SESSION_ID` (in Amp: `$AMP_CURRENT_THREAD_ID`),
23///   the session that invoked this command (exported by the SessionStart hook,
24///   or set by Amp). Used when no flag is given
25///   and that session has recorded events in this worktree, so an agent never
26///   needs `--session-id` just because other sessions share the worktree.
27///   Otherwise the session is auto-detected by `origin` marker, falling back
28///   to the most recently modified session directory.
29///
30/// The event goes to the repo the session's tool events were streamed to,
31/// resolved as the stream hook resolves it (VIS-601) — otherwise the window
32/// and the events it should cover never meet on the server.
33pub async fn open_verification_phase(
34    project_root: &Path,
35    cwd: &Path,
36    explicit_session_id: Option<&str>,
37    env_session_id: Option<&str>,
38) -> Result<(), String> {
39    // Optional, like on the hook path: a session bound with `repo switch`
40    // resolves without a `.visdom/tracing.toml`. A malformed one is still
41    // an error — the hook refuses to send under it too.
42    let config = TracevaultConfig::try_load(project_root)
43        .map_err(|e| format!("malformed .visdom/tracing.toml: {e}"))?;
44
45    let sessions_dir = crate::layout::sessions_dir(project_root);
46    let worktree_top = crate::paths::worktree_toplevel(cwd);
47    // A session's own dir may live in the `.visdom/` it started in, not
48    // this checkout's (VIS-1257).
49    let session_dir_of = |id: &str| crate::session_state::session_dir(project_root, id);
50    let invoking = explicit_session_id
51        .is_none()
52        .then(|| invoking_session(&session_dir_of, &worktree_top, env_session_id))
53        .flatten();
54
55    let session_id = if let Some(id) = invoking {
56        id
57    } else if let Some(id) = explicit_session_id {
58        // Verify the session directory exists when an explicit ID is given.
59        if !crate::session_state::is_safe_session_id(id) {
60            return Err(format!("Invalid session ID: {id:?}"));
61        }
62        let dir = session_dir_of(id);
63        if !dir.is_dir() {
64            return Err(format!(
65                "Session directory not found: {}. Check the session ID.",
66                dir.display()
67            ));
68        }
69        if !belongs_here(&dir, &worktree_top) {
70            return Err(format!(
71                "Session {id} belongs to a different worktree (origin != {worktree_top}). \
72                 Run verify-start from that worktree, or omit --session-id."
73            ));
74        }
75        id.to_string()
76    } else {
77        // Auto-detect with worktree disambiguation.
78        //
79        // Since all worktrees share the primary `.visdom/sessions/` dir, the
80        // most-recently-modified heuristic can silently open the wrong session.
81        // Instead:
82        //   1. Compute the current worktree toplevel.
83        //   2. Look for sessions whose `origin` marker matches it.
84        //   3. If exactly one matches → use it.
85        //      If multiple match → error asking for --session-id.
86        //      If none match (legacy sessions without marker) → fall back to
87        //      most-recently-modified + print a warning.
88        // Use `cwd` (the actual invocation directory), not `project_root`
89        // (the primary root), so that in a sibling worktree we correctly
90        // compare against the sibling's toplevel, not the primary's.
91        // Plus sessions kept in the `.visdom/` they started in (an
92        // umbrella dir) that ran here (VIS-1257).
93        let mut matching = find_sessions_by_origin(&sessions_dir, &worktree_top);
94        matching.extend(crate::session_state::anchored_session_dirs(
95            &sessions_dir,
96            &worktree_top,
97        ));
98
99        match matching.len() {
100            1 => matching[0]
101                .file_name()
102                .and_then(|n| n.to_str())
103                .ok_or("Could not determine session ID from origin-matched session")?
104                .to_string(),
105            n if n > 1 => {
106                let ids: Vec<String> = matching
107                    .iter()
108                    .filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(String::from))
109                    .collect();
110                return Err(format!(
111                    "Multiple sessions belong to this worktree ({worktree_top}): {}. \
112                     Pass --session-id to select one, or run verify-start from the agent \
113                     session itself (it reads ${ENV}_SESSION_ID, or $AMP_CURRENT_THREAD_ID in Amp).",
114                    ids.join(", ")
115                ));
116            }
117            _ => {
118                let session_dir = find_latest_session(&sessions_dir, &worktree_top).ok_or(
119                    "No active session found for this worktree. Start a session by running an \
120                     AI coding agent here first, or pass --session-id to target a specific session.",
121                )?;
122                let chosen = session_dir
123                    .file_name()
124                    .and_then(|n| n.to_str())
125                    .ok_or("Could not determine session ID")?
126                    .to_string();
127                eprintln!(
128                    "Warning: no session matched this worktree by origin marker — \
129                     falling back to most recently modified session ({chosen})."
130                );
131                chosen
132            }
133        }
134    };
135
136    let event = StreamEventRequest {
137        protocol_version: 2,
138        // Carry the tool like the hook stream path does — the server's
139        // `sessions.tool` column is NOT NULL, so sending None makes the
140        // session upsert fail. (The server also defends against this, but
141        // there's no reason to send a null here.)
142        tool: Some("claude-code".to_string()),
143        event_type: StreamEventType::VerificationPhaseStart,
144        session_id: session_id.clone(),
145        timestamp: chrono::Utc::now(),
146        hook_event_name: None,
147        tool_name: None,
148        tool_use_id: None,
149        tool_input: None,
150        tool_response: None,
151        tool_is_error: None,
152        // The server's VerificationPhaseStart handler only records a timestamp;
153        // it stores no event row, so neither an index nor a uuid is needed.
154        event_index: None,
155        event_uuid: None,
156        transcript_lines: None,
157        transcript_offset: None,
158        model: None,
159        // Record the ACTUAL invocation directory (the worktree where
160        // verify-start ran), matching the stream hook's `cwd` field. Using
161        // `project_root` here would record the primary checkout in a sibling
162        // worktree and misattribute the verification-phase metadata.
163        cwd: Some(cwd.to_string_lossy().into_owned()),
164        final_stats: None,
165        flow_id: None,
166        labels: None,
167        params: None,
168        billing_mode: None,
169    };
170
171    // Through `resolve_client`, like every other command — NOT by pairing
172    // `Credentials::load()` with `config.server_url` directly.
173    //
174    // This is a security fix, not tidiness. `.visdom/tracing.toml` is
175    // TRACKED in user repos (the `.gitignore` this CLI writes covers only
176    // `sessions/`, `cache/` and `*.local.toml`), so a pull request that edited
177    // `server_url` made any reviewer who ran `tracevault verify-start` in that
178    // checkout POST their Keycloak access token to an arbitrary host. The
179    // refresh token is protected by the credential/URL scoping in
180    // `resolve_credentials`, but the access token went out on the very first
181    // request, ahead of every guard. Going through `resolve_client` applies
182    // that scoping here too, and picks up TRACEVAULT_API_KEY /
183    // TRACEVAULT_SERVER_URL, which this path ignored entirely.
184    //
185    // Two deliberate precedence changes come with it: the credentials file's
186    // URL now beats `config.server_url`, and having no URL configured is an
187    // error instead of a stale hardcoded default (which pointed at a
188    // softwaremill host this project has since migrated away from).
189    let client = crate::api_client::resolve_client(project_root).map_err(|e| e.to_string())?;
190
191    // The repo the session's tool events went to: the same chain as the hook
192    // (subagent override → `repo switch` → bound config → user default), and
193    // nothing else. The hook has no by-name fallback — with no repo binding
194    // it sends project-only or not at all — so guessing a repo here would
195    // open a window no tool event of this session ever reaches.
196    let state = crate::session_state::load(&session_id);
197    let binding = crate::resolution::recorded_session_binding(
198        &session_dir_of(&session_id),
199        &worktree_top,
200        &state,
201        config
202            .as_ref()
203            .and_then(crate::resolution::binding_from_config),
204        crate::user_default::load(),
205    );
206    let repo_id = binding
207        .ok_or_else(|| {
208            format!(
209                "No repo resolved for session {session_id}: it is not bound with \
210                 `{CLI} repo switch` and no repo_id is configured, so its tool events \
211                 are not sent to any repo. Run `{CLI} repo switch <path>` or \
212                 `{TOP} init`."
213            )
214        })?
215        .repo_id;
216
217    client
218        .stream_event(&repo_id, &event)
219        .await
220        .map_err(|e| format!("Failed to send verification phase event: {e}"))?;
221
222    println!("✓ Verification phase opened for session {session_id}");
223    println!("  Tool calls from this point are evaluated by verification_phase-scoped policies.");
224    println!("  Run `{CLI} verify-start` again to reset the phase if needed.");
225
226    Ok(())
227}
228
229/// The invoking session (`$TRACEVAULT_SESSION_ID`, in Amp `$AMP_CURRENT_THREAD_ID`),
230/// if it has a session directory here whose `origin` marker does not name another worktree. `None`
231/// sends the caller to the usual auto-detection — e.g. when the session has
232/// not streamed an event in this repo yet, or last streamed from a sibling
233/// worktree, where the explicit-flag path would refuse it.
234fn invoking_session(
235    session_dir_of: &dyn Fn(&str) -> PathBuf,
236    worktree_top: &str,
237    env_session_id: Option<&str>,
238) -> Option<String> {
239    let id = env_session_id.filter(|s| crate::session_state::is_safe_session_id(s))?;
240    let dir = session_dir_of(id);
241    (dir.is_dir() && belongs_here(&dir, worktree_top)).then(|| id.to_string())
242}
243
244/// A session dir's `origin` marker does not name another worktree — or it
245/// does, but the session also ran in this one: an anchored session's marker
246/// names only where its latest event ran (VIS-1257).
247fn belongs_here(dir: &Path, worktree_top: &str) -> bool {
248    origin_match(dir, worktree_top) != OriginMatch::Mismatch
249        || crate::session_state::ran_in(dir, worktree_top)
250}
251
252/// Return the most recently modified session directory under `sessions_dir`.
253///
254/// Sessions whose `origin` marker names another worktree are skipped: this is
255/// the fallback for legacy, unmarked sessions, and picking another worktree's
256/// session would open the window under that worktree's repo binding.
257fn find_latest_session(sessions_dir: &Path, worktree_top: &str) -> Option<PathBuf> {
258    crate::layout::session_entries(sessions_dir)
259        .into_iter()
260        .filter(|e| e.path().is_dir())
261        .filter(|e| belongs_here(&e.path(), worktree_top))
262        .max_by_key(|e| {
263            e.metadata()
264                .and_then(|m| m.modified())
265                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
266        })
267        .map(|e| e.path())
268}
269
270#[derive(Debug, PartialEq, Eq)]
271enum OriginMatch {
272    Match,
273    Mismatch,
274    NoMarker,
275}
276
277/// Classify a session's `origin` marker against the current worktree toplevel.
278fn origin_match(session_dir: &Path, worktree_top: &str) -> OriginMatch {
279    match fs::read_to_string(session_dir.join("origin")) {
280        Ok(s) if s.trim() == worktree_top => OriginMatch::Match,
281        Ok(_) => OriginMatch::Mismatch,
282        // Only a genuinely-absent marker is "legacy/no marker" (allowed).
283        Err(e) if e.kind() == std::io::ErrorKind::NotFound => OriginMatch::NoMarker,
284        // Marker present but unreadable: don't let it bypass the cross-worktree
285        // guard — treat it as a mismatch.
286        Err(_) => OriginMatch::Mismatch,
287    }
288}
289
290/// Return all session directories under `sessions_dir` that ran in
291/// `worktree_top`: their `origin` marker matches it (exact string match after
292/// trimming), or their worktree list names it.
293fn find_sessions_by_origin(sessions_dir: &Path, worktree_top: &str) -> Vec<PathBuf> {
294    crate::layout::session_entries(sessions_dir)
295        .into_iter()
296        .filter(|e| e.path().is_dir())
297        // `ran_in`: the `origin` marker names it, or an anchored session
298        // lists it among the worktrees it ran in (VIS-1257).
299        .filter(|e| crate::session_state::ran_in(&e.path(), worktree_top))
300        .map(|e| e.path())
301        .collect()
302}
303
304// ---------------------------------------------------------------------------
305// Tests
306// ---------------------------------------------------------------------------
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::test_helpers::{add_worktree, init_git_repo};
312
313    fn make_session_dir(sessions_dir: &Path, session_id: &str, origin: Option<&str>) -> PathBuf {
314        let dir = sessions_dir.join(session_id);
315        std::fs::create_dir_all(&dir).unwrap();
316        if let Some(o) = origin {
317            std::fs::write(dir.join("origin"), o).unwrap();
318        }
319        dir
320    }
321
322    // ── find_sessions_by_origin unit tests ───────────────────────────────────
323
324    #[test]
325    fn find_by_origin_matches_exact() {
326        let tmp = tempfile::tempdir().unwrap();
327        let sessions = tmp.path().join("sessions");
328        std::fs::create_dir_all(&sessions).unwrap();
329        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
330        make_session_dir(&sessions, "sess-b", Some("/repo/sibling"));
331        make_session_dir(&sessions, "sess-c", None); // legacy — no marker
332
333        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
334        assert_eq!(matched.len(), 1);
335        assert!(matched[0].ends_with("sess-a"));
336    }
337
338    #[test]
339    fn find_by_origin_no_match_returns_empty() {
340        let tmp = tempfile::tempdir().unwrap();
341        let sessions = tmp.path().join("sessions");
342        std::fs::create_dir_all(&sessions).unwrap();
343        make_session_dir(&sessions, "sess-a", Some("/repo/other"));
344        make_session_dir(&sessions, "sess-b", None);
345
346        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
347        assert!(matched.is_empty());
348    }
349
350    #[test]
351    fn find_by_origin_multiple_match() {
352        let tmp = tempfile::tempdir().unwrap();
353        let sessions = tmp.path().join("sessions");
354        std::fs::create_dir_all(&sessions).unwrap();
355        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
356        make_session_dir(&sessions, "sess-b", Some("/repo/primary"));
357        make_session_dir(&sessions, "sess-c", Some("/other"));
358
359        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
360        assert_eq!(matched.len(), 2);
361    }
362
363    // ── worktree-aware selection with real git worktrees ──────────────────────
364
365    /// check/verify-start from a sibling worktree resolves sessions_dir to the
366    /// primary `.visdom/` directory, not the worktree dir.
367    #[test]
368    fn sessions_dir_from_sibling_worktree_is_under_primary() {
369        let tmp = tempfile::tempdir().unwrap();
370        let repo = tmp.path().join("repo");
371        let wt = tmp.path().join("sibling-wt");
372        std::fs::create_dir_all(&repo).unwrap();
373        init_git_repo(&repo);
374        add_worktree(&repo, &wt);
375
376        // When open_verification_phase is called with project_root from
377        // resolve_project_root(sibling_wt), the sessions_dir is primary.
378        let resolved = crate::paths::resolve_project_root(&wt);
379        assert_eq!(
380            resolved.root.canonicalize().unwrap(),
381            repo.canonicalize().unwrap(),
382            "sibling worktree must resolve to primary repo root"
383        );
384        let sessions_dir = resolved.root.join(".visdom").join("sessions");
385        assert!(
386            sessions_dir.starts_with(&repo),
387            "sessions_dir must be under primary repo root"
388        );
389    }
390
391    /// Two sessions seeded under the shared sessions dir with different origins.
392    /// find_sessions_by_origin must return only the one matching the current
393    /// worktree toplevel.
394    #[test]
395    fn disambiguation_selects_current_worktree_session() {
396        let tmp = tempfile::tempdir().unwrap();
397        let repo = tmp.path().join("repo");
398        let wt = tmp.path().join("sibling-wt");
399        std::fs::create_dir_all(&repo).unwrap();
400        init_git_repo(&repo);
401        add_worktree(&repo, &wt);
402
403        let primary_top = repo.canonicalize().unwrap().to_string_lossy().into_owned();
404        let wt_top = wt.canonicalize().unwrap().to_string_lossy().into_owned();
405
406        let sessions_dir = repo.join(".visdom").join("sessions");
407        std::fs::create_dir_all(&sessions_dir).unwrap();
408        make_session_dir(&sessions_dir, "session-primary", Some(&primary_top));
409        make_session_dir(&sessions_dir, "session-sibling", Some(&wt_top));
410
411        // From the sibling worktree, only session-sibling matches.
412        let matched = find_sessions_by_origin(&sessions_dir, &wt_top);
413        assert_eq!(matched.len(), 1);
414        assert!(
415            matched[0].ends_with("session-sibling"),
416            "expected session-sibling, got {:?}",
417            matched[0]
418        );
419
420        // From the primary, only session-primary matches.
421        let matched_primary = find_sessions_by_origin(&sessions_dir, &primary_top);
422        assert_eq!(matched_primary.len(), 1);
423        assert!(matched_primary[0].ends_with("session-primary"));
424    }
425
426    /// Two sessions with the same origin → caller gets 2 results and should
427    /// emit an error requesting --session-id.
428    #[test]
429    fn disambiguation_errors_on_multiple_matches() {
430        let tmp = tempfile::tempdir().unwrap();
431        let sessions = tmp.path().join("sessions");
432        std::fs::create_dir_all(&sessions).unwrap();
433        make_session_dir(&sessions, "sess-a", Some("/worktree/top"));
434        make_session_dir(&sessions, "sess-b", Some("/worktree/top"));
435
436        let matched = find_sessions_by_origin(&sessions, "/worktree/top");
437        assert_eq!(
438            matched.len(),
439            2,
440            "both sessions must be returned for disambiguation"
441        );
442    }
443
444    /// Legacy sessions with no origin markers → find_sessions_by_origin returns
445    /// empty; find_latest_session (fallback) still returns a session.
446    #[test]
447    fn disambiguation_fallback_when_no_markers() {
448        let tmp = tempfile::tempdir().unwrap();
449        let sessions = tmp.path().join("sessions");
450        std::fs::create_dir_all(&sessions).unwrap();
451        make_session_dir(&sessions, "sess-legacy-1", None);
452        make_session_dir(&sessions, "sess-legacy-2", None);
453
454        let matched = find_sessions_by_origin(&sessions, "/any/worktree");
455        assert!(matched.is_empty(), "no markers means no matches");
456
457        // Fallback must still find a session.
458        let latest = find_latest_session(&sessions, "/any/worktree");
459        assert!(latest.is_some(), "fallback must find a session");
460    }
461
462    /// The fallback is for legacy, unmarked sessions only: it must never pick
463    /// a session marked as another worktree's — e.g. the invoking session that
464    /// `invoking_session` just rejected for that reason — because its repo
465    /// binding (and subagent override) belong to that other worktree.
466    #[test]
467    fn fallback_never_picks_another_worktrees_session() {
468        let tmp = tempfile::tempdir().unwrap();
469        let sessions = tmp.path().join("sessions");
470        make_session_dir(&sessions, "sess-legacy", None);
471        // Created last, so it is the most recently modified.
472        make_session_dir(&sessions, "sess-elsewhere", Some("/wt/b"));
473
474        let latest = find_latest_session(&sessions, "/wt/a").unwrap();
475        assert!(latest.ends_with("sess-legacy"), "{}", latest.display());
476
477        let only_elsewhere = tmp.path().join("only-elsewhere");
478        make_session_dir(&only_elsewhere, "sess-elsewhere", Some("/wt/b"));
479        assert_eq!(find_latest_session(&only_elsewhere, "/wt/a"), None);
480    }
481
482    /// Verify that `paths::worktree_toplevel(sibling_wt)` returns the sibling
483    /// worktree's path, NOT the primary repo path. This confirms that the `cwd`
484    /// parameter to `open_verification_phase` correctly identifies the invoking
485    /// worktree for disambiguation purposes.
486    #[test]
487    fn current_worktree_toplevel_returns_sibling_top_not_primary() {
488        let tmp = tempfile::tempdir().unwrap();
489        let repo = tmp.path().join("repo");
490        let wt = tmp.path().join("sibling-wt");
491        std::fs::create_dir_all(&repo).unwrap();
492        init_git_repo(&repo);
493        add_worktree(&repo, &wt);
494
495        let wt_top = crate::paths::worktree_toplevel(&wt);
496        let wt_canonical = wt.canonicalize().unwrap().to_string_lossy().into_owned();
497        let repo_canonical = repo.canonicalize().unwrap().to_string_lossy().into_owned();
498
499        assert_eq!(
500            wt_top, wt_canonical,
501            "current_worktree_toplevel from sibling must return sibling path"
502        );
503        assert_ne!(
504            wt_top, repo_canonical,
505            "current_worktree_toplevel from sibling must NOT return primary repo path"
506        );
507    }
508
509    #[test]
510    fn origin_match_classifies_marker_states() {
511        let tmp = tempfile::tempdir().unwrap();
512        let sessions = tmp.path().join("sessions");
513        std::fs::create_dir_all(&sessions).unwrap();
514        let m = make_session_dir(&sessions, "match", Some("/wt/a"));
515        let x = make_session_dir(&sessions, "mismatch", Some("/wt/b"));
516        let n = make_session_dir(&sessions, "none", None);
517
518        assert_eq!(origin_match(&m, "/wt/a"), OriginMatch::Match);
519        assert_eq!(origin_match(&x, "/wt/a"), OriginMatch::Mismatch);
520        assert_eq!(origin_match(&n, "/wt/a"), OriginMatch::NoMarker);
521    }
522
523    #[test]
524    fn origin_match_unreadable_marker_is_mismatch_not_nomarker() {
525        // A present-but-unreadable marker must NOT bypass the cross-worktree
526        // guard. Make `origin` a directory so read_to_string fails with a
527        // non-NotFound error.
528        let tmp = tempfile::tempdir().unwrap();
529        let dir = tmp.path().join("sess-bad");
530        std::fs::create_dir_all(dir.join("origin")).unwrap();
531
532        assert_eq!(origin_match(&dir, "/wt/a"), OriginMatch::Mismatch);
533    }
534
535    /// `verify-start` used to pair `Credentials::load()` with
536    /// `config.server_url` directly, bypassing everything `resolve_credentials`
537    /// enforces. Since `.visdom/tracing.toml` is TRACKED in user repos, a PR
538    /// that edited `server_url` made any reviewer running this command POST
539    /// their Keycloak access token to an arbitrary host.
540    ///
541    /// Going through `resolve_client` closes it by PRECEDENCE, which is stronger
542    /// than refusing: the credentials file's own URL outranks
543    /// `config.server_url`, so a committed config can no longer redirect the
544    /// token anywhere. Proven by pointing the saved login at a local one-shot
545    /// server and the config at a host that must never be contacted — if the
546    /// old code path were still in place, no request would arrive here at all.
547    #[tokio::test]
548    async fn a_committed_config_url_cannot_redirect_the_token() {
549        let _env_lock = crate::test_helpers::lock_env_mutation().await;
550        let home = tempfile::tempdir().unwrap();
551        let mut guard = crate::test_helpers::EnvVarGuard::new();
552        guard.set("XDG_CONFIG_HOME", home.path());
553        guard.set("XDG_STATE_HOME", home.path());
554        guard.remove("TRACEVAULT_API_KEY");
555        guard.remove("TRACEVAULT_SERVER_URL");
556
557        let (login_server, rx) = crate::test_helpers::spawn_seq(vec![
558            crate::test_helpers::http_json(
559                "200 OK",
560                r#"{"session_db_id":"22222222-2222-4222-8222-222222222222","event_db_id":null,"status":"ok"}"#,
561            ),
562        ]);
563
564        // The saved login is for `login_server`.
565        let creds_dir = home.path().join("visdom");
566        std::fs::create_dir_all(&creds_dir).unwrap();
567        std::fs::write(
568            creds_dir.join("credentials.json"),
569            format!(
570                r#"{{"server_url":"{login_server}","email":"a@b.com","auth":{{
571                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
572                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
573            ),
574        )
575        .unwrap();
576
577        // The repo's committed config points somewhere else — the malicious PR.
578        let repo = tempfile::tempdir().unwrap();
579        let tv = repo.path().join(".visdom");
580        std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
581        std::fs::write(
582            tv.join("tracing.toml"),
583            "repo_id = \"11111111-1111-4111-8111-111111111111\"\n\
584             server_url = \"https://attacker.invalid\"\n",
585        )
586        .unwrap();
587
588        open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
589            .await
590            .expect("the event must go to the login's server");
591
592        let request = rx
593            .recv_timeout(crate::test_helpers::RECV_TIMEOUT)
594            .expect("no request reached the login's server — the config URL was used instead");
595        assert!(
596            request.contains("/api/v1/repos/11111111-1111-4111-8111-111111111111/stream"),
597            "unexpected request: {request}"
598        );
599        assert!(
600            request.contains("Bearer at"),
601            "must present the saved credential: {request}"
602        );
603    }
604
605    /// And it consults the credential/URL guard: a `TRACEVAULT_SERVER_URL`
606    /// pointing at another instance is refused before any request goes out,
607    /// rather than sending the saved token there.
608    #[tokio::test]
609    async fn a_mismatched_env_server_url_refuses_before_sending() {
610        let _env_lock = crate::test_helpers::lock_env_mutation().await;
611        let home = tempfile::tempdir().unwrap();
612        let mut guard = crate::test_helpers::EnvVarGuard::new();
613        guard.set("XDG_CONFIG_HOME", home.path());
614        guard.set("XDG_STATE_HOME", home.path());
615        guard.remove("TRACEVAULT_API_KEY");
616        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
617
618        let creds_dir = home.path().join("visdom");
619        std::fs::create_dir_all(&creds_dir).unwrap();
620        std::fs::write(
621            creds_dir.join("credentials.json"),
622            r#"{"server_url":"https://instance-b.example.com","email":"a@b.com","auth":{
623                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
624                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}"#,
625        )
626        .unwrap();
627
628        let repo = tempfile::tempdir().unwrap();
629        let tv = repo.path().join(".visdom");
630        std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
631        std::fs::write(
632            tv.join("tracing.toml"),
633            "repo_id = \"11111111-1111-4111-8111-111111111111\"\n",
634        )
635        .unwrap();
636
637        let err = open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
638            .await
639            .expect_err("a mismatched server URL must be refused");
640        assert!(
641            err.contains("instance-a.example.com") && err.contains("instance-b.example.com"),
642            "the refusal must name both URLs: {err}"
643        );
644        assert!(
645            err.contains("refusing to use the saved credentials"),
646            "must be the credential-scoping refusal, not a connection error: {err}"
647        );
648    }
649
650    // ── VIS-601: same session, same repo as the stream hook ──────────────────
651
652    const CONFIG_REPO: &str = "11111111-1111-4111-8111-111111111111";
653    const SWITCHED_REPO: &str = "44444444-4444-4444-8444-444444444444";
654
655    /// Isolated config/state homes with a saved login pointing at a one-shot
656    /// server that accepts one stream event. Returns the guard (keep it alive),
657    /// the home dir and the request receiver.
658    fn login_to_one_shot_server() -> (
659        crate::test_helpers::EnvVarGuard,
660        tempfile::TempDir,
661        std::sync::mpsc::Receiver<String>,
662    ) {
663        let home = tempfile::tempdir().unwrap();
664        let mut guard = crate::test_helpers::EnvVarGuard::new();
665        guard.set("XDG_CONFIG_HOME", home.path());
666        guard.set("XDG_STATE_HOME", home.path());
667        guard.remove("TRACEVAULT_API_KEY");
668        guard.remove("TRACEVAULT_SERVER_URL");
669        let (server, rx) = crate::test_helpers::spawn_seq(vec![crate::test_helpers::http_json(
670            "200 OK",
671            r#"{"session_db_id":"22222222-2222-4222-8222-222222222222","event_db_id":null,"status":"ok"}"#,
672        )]);
673        let creds_dir = home.path().join("visdom");
674        std::fs::create_dir_all(&creds_dir).unwrap();
675        std::fs::write(
676            creds_dir.join("credentials.json"),
677            format!(
678                r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
679                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
680                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
681            ),
682        )
683        .unwrap();
684        (guard, home, rx)
685    }
686
687    /// A checkout with a pinned config repo and the given sessions, all of
688    /// them recorded (by `origin` marker) as belonging to this worktree.
689    fn checkout_with_sessions(ids: &[&str]) -> tempfile::TempDir {
690        let repo = tempfile::tempdir().unwrap();
691        let tv = repo.path().join(".visdom");
692        let top = crate::paths::worktree_toplevel(repo.path());
693        for id in ids {
694            make_session_dir(&tv.join("sessions"), id, Some(&top));
695        }
696        std::fs::write(
697            tv.join("tracing.toml"),
698            format!("repo_id = \"{CONFIG_REPO}\"\n"),
699        )
700        .unwrap();
701        repo
702    }
703
704    fn bind_with_repo_switch(session_id: &str, repo_id: &str) {
705        let state = crate::session_state::SessionState {
706            active: Some(crate::session_state::RepoBinding {
707                repo_id: repo_id.into(),
708                git_url: None,
709                remote_id: None,
710                codebase_name: None,
711                updated_at: "t".into(),
712            }),
713            ..Default::default()
714        };
715        crate::session_state::save(session_id, &state).unwrap();
716    }
717
718    #[tokio::test]
719    async fn a_session_bound_with_repo_switch_opens_its_window_under_the_bound_repo() {
720        let _env_lock = crate::test_helpers::lock_env_mutation().await;
721        let (_guard, _home, rx) = login_to_one_shot_server();
722        let repo = checkout_with_sessions(&["sess-1"]);
723        bind_with_repo_switch("sess-1", SWITCHED_REPO);
724
725        open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
726            .await
727            .unwrap();
728
729        let request = rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap();
730        assert!(
731            request.contains(&format!("/api/v1/repos/{SWITCHED_REPO}/stream")),
732            "the window must go where the session's tool events go, not to config.repo_id: \
733             {request}"
734        );
735    }
736
737    /// Several sessions in one worktree is the normal state (`.pushed` is never
738    /// written), so the invoking session must not need `--session-id`.
739    #[tokio::test]
740    async fn the_invoking_session_is_used_when_several_share_the_worktree() {
741        let _env_lock = crate::test_helpers::lock_env_mutation().await;
742        let (_guard, _home, rx) = login_to_one_shot_server();
743        let repo = checkout_with_sessions(&["sess-other", "sess-me"]);
744        bind_with_repo_switch("sess-me", SWITCHED_REPO);
745
746        open_verification_phase(repo.path(), repo.path(), None, Some("sess-me"))
747            .await
748            .expect("must not ask for --session-id");
749
750        let request = rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap();
751        assert!(
752            request.contains(&format!("/api/v1/repos/{SWITCHED_REPO}/stream")),
753            "{request}"
754        );
755        assert!(
756            request.contains(r#""session_id":"sess-me""#),
757            "must open the window for the invoking session: {request}"
758        );
759    }
760
761    /// With no repo binding the hook sends nothing to any repo, so there is no
762    /// repo to open the window under: refuse instead of guessing one by name.
763    #[tokio::test]
764    async fn an_unbound_session_without_config_is_refused_without_sending() {
765        let _env_lock = crate::test_helpers::lock_env_mutation().await;
766        let (_guard, _home, rx) = login_to_one_shot_server();
767        let repo = tempfile::tempdir().unwrap();
768        let top = crate::paths::worktree_toplevel(repo.path());
769        make_session_dir(
770            &repo.path().join(".visdom").join("sessions"),
771            "sess-1",
772            Some(&top),
773        );
774
775        let err = open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
776            .await
777            .expect_err("no repo resolves for this session");
778        assert!(err.contains("No repo resolved for session sess-1"), "{err}");
779        assert!(
780            rx.recv_timeout(std::time::Duration::from_millis(300))
781                .is_err(),
782            "nothing may be sent"
783        );
784    }
785
786    #[test]
787    fn invoking_session_needs_a_session_dir_in_this_worktree() {
788        let tmp = tempfile::tempdir().unwrap();
789        let sessions = tmp.path().join("sessions");
790        make_session_dir(&sessions, "here", Some("/wt/a"));
791        make_session_dir(&sessions, "legacy", None);
792        make_session_dir(&sessions, "elsewhere", Some("/wt/b"));
793
794        assert_eq!(
795            invoking_session(&|id| sessions.join(id), "/wt/a", Some("here")).as_deref(),
796            Some("here")
797        );
798        assert_eq!(
799            invoking_session(&|id| sessions.join(id), "/wt/a", Some("legacy")).as_deref(),
800            Some("legacy")
801        );
802        assert_eq!(
803            invoking_session(&|id| sessions.join(id), "/wt/a", Some("elsewhere")),
804            None
805        );
806        assert_eq!(
807            invoking_session(&|id| sessions.join(id), "/wt/a", Some("missing")),
808            None
809        );
810        // An anchored session that ran here and moved on (VIS-1257).
811        crate::session_state::record_worktree(&sessions.join("elsewhere"), "/wt/a").unwrap();
812        assert_eq!(
813            invoking_session(&|id| sessions.join(id), "/wt/a", Some("elsewhere")).as_deref(),
814            Some("elsewhere")
815        );
816        assert_eq!(
817            invoking_session(&|id| sessions.join(id), "/wt/a", Some("../here")),
818            None
819        );
820        assert_eq!(
821            invoking_session(&|id| sessions.join(id), "/wt/a", None),
822            None
823        );
824    }
825}