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        // Carry the tool like the hook stream path does — the server's
69        // `sessions.tool` column is NOT NULL, so sending None makes the
70        // session upsert fail. (The server also defends against this, but
71        // there's no reason to send a null here.)
72        tool: Some("claude-code".to_string()),
73        event_type: StreamEventType::ValidationWindowStart,
74        session_id: session_id.clone(),
75        timestamp: chrono::Utc::now(),
76        hook_event_name: None,
77        tool_name: None,
78        tool_use_id: None,
79        tool_input: None,
80        tool_response: None,
81        tool_is_error: None,
82        event_index: Some(event_index),
83        transcript_lines: None,
84        transcript_offset: None,
85        model: None,
86        cwd: Some(project_root.to_string_lossy().into_owned()),
87        final_stats: None,
88    };
89
90    let creds = Credentials::load().ok_or("Not logged in. Run `tracevault login` first.")?;
91    let server_url = config
92        .server_url
93        .as_deref()
94        .unwrap_or("https://tracevault.softwaremill.com");
95    let client = ApiClient::new(server_url, Some(&creds.token));
96
97    client
98        .stream_event(org_slug, repo_id, &event)
99        .await
100        .map_err(|e| format!("Failed to send validation window event: {e}"))?;
101
102    println!("✓ Validation window opened for session {session_id}");
103    println!("  Tool calls from this point are evaluated by validation_window-scoped policies.");
104    println!("  Run `tracevault validation-start` again to reset the window if needed.");
105
106    Ok(())
107}
108
109/// Return the most recently modified session directory under `sessions_dir`.
110fn find_latest_session(sessions_dir: &Path) -> Option<std::path::PathBuf> {
111    let entries = fs::read_dir(sessions_dir).ok()?;
112    entries
113        .filter_map(|e| e.ok())
114        .filter(|e| e.path().is_dir())
115        .max_by_key(|e| {
116            e.metadata()
117                .and_then(|m| m.modified())
118                .unwrap_or(std::time::SystemTime::UNIX_EPOCH)
119        })
120        .map(|e| e.path())
121}