Skip to main content

tracevault_cli/commands/
validation_window.rs

1use std::fs;
2use std::path::Path;
3
4use tracevault_core::streaming::{StreamEventRequest, StreamEventType};
5
6use crate::api_client::ApiClient;
7use crate::commands::stream::next_event_index;
8use crate::config::TracevaultConfig;
9use crate::credentials::Credentials;
10
11/// Send a ValidationWindowStart event to the server, recording the current
12/// timestamp as the start of the validation window for this session.
13///
14/// Only the most recent call per session matters — calling this again simply
15/// moves the window cursor forward, discarding events from the previous window.
16///
17/// `explicit_session_id` — when Some, targets that session directly.
18/// When None, the most recently modified session directory is used (suitable
19/// for single-agent setups; pass `--session-id` in multi-agent setups).
20pub async fn open_validation_window(
21    project_root: &Path,
22    explicit_session_id: Option<&str>,
23) -> Result<(), String> {
24    let config = TracevaultConfig::load(project_root)
25        .ok_or("TraceVault not initialized. Run `tracevault init` first.")?;
26
27    let org_slug = config
28        .org_slug
29        .as_deref()
30        .ok_or("No org_slug configured. Run `tracevault init`.")?;
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        id.to_string()
48    } else {
49        // Auto-detect: use the most recently modified session directory.
50        let session_dir = find_latest_session(&sessions_dir).ok_or(
51            "No active session found. Start a session by running an AI coding agent first, \
52             or pass --session-id to target a specific session.",
53        )?;
54        session_dir
55            .file_name()
56            .and_then(|n| n.to_str())
57            .ok_or("Could not determine session ID")?
58            .to_string()
59    };
60
61    let session_dir = sessions_dir.join(&session_id);
62    let counter_path = session_dir.join(".event_counter");
63    let event_index = next_event_index(&counter_path)
64        .map_err(|e| format!("Failed to read event counter: {e}"))?;
65
66    let event = StreamEventRequest {
67        protocol_version: 2,
68        tool: None,
69        event_type: StreamEventType::ValidationWindowStart,
70        session_id: session_id.clone(),
71        timestamp: chrono::Utc::now(),
72        hook_event_name: None,
73        tool_name: None,
74        tool_use_id: None,
75        tool_input: None,
76        tool_response: None,
77        tool_is_error: None,
78        event_index: Some(event_index),
79        transcript_lines: None,
80        transcript_offset: None,
81        model: None,
82        cwd: Some(project_root.to_string_lossy().into_owned()),
83        final_stats: None,
84    };
85
86    let creds = Credentials::load().ok_or("Not logged in. Run `tracevault login` first.")?;
87    let server_url = config
88        .server_url
89        .as_deref()
90        .unwrap_or("https://tracevault.softwaremill.com");
91    let client = ApiClient::new(server_url, Some(&creds.token));
92
93    client
94        .stream_event(org_slug, repo_id, &event)
95        .await
96        .map_err(|e| format!("Failed to send validation window event: {e}"))?;
97
98    println!("✓ Validation window opened for session {session_id}");
99    println!("  Tool calls from this point are evaluated by validation_window-scoped policies.");
100    println!("  Run `tracevault validation-start` again to reset the window if needed.");
101
102    Ok(())
103}
104
105/// Return the most recently modified session directory under `sessions_dir`.
106fn find_latest_session(sessions_dir: &Path) -> Option<std::path::PathBuf> {
107    let entries = fs::read_dir(sessions_dir).ok()?;
108    entries
109        .filter_map(|e| e.ok())
110        .filter(|e| e.path().is_dir())
111        .max_by_key(|e| {
112            e.metadata()
113                .and_then(|m| m.modified())
114                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
115        })
116        .map(|e| e.path())
117}