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::api_client::ApiClient;
7use crate::config::TracevaultConfig;
8use crate::credentials::Credentials;
9
10/// Send a VerificationPhaseStart event to the server, recording the current
11/// timestamp as the start of the verification phase for this session.
12///
13/// Only the most recent call per session matters — calling this again simply
14/// moves the phase cursor forward, discarding events from the previous phase.
15///
16/// `project_root` — the git-resolved PRIMARY worktree root (from
17///   `paths::resolve_project_root`). Used to locate `.tracevault/`.
18/// `cwd` — the ACTUAL working directory where the CLI was invoked. Used to
19///   determine the current worktree toplevel for session disambiguation. In a
20///   sibling linked worktree `cwd` differs from `project_root`, so both are
21///   needed.
22/// `explicit_session_id` — when Some, targets that session directly.
23///   When None, the most recently modified session directory is used (suitable
24///   for single-agent setups; pass `--session-id` in multi-agent setups).
25pub async fn open_verification_phase(
26    project_root: &Path,
27    cwd: &Path,
28    explicit_session_id: Option<&str>,
29) -> Result<(), String> {
30    let config = TracevaultConfig::load(project_root)
31        .ok_or("TraceVault not initialized. Run `tracevault init` first.")?;
32
33    let org_slug = config
34        .org_slug
35        .as_deref()
36        .ok_or("No org_slug configured. Run `tracevault init`.")?;
37    let repo_id = config
38        .repo_id
39        .as_deref()
40        .ok_or("No repo_id configured. Run `tracevault init`.")?;
41
42    let sessions_dir = project_root.join(".tracevault").join("sessions");
43
44    let session_id = if let Some(id) = explicit_session_id {
45        // Verify the session directory exists when an explicit ID is given.
46        let dir = sessions_dir.join(id);
47        if !dir.is_dir() {
48            return Err(format!(
49                "Session directory not found: {}. Check the session ID.",
50                dir.display()
51            ));
52        }
53        let worktree_top = crate::paths::worktree_toplevel(cwd);
54        if origin_match(&dir, &worktree_top) == OriginMatch::Mismatch {
55            return Err(format!(
56                "Session {id} belongs to a different worktree (origin != {worktree_top}). \
57                 Run verify-start from that worktree, or omit --session-id."
58            ));
59        }
60        id.to_string()
61    } else {
62        // Auto-detect with worktree disambiguation.
63        //
64        // Since all worktrees share the primary `.tracevault/sessions/` dir, the
65        // most-recently-modified heuristic can silently open the wrong session.
66        // Instead:
67        //   1. Compute the current worktree toplevel.
68        //   2. Look for sessions whose `origin` marker matches it.
69        //   3. If exactly one matches → use it.
70        //      If multiple match → error asking for --session-id.
71        //      If none match (legacy sessions without marker) → fall back to
72        //      most-recently-modified + print a warning.
73        // Use `cwd` (the actual invocation directory), not `project_root`
74        // (the primary root), so that in a sibling worktree we correctly
75        // compare against the sibling's toplevel, not the primary's.
76        let worktree_top = crate::paths::worktree_toplevel(cwd);
77        let matching = find_sessions_by_origin(&sessions_dir, &worktree_top);
78
79        match matching.len() {
80            1 => matching[0]
81                .file_name()
82                .and_then(|n| n.to_str())
83                .ok_or("Could not determine session ID from origin-matched session")?
84                .to_string(),
85            n if n > 1 => {
86                let ids: Vec<String> = matching
87                    .iter()
88                    .filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(String::from))
89                    .collect();
90                return Err(format!(
91                    "Multiple sessions belong to this worktree ({worktree_top}): {}. \
92                     Pass --session-id to select one.",
93                    ids.join(", ")
94                ));
95            }
96            _ => {
97                let session_dir = find_latest_session(&sessions_dir).ok_or(
98                    "No active session found. Start a session by running an AI coding agent \
99                     first, or pass --session-id to target a specific session.",
100                )?;
101                let chosen = session_dir
102                    .file_name()
103                    .and_then(|n| n.to_str())
104                    .ok_or("Could not determine session ID")?
105                    .to_string();
106                eprintln!(
107                    "Warning: no session matched this worktree by origin marker — \
108                     falling back to most recently modified session ({chosen})."
109                );
110                chosen
111            }
112        }
113    };
114
115    let event = StreamEventRequest {
116        protocol_version: 2,
117        // Carry the tool like the hook stream path does — the server's
118        // `sessions.tool` column is NOT NULL, so sending None makes the
119        // session upsert fail. (The server also defends against this, but
120        // there's no reason to send a null here.)
121        tool: Some("claude-code".to_string()),
122        event_type: StreamEventType::VerificationPhaseStart,
123        session_id: session_id.clone(),
124        timestamp: chrono::Utc::now(),
125        hook_event_name: None,
126        tool_name: None,
127        tool_use_id: None,
128        tool_input: None,
129        tool_response: None,
130        tool_is_error: None,
131        // The server's VerificationPhaseStart handler only records a timestamp;
132        // it stores no event row, so neither an index nor a uuid is needed.
133        event_index: None,
134        event_uuid: None,
135        transcript_lines: None,
136        transcript_offset: None,
137        model: None,
138        // Record the ACTUAL invocation directory (the worktree where
139        // verify-start ran), matching the stream hook's `cwd` field. Using
140        // `project_root` here would record the primary checkout in a sibling
141        // worktree and misattribute the verification-phase metadata.
142        cwd: Some(cwd.to_string_lossy().into_owned()),
143        final_stats: None,
144        flow_id: None,
145        labels: None,
146        params: None,
147    };
148
149    let creds = Credentials::load().ok_or("Not logged in. Run `tracevault login` first.")?;
150    let server_url = config
151        .server_url
152        .as_deref()
153        .unwrap_or("https://tracevault.softwaremill.com");
154    let client = ApiClient::new(server_url, Some(&creds.token));
155
156    client
157        .stream_event(org_slug, repo_id, &event)
158        .await
159        .map_err(|e| format!("Failed to send verification phase event: {e}"))?;
160
161    println!("✓ Verification phase opened for session {session_id}");
162    println!("  Tool calls from this point are evaluated by verification_phase-scoped policies.");
163    println!("  Run `tracevault verify-start` again to reset the phase if needed.");
164
165    Ok(())
166}
167
168/// Return the most recently modified session directory under `sessions_dir`.
169fn find_latest_session(sessions_dir: &Path) -> Option<PathBuf> {
170    let entries = fs::read_dir(sessions_dir).ok()?;
171    entries
172        .filter_map(|e| e.ok())
173        .filter(|e| e.path().is_dir())
174        .max_by_key(|e| {
175            e.metadata()
176                .and_then(|m| m.modified())
177                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
178        })
179        .map(|e| e.path())
180}
181
182#[derive(Debug, PartialEq, Eq)]
183enum OriginMatch {
184    Match,
185    Mismatch,
186    NoMarker,
187}
188
189/// Classify a session's `origin` marker against the current worktree toplevel.
190fn origin_match(session_dir: &Path, worktree_top: &str) -> OriginMatch {
191    match fs::read_to_string(session_dir.join("origin")) {
192        Ok(s) if s.trim() == worktree_top => OriginMatch::Match,
193        Ok(_) => OriginMatch::Mismatch,
194        // Only a genuinely-absent marker is "legacy/no marker" (allowed).
195        Err(e) if e.kind() == std::io::ErrorKind::NotFound => OriginMatch::NoMarker,
196        // Marker present but unreadable: don't let it bypass the cross-worktree
197        // guard — treat it as a mismatch.
198        Err(_) => OriginMatch::Mismatch,
199    }
200}
201
202/// Return all session directories under `sessions_dir` whose `origin` marker
203/// file matches `worktree_top` (exact string match after trimming).
204fn find_sessions_by_origin(sessions_dir: &Path, worktree_top: &str) -> Vec<PathBuf> {
205    let Ok(entries) = fs::read_dir(sessions_dir) else {
206        return vec![];
207    };
208    entries
209        .filter_map(|e| e.ok())
210        .filter(|e| e.path().is_dir())
211        .filter(|e| {
212            let origin_file = e.path().join("origin");
213            fs::read_to_string(&origin_file)
214                .map(|s| s.trim() == worktree_top)
215                .unwrap_or(false)
216        })
217        .map(|e| e.path())
218        .collect()
219}
220
221// ---------------------------------------------------------------------------
222// Tests
223// ---------------------------------------------------------------------------
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228    use crate::test_helpers::{add_worktree, init_git_repo};
229
230    fn make_session_dir(sessions_dir: &Path, session_id: &str, origin: Option<&str>) -> PathBuf {
231        let dir = sessions_dir.join(session_id);
232        std::fs::create_dir_all(&dir).unwrap();
233        if let Some(o) = origin {
234            std::fs::write(dir.join("origin"), o).unwrap();
235        }
236        dir
237    }
238
239    // ── find_sessions_by_origin unit tests ───────────────────────────────────
240
241    #[test]
242    fn find_by_origin_matches_exact() {
243        let tmp = tempfile::tempdir().unwrap();
244        let sessions = tmp.path().join("sessions");
245        std::fs::create_dir_all(&sessions).unwrap();
246        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
247        make_session_dir(&sessions, "sess-b", Some("/repo/sibling"));
248        make_session_dir(&sessions, "sess-c", None); // legacy — no marker
249
250        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
251        assert_eq!(matched.len(), 1);
252        assert!(matched[0].ends_with("sess-a"));
253    }
254
255    #[test]
256    fn find_by_origin_no_match_returns_empty() {
257        let tmp = tempfile::tempdir().unwrap();
258        let sessions = tmp.path().join("sessions");
259        std::fs::create_dir_all(&sessions).unwrap();
260        make_session_dir(&sessions, "sess-a", Some("/repo/other"));
261        make_session_dir(&sessions, "sess-b", None);
262
263        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
264        assert!(matched.is_empty());
265    }
266
267    #[test]
268    fn find_by_origin_multiple_match() {
269        let tmp = tempfile::tempdir().unwrap();
270        let sessions = tmp.path().join("sessions");
271        std::fs::create_dir_all(&sessions).unwrap();
272        make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
273        make_session_dir(&sessions, "sess-b", Some("/repo/primary"));
274        make_session_dir(&sessions, "sess-c", Some("/other"));
275
276        let matched = find_sessions_by_origin(&sessions, "/repo/primary");
277        assert_eq!(matched.len(), 2);
278    }
279
280    // ── worktree-aware selection with real git worktrees ──────────────────────
281
282    /// check/verify-start from a sibling worktree resolves sessions_dir to the
283    /// primary `.tracevault/` directory, not the worktree dir.
284    #[test]
285    fn sessions_dir_from_sibling_worktree_is_under_primary() {
286        let tmp = tempfile::tempdir().unwrap();
287        let repo = tmp.path().join("repo");
288        let wt = tmp.path().join("sibling-wt");
289        std::fs::create_dir_all(&repo).unwrap();
290        init_git_repo(&repo);
291        add_worktree(&repo, &wt);
292
293        // When open_verification_phase is called with project_root from
294        // resolve_project_root(sibling_wt), the sessions_dir is primary.
295        let resolved = crate::paths::resolve_project_root(&wt);
296        assert_eq!(
297            resolved.root.canonicalize().unwrap(),
298            repo.canonicalize().unwrap(),
299            "sibling worktree must resolve to primary repo root"
300        );
301        let sessions_dir = resolved.root.join(".tracevault").join("sessions");
302        assert!(
303            sessions_dir.starts_with(&repo),
304            "sessions_dir must be under primary repo root"
305        );
306    }
307
308    /// Two sessions seeded under the shared sessions dir with different origins.
309    /// find_sessions_by_origin must return only the one matching the current
310    /// worktree toplevel.
311    #[test]
312    fn disambiguation_selects_current_worktree_session() {
313        let tmp = tempfile::tempdir().unwrap();
314        let repo = tmp.path().join("repo");
315        let wt = tmp.path().join("sibling-wt");
316        std::fs::create_dir_all(&repo).unwrap();
317        init_git_repo(&repo);
318        add_worktree(&repo, &wt);
319
320        let primary_top = repo.canonicalize().unwrap().to_string_lossy().into_owned();
321        let wt_top = wt.canonicalize().unwrap().to_string_lossy().into_owned();
322
323        let sessions_dir = repo.join(".tracevault").join("sessions");
324        std::fs::create_dir_all(&sessions_dir).unwrap();
325        make_session_dir(&sessions_dir, "session-primary", Some(&primary_top));
326        make_session_dir(&sessions_dir, "session-sibling", Some(&wt_top));
327
328        // From the sibling worktree, only session-sibling matches.
329        let matched = find_sessions_by_origin(&sessions_dir, &wt_top);
330        assert_eq!(matched.len(), 1);
331        assert!(
332            matched[0].ends_with("session-sibling"),
333            "expected session-sibling, got {:?}",
334            matched[0]
335        );
336
337        // From the primary, only session-primary matches.
338        let matched_primary = find_sessions_by_origin(&sessions_dir, &primary_top);
339        assert_eq!(matched_primary.len(), 1);
340        assert!(matched_primary[0].ends_with("session-primary"));
341    }
342
343    /// Two sessions with the same origin → caller gets 2 results and should
344    /// emit an error requesting --session-id.
345    #[test]
346    fn disambiguation_errors_on_multiple_matches() {
347        let tmp = tempfile::tempdir().unwrap();
348        let sessions = tmp.path().join("sessions");
349        std::fs::create_dir_all(&sessions).unwrap();
350        make_session_dir(&sessions, "sess-a", Some("/worktree/top"));
351        make_session_dir(&sessions, "sess-b", Some("/worktree/top"));
352
353        let matched = find_sessions_by_origin(&sessions, "/worktree/top");
354        assert_eq!(
355            matched.len(),
356            2,
357            "both sessions must be returned for disambiguation"
358        );
359    }
360
361    /// Legacy sessions with no origin markers → find_sessions_by_origin returns
362    /// empty; find_latest_session (fallback) still returns a session.
363    #[test]
364    fn disambiguation_fallback_when_no_markers() {
365        let tmp = tempfile::tempdir().unwrap();
366        let sessions = tmp.path().join("sessions");
367        std::fs::create_dir_all(&sessions).unwrap();
368        make_session_dir(&sessions, "sess-legacy-1", None);
369        make_session_dir(&sessions, "sess-legacy-2", None);
370
371        let matched = find_sessions_by_origin(&sessions, "/any/worktree");
372        assert!(matched.is_empty(), "no markers means no matches");
373
374        // Fallback must still find a session.
375        let latest = find_latest_session(&sessions);
376        assert!(latest.is_some(), "fallback must find a session");
377    }
378
379    /// Verify that `paths::worktree_toplevel(sibling_wt)` returns the sibling
380    /// worktree's path, NOT the primary repo path. This confirms that the `cwd`
381    /// parameter to `open_verification_phase` correctly identifies the invoking
382    /// worktree for disambiguation purposes.
383    #[test]
384    fn current_worktree_toplevel_returns_sibling_top_not_primary() {
385        let tmp = tempfile::tempdir().unwrap();
386        let repo = tmp.path().join("repo");
387        let wt = tmp.path().join("sibling-wt");
388        std::fs::create_dir_all(&repo).unwrap();
389        init_git_repo(&repo);
390        add_worktree(&repo, &wt);
391
392        let wt_top = crate::paths::worktree_toplevel(&wt);
393        let wt_canonical = wt.canonicalize().unwrap().to_string_lossy().into_owned();
394        let repo_canonical = repo.canonicalize().unwrap().to_string_lossy().into_owned();
395
396        assert_eq!(
397            wt_top, wt_canonical,
398            "current_worktree_toplevel from sibling must return sibling path"
399        );
400        assert_ne!(
401            wt_top, repo_canonical,
402            "current_worktree_toplevel from sibling must NOT return primary repo path"
403        );
404    }
405
406    #[test]
407    fn origin_match_classifies_marker_states() {
408        let tmp = tempfile::tempdir().unwrap();
409        let sessions = tmp.path().join("sessions");
410        std::fs::create_dir_all(&sessions).unwrap();
411        let m = make_session_dir(&sessions, "match", Some("/wt/a"));
412        let x = make_session_dir(&sessions, "mismatch", Some("/wt/b"));
413        let n = make_session_dir(&sessions, "none", None);
414
415        assert_eq!(origin_match(&m, "/wt/a"), OriginMatch::Match);
416        assert_eq!(origin_match(&x, "/wt/a"), OriginMatch::Mismatch);
417        assert_eq!(origin_match(&n, "/wt/a"), OriginMatch::NoMarker);
418    }
419
420    #[test]
421    fn origin_match_unreadable_marker_is_mismatch_not_nomarker() {
422        // A present-but-unreadable marker must NOT bypass the cross-worktree
423        // guard. Make `origin` a directory so read_to_string fails with a
424        // non-NotFound error.
425        let tmp = tempfile::tempdir().unwrap();
426        let dir = tmp.path().join("sess-bad");
427        std::fs::create_dir_all(dir.join("origin")).unwrap();
428
429        assert_eq!(origin_match(&dir, "/wt/a"), OriginMatch::Mismatch);
430    }
431}