Skip to main content

tracevault_cli/commands/
verification_phase.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3
4use tracevault_protocol::streaming::{StreamEventRequest, StreamEventType};
5
6use crate::config::TracevaultConfig;
7
8/// Send a VerificationPhaseStart event to the server, recording the current
9/// timestamp as the start of the verification phase for this session.
10///
11/// Only the most recent call per session matters — calling this again simply
12/// moves the phase cursor forward, discarding events from the previous phase.
13///
14/// `project_root` — the git-resolved PRIMARY worktree root (from
15///   `paths::resolve_project_root`). Used to locate `.tracevault/`.
16/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used to
17///   determine the current worktree toplevel for session disambiguation. In a
18///   sibling linked worktree `cwd` differs from `project_root`, so both are
19///   needed.
20/// `explicit_session_id` — when Some, targets that session directly.
21///   When None, the most recently modified session directory is used (suitable
22///   for single-agent setups; pass `--session-id` in multi-agent setups).
23pub async fn open_verification_phase(
24    project_root: &Path,
25    cwd: &Path,
26    explicit_session_id: Option<&str>,
27) -> Result<(), String> {
28    let config = TracevaultConfig::load(project_root)
29        .ok_or("TraceVault not initialized. Run `tracevault init` first.")?;
30
31    let repo_id = config
32        .repo_id
33        .as_deref()
34        .ok_or("No repo_id configured. Run `tracevault init`.")?;
35
36    let sessions_dir = project_root.join(".tracevault").join("sessions");
37
38    let session_id = if let Some(id) = explicit_session_id {
39        // Verify the session directory exists when an explicit ID is given.
40        let dir = sessions_dir.join(id);
41        if !dir.is_dir() {
42            return Err(format!(
43                "Session directory not found: {}. Check the session ID.",
44                dir.display()
45            ));
46        }
47        let worktree_top = crate::paths::worktree_toplevel(cwd);
48        if origin_match(&dir, &worktree_top) == OriginMatch::Mismatch {
49            return Err(format!(
50                "Session {id} belongs to a different worktree (origin != {worktree_top}). \
51                 Run verify-start from that worktree, or omit --session-id."
52            ));
53        }
54        id.to_string()
55    } else {
56        // Auto-detect with worktree disambiguation.
57        //
58        // Since all worktrees share the primary `.tracevault/sessions/` dir, the
59        // most-recently-modified heuristic can silently open the wrong session.
60        // Instead:
61        //   1. Compute the current worktree toplevel.
62        //   2. Look for sessions whose `origin` marker matches it.
63        //   3. If exactly one matches → use it.
64        //      If multiple match → error asking for --session-id.
65        //      If none match (legacy sessions without marker) → fall back to
66        //      most-recently-modified + print a warning.
67        // Use `cwd` (the actual invocation directory), not `project_root`
68        // (the primary root), so that in a sibling worktree we correctly
69        // compare against the sibling's toplevel, not the primary's.
70        let worktree_top = crate::paths::worktree_toplevel(cwd);
71        let matching = find_sessions_by_origin(&sessions_dir, &worktree_top);
72
73        match matching.len() {
74            1 => matching[0]
75                .file_name()
76                .and_then(|n| n.to_str())
77                .ok_or("Could not determine session ID from origin-matched session")?
78                .to_string(),
79            n if n > 1 => {
80                let ids: Vec<String> = matching
81                    .iter()
82                    .filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(String::from))
83                    .collect();
84                return Err(format!(
85                    "Multiple sessions belong to this worktree ({worktree_top}): {}. \
86                     Pass --session-id to select one.",
87                    ids.join(", ")
88                ));
89            }
90            _ => {
91                let session_dir = find_latest_session(&sessions_dir).ok_or(
92                    "No active session found. Start a session by running an AI coding agent \
93                     first, or pass --session-id to target a specific session.",
94                )?;
95                let chosen = session_dir
96                    .file_name()
97                    .and_then(|n| n.to_str())
98                    .ok_or("Could not determine session ID")?
99                    .to_string();
100                eprintln!(
101                    "Warning: no session matched this worktree by origin marker — \
102                     falling back to most recently modified session ({chosen})."
103                );
104                chosen
105            }
106        }
107    };
108
109    let event = StreamEventRequest {
110        protocol_version: 2,
111        // Carry the tool like the hook stream path does — the server's
112        // `sessions.tool` column is NOT NULL, so sending None makes the
113        // session upsert fail. (The server also defends against this, but
114        // there's no reason to send a null here.)
115        tool: Some("claude-code".to_string()),
116        event_type: StreamEventType::VerificationPhaseStart,
117        session_id: session_id.clone(),
118        timestamp: chrono::Utc::now(),
119        hook_event_name: None,
120        tool_name: None,
121        tool_use_id: None,
122        tool_input: None,
123        tool_response: None,
124        tool_is_error: None,
125        // The server's VerificationPhaseStart handler only records a timestamp;
126        // it stores no event row, so neither an index nor a uuid is needed.
127        event_index: None,
128        event_uuid: None,
129        transcript_lines: None,
130        transcript_offset: None,
131        model: None,
132        // Record the ACTUAL invocation directory (the worktree where
133        // verify-start ran), matching the stream hook's `cwd` field. Using
134        // `project_root` here would record the primary checkout in a sibling
135        // worktree and misattribute the verification-phase metadata.
136        cwd: Some(cwd.to_string_lossy().into_owned()),
137        final_stats: None,
138        flow_id: None,
139        labels: None,
140        params: None,
141    };
142
143    // Through `resolve_client`, like every other command — NOT by pairing
144    // `Credentials::load()` with `config.server_url` directly.
145    //
146    // This is a security fix, not tidiness. `.tracevault/config.toml` is
147    // TRACKED in user repos (the `.gitignore` this CLI writes covers only
148    // `sessions/`, `cache/` and `*.local.toml`), so a pull request that edited
149    // `server_url` made any reviewer who ran `tracevault verify-start` in that
150    // checkout POST their Keycloak access token to an arbitrary host. The
151    // refresh token is protected by the credential/URL scoping in
152    // `resolve_credentials`, but the access token went out on the very first
153    // request, ahead of every guard. Going through `resolve_client` applies
154    // that scoping here too, and picks up TRACEVAULT_API_KEY /
155    // TRACEVAULT_SERVER_URL, which this path ignored entirely.
156    //
157    // Two deliberate precedence changes come with it: the credentials file's
158    // URL now beats `config.server_url`, and having no URL configured is an
159    // error instead of a stale hardcoded default (which pointed at a
160    // softwaremill host this project has since migrated away from).
161    let client = crate::api_client::resolve_client(project_root).map_err(|e| e.to_string())?;
162
163    client
164        .stream_event(repo_id, &event)
165        .await
166        .map_err(|e| format!("Failed to send verification phase event: {e}"))?;
167
168    println!("✓ Verification phase opened for session {session_id}");
169    println!("  Tool calls from this point are evaluated by verification_phase-scoped policies.");
170    println!("  Run `tracevault verify-start` again to reset the phase if needed.");
171
172    Ok(())
173}
174
175/// Return the most recently modified session directory under `sessions_dir`.
176fn find_latest_session(sessions_dir: &Path) -> Option<PathBuf> {
177    let entries = fs::read_dir(sessions_dir).ok()?;
178    entries
179        .filter_map(|e| e.ok())
180        .filter(|e| e.path().is_dir())
181        .max_by_key(|e| {
182            e.metadata()
183                .and_then(|m| m.modified())
184                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
185        })
186        .map(|e| e.path())
187}
188
189#[derive(Debug, PartialEq, Eq)]
190enum OriginMatch {
191    Match,
192    Mismatch,
193    NoMarker,
194}
195
196/// Classify a session's `origin` marker against the current worktree toplevel.
197fn origin_match(session_dir: &Path, worktree_top: &str) -> OriginMatch {
198    match fs::read_to_string(session_dir.join("origin")) {
199        Ok(s) if s.trim() == worktree_top => OriginMatch::Match,
200        Ok(_) => OriginMatch::Mismatch,
201        // Only a genuinely-absent marker is "legacy/no marker" (allowed).
202        Err(e) if e.kind() == std::io::ErrorKind::NotFound => OriginMatch::NoMarker,
203        // Marker present but unreadable: don't let it bypass the cross-worktree
204        // guard — treat it as a mismatch.
205        Err(_) => OriginMatch::Mismatch,
206    }
207}
208
209/// Return all session directories under `sessions_dir` whose `origin` marker
210/// file matches `worktree_top` (exact string match after trimming).
211fn find_sessions_by_origin(sessions_dir: &Path, worktree_top: &str) -> Vec<PathBuf> {
212    let Ok(entries) = fs::read_dir(sessions_dir) else {
213        return vec![];
214    };
215    entries
216        .filter_map(|e| e.ok())
217        .filter(|e| e.path().is_dir())
218        .filter(|e| {
219            let origin_file = e.path().join("origin");
220            fs::read_to_string(&origin_file)
221                .map(|s| s.trim() == worktree_top)
222                .unwrap_or(false)
223        })
224        .map(|e| e.path())
225        .collect()
226}
227
228// ---------------------------------------------------------------------------
229// Tests
230// ---------------------------------------------------------------------------
231
232#[cfg(test)]
233mod tests {
234    use super::*;
235    use crate::test_helpers::{add_worktree, init_git_repo};
236
237    fn make_session_dir(sessions_dir: &Path, session_id: &str, origin: Option<&str>) -> PathBuf {
238        let dir = sessions_dir.join(session_id);
239        std::fs::create_dir_all(&dir).unwrap();
240        if let Some(o) = origin {
241            std::fs::write(dir.join("origin"), o).unwrap();
242        }
243        dir
244    }
245
246    // ── find_sessions_by_origin unit tests ───────────────────────────────────
247
248    #[test]
249    fn find_by_origin_matches_exact() {
250        let tmp = tempfile::tempdir().unwrap();
251        let sessions = tmp.path().join("sessions");
252        std::fs::create_dir_all(&sessions).unwrap();
253        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
254        make_session_dir(&sessions, "sess-b", Some("/repo/sibling"));
255        make_session_dir(&sessions, "sess-c", None); // legacy — no marker
256
257        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
258        assert_eq!(matched.len(), 1);
259        assert!(matched[0].ends_with("sess-a"));
260    }
261
262    #[test]
263    fn find_by_origin_no_match_returns_empty() {
264        let tmp = tempfile::tempdir().unwrap();
265        let sessions = tmp.path().join("sessions");
266        std::fs::create_dir_all(&sessions).unwrap();
267        make_session_dir(&sessions, "sess-a", Some("/repo/other"));
268        make_session_dir(&sessions, "sess-b", None);
269
270        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
271        assert!(matched.is_empty());
272    }
273
274    #[test]
275    fn find_by_origin_multiple_match() {
276        let tmp = tempfile::tempdir().unwrap();
277        let sessions = tmp.path().join("sessions");
278        std::fs::create_dir_all(&sessions).unwrap();
279        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
280        make_session_dir(&sessions, "sess-b", Some("/repo/primary"));
281        make_session_dir(&sessions, "sess-c", Some("/other"));
282
283        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
284        assert_eq!(matched.len(), 2);
285    }
286
287    // ── worktree-aware selection with real git worktrees ──────────────────────
288
289    /// check/verify-start from a sibling worktree resolves sessions_dir to the
290    /// primary `.tracevault/` directory, not the worktree dir.
291    #[test]
292    fn sessions_dir_from_sibling_worktree_is_under_primary() {
293        let tmp = tempfile::tempdir().unwrap();
294        let repo = tmp.path().join("repo");
295        let wt = tmp.path().join("sibling-wt");
296        std::fs::create_dir_all(&repo).unwrap();
297        init_git_repo(&repo);
298        add_worktree(&repo, &wt);
299
300        // When open_verification_phase is called with project_root from
301        // resolve_project_root(sibling_wt), the sessions_dir is primary.
302        let resolved = crate::paths::resolve_project_root(&wt);
303        assert_eq!(
304            resolved.root.canonicalize().unwrap(),
305            repo.canonicalize().unwrap(),
306            "sibling worktree must resolve to primary repo root"
307        );
308        let sessions_dir = resolved.root.join(".tracevault").join("sessions");
309        assert!(
310            sessions_dir.starts_with(&repo),
311            "sessions_dir must be under primary repo root"
312        );
313    }
314
315    /// Two sessions seeded under the shared sessions dir with different origins.
316    /// find_sessions_by_origin must return only the one matching the current
317    /// worktree toplevel.
318    #[test]
319    fn disambiguation_selects_current_worktree_session() {
320        let tmp = tempfile::tempdir().unwrap();
321        let repo = tmp.path().join("repo");
322        let wt = tmp.path().join("sibling-wt");
323        std::fs::create_dir_all(&repo).unwrap();
324        init_git_repo(&repo);
325        add_worktree(&repo, &wt);
326
327        let primary_top = repo.canonicalize().unwrap().to_string_lossy().into_owned();
328        let wt_top = wt.canonicalize().unwrap().to_string_lossy().into_owned();
329
330        let sessions_dir = repo.join(".tracevault").join("sessions");
331        std::fs::create_dir_all(&sessions_dir).unwrap();
332        make_session_dir(&sessions_dir, "session-primary", Some(&primary_top));
333        make_session_dir(&sessions_dir, "session-sibling", Some(&wt_top));
334
335        // From the sibling worktree, only session-sibling matches.
336        let matched = find_sessions_by_origin(&sessions_dir, &wt_top);
337        assert_eq!(matched.len(), 1);
338        assert!(
339            matched[0].ends_with("session-sibling"),
340            "expected session-sibling, got {:?}",
341            matched[0]
342        );
343
344        // From the primary, only session-primary matches.
345        let matched_primary = find_sessions_by_origin(&sessions_dir, &primary_top);
346        assert_eq!(matched_primary.len(), 1);
347        assert!(matched_primary[0].ends_with("session-primary"));
348    }
349
350    /// Two sessions with the same origin → caller gets 2 results and should
351    /// emit an error requesting --session-id.
352    #[test]
353    fn disambiguation_errors_on_multiple_matches() {
354        let tmp = tempfile::tempdir().unwrap();
355        let sessions = tmp.path().join("sessions");
356        std::fs::create_dir_all(&sessions).unwrap();
357        make_session_dir(&sessions, "sess-a", Some("/worktree/top"));
358        make_session_dir(&sessions, "sess-b", Some("/worktree/top"));
359
360        let matched = find_sessions_by_origin(&sessions, "/worktree/top");
361        assert_eq!(
362            matched.len(),
363            2,
364            "both sessions must be returned for disambiguation"
365        );
366    }
367
368    /// Legacy sessions with no origin markers → find_sessions_by_origin returns
369    /// empty; find_latest_session (fallback) still returns a session.
370    #[test]
371    fn disambiguation_fallback_when_no_markers() {
372        let tmp = tempfile::tempdir().unwrap();
373        let sessions = tmp.path().join("sessions");
374        std::fs::create_dir_all(&sessions).unwrap();
375        make_session_dir(&sessions, "sess-legacy-1", None);
376        make_session_dir(&sessions, "sess-legacy-2", None);
377
378        let matched = find_sessions_by_origin(&sessions, "/any/worktree");
379        assert!(matched.is_empty(), "no markers means no matches");
380
381        // Fallback must still find a session.
382        let latest = find_latest_session(&sessions);
383        assert!(latest.is_some(), "fallback must find a session");
384    }
385
386    /// Verify that `paths::worktree_toplevel(sibling_wt)` returns the sibling
387    /// worktree's path, NOT the primary repo path. This confirms that the `cwd`
388    /// parameter to `open_verification_phase` correctly identifies the invoking
389    /// worktree for disambiguation purposes.
390    #[test]
391    fn current_worktree_toplevel_returns_sibling_top_not_primary() {
392        let tmp = tempfile::tempdir().unwrap();
393        let repo = tmp.path().join("repo");
394        let wt = tmp.path().join("sibling-wt");
395        std::fs::create_dir_all(&repo).unwrap();
396        init_git_repo(&repo);
397        add_worktree(&repo, &wt);
398
399        let wt_top = crate::paths::worktree_toplevel(&wt);
400        let wt_canonical = wt.canonicalize().unwrap().to_string_lossy().into_owned();
401        let repo_canonical = repo.canonicalize().unwrap().to_string_lossy().into_owned();
402
403        assert_eq!(
404            wt_top, wt_canonical,
405            "current_worktree_toplevel from sibling must return sibling path"
406        );
407        assert_ne!(
408            wt_top, repo_canonical,
409            "current_worktree_toplevel from sibling must NOT return primary repo path"
410        );
411    }
412
413    #[test]
414    fn origin_match_classifies_marker_states() {
415        let tmp = tempfile::tempdir().unwrap();
416        let sessions = tmp.path().join("sessions");
417        std::fs::create_dir_all(&sessions).unwrap();
418        let m = make_session_dir(&sessions, "match", Some("/wt/a"));
419        let x = make_session_dir(&sessions, "mismatch", Some("/wt/b"));
420        let n = make_session_dir(&sessions, "none", None);
421
422        assert_eq!(origin_match(&m, "/wt/a"), OriginMatch::Match);
423        assert_eq!(origin_match(&x, "/wt/a"), OriginMatch::Mismatch);
424        assert_eq!(origin_match(&n, "/wt/a"), OriginMatch::NoMarker);
425    }
426
427    #[test]
428    fn origin_match_unreadable_marker_is_mismatch_not_nomarker() {
429        // A present-but-unreadable marker must NOT bypass the cross-worktree
430        // guard. Make `origin` a directory so read_to_string fails with a
431        // non-NotFound error.
432        let tmp = tempfile::tempdir().unwrap();
433        let dir = tmp.path().join("sess-bad");
434        std::fs::create_dir_all(dir.join("origin")).unwrap();
435
436        assert_eq!(origin_match(&dir, "/wt/a"), OriginMatch::Mismatch);
437    }
438
439    /// `verify-start` used to pair `Credentials::load()` with
440    /// `config.server_url` directly, bypassing everything `resolve_credentials`
441    /// enforces. Since `.tracevault/config.toml` is TRACKED in user repos, a PR
442    /// that edited `server_url` made any reviewer running this command POST
443    /// their Keycloak access token to an arbitrary host.
444    ///
445    /// Going through `resolve_client` closes it by PRECEDENCE, which is stronger
446    /// than refusing: the credentials file's own URL outranks
447    /// `config.server_url`, so a committed config can no longer redirect the
448    /// token anywhere. Proven by pointing the saved login at a local one-shot
449    /// server and the config at a host that must never be contacted — if the
450    /// old code path were still in place, no request would arrive here at all.
451    #[tokio::test]
452    async fn a_committed_config_url_cannot_redirect_the_token() {
453        let _env_lock = crate::test_helpers::lock_env_mutation().await;
454        let home = tempfile::tempdir().unwrap();
455        let mut guard = crate::test_helpers::EnvVarGuard::new();
456        guard.set("XDG_CONFIG_HOME", home.path());
457        guard.remove("TRACEVAULT_API_KEY");
458        guard.remove("TRACEVAULT_SERVER_URL");
459
460        let (login_server, rx) = crate::test_helpers::spawn_seq(vec![
461            crate::test_helpers::http_json(
462                "200 OK",
463                r#"{"session_db_id":"22222222-2222-4222-8222-222222222222","event_db_id":null,"status":"ok"}"#,
464            ),
465        ]);
466
467        // The saved login is for `login_server`.
468        let creds_dir = home.path().join("tracevault");
469        std::fs::create_dir_all(&creds_dir).unwrap();
470        std::fs::write(
471            creds_dir.join("credentials.json"),
472            format!(
473                r#"{{"server_url":"{login_server}","email":"a@b.com","auth":{{
474                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
475                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
476            ),
477        )
478        .unwrap();
479
480        // The repo's committed config points somewhere else — the malicious PR.
481        let repo = tempfile::tempdir().unwrap();
482        let tv = repo.path().join(".tracevault");
483        std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
484        std::fs::write(
485            tv.join("config.toml"),
486            "repo_id = \"11111111-1111-4111-8111-111111111111\"\n\
487             server_url = \"https://attacker.invalid\"\n",
488        )
489        .unwrap();
490
491        open_verification_phase(repo.path(), repo.path(), Some("sess-1"))
492            .await
493            .expect("the event must go to the login's server");
494
495        let request = rx
496            .recv_timeout(crate::test_helpers::RECV_TIMEOUT)
497            .expect("no request reached the login's server — the config URL was used instead");
498        assert!(
499            request.contains("/api/v1/repos/11111111-1111-4111-8111-111111111111/stream"),
500            "unexpected request: {request}"
501        );
502        assert!(
503            request.contains("Bearer at"),
504            "must present the saved credential: {request}"
505        );
506    }
507
508    /// And it consults the credential/URL guard: a `TRACEVAULT_SERVER_URL`
509    /// pointing at another instance is refused before any request goes out,
510    /// rather than sending the saved token there.
511    #[tokio::test]
512    async fn a_mismatched_env_server_url_refuses_before_sending() {
513        let _env_lock = crate::test_helpers::lock_env_mutation().await;
514        let home = tempfile::tempdir().unwrap();
515        let mut guard = crate::test_helpers::EnvVarGuard::new();
516        guard.set("XDG_CONFIG_HOME", home.path());
517        guard.remove("TRACEVAULT_API_KEY");
518        guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
519
520        let creds_dir = home.path().join("tracevault");
521        std::fs::create_dir_all(&creds_dir).unwrap();
522        std::fs::write(
523            creds_dir.join("credentials.json"),
524            r#"{"server_url":"https://instance-b.example.com","email":"a@b.com","auth":{
525                "issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
526                "refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}"#,
527        )
528        .unwrap();
529
530        let repo = tempfile::tempdir().unwrap();
531        let tv = repo.path().join(".tracevault");
532        std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
533        std::fs::write(
534            tv.join("config.toml"),
535            "repo_id = \"11111111-1111-4111-8111-111111111111\"\n",
536        )
537        .unwrap();
538
539        let err = open_verification_phase(repo.path(), repo.path(), Some("sess-1"))
540            .await
541            .expect_err("a mismatched server URL must be refused");
542        assert!(
543            err.contains("instance-a.example.com") && err.contains("instance-b.example.com"),
544            "the refusal must name both URLs: {err}"
545        );
546        assert!(
547            err.contains("refusing to use the saved credentials"),
548            "must be the credential-scoping refusal, not a connection error: {err}"
549        );
550    }
551}