use std::fs;
use std::path::{Path, PathBuf};
use tracevault_protocol::streaming::{StreamEventRequest, StreamEventType};
use crate::config::TracevaultConfig;
pub async fn open_verification_phase(
project_root: &Path,
cwd: &Path,
explicit_session_id: Option<&str>,
env_session_id: Option<&str>,
) -> Result<(), String> {
let config = TracevaultConfig::try_load(project_root)
.map_err(|e| format!("malformed .tracevault/config.toml: {e}"))?;
let sessions_dir = project_root.join(".tracevault").join("sessions");
let worktree_top = crate::paths::worktree_toplevel(cwd);
let invoking = explicit_session_id
.is_none()
.then(|| invoking_session(&sessions_dir, &worktree_top, env_session_id))
.flatten();
let session_id = if let Some(id) = invoking {
id
} else if let Some(id) = explicit_session_id {
let dir = sessions_dir.join(id);
if !dir.is_dir() {
return Err(format!(
"Session directory not found: {}. Check the session ID.",
dir.display()
));
}
if origin_match(&dir, &worktree_top) == OriginMatch::Mismatch {
return Err(format!(
"Session {id} belongs to a different worktree (origin != {worktree_top}). \
Run verify-start from that worktree, or omit --session-id."
));
}
id.to_string()
} else {
let matching = find_sessions_by_origin(&sessions_dir, &worktree_top);
match matching.len() {
1 => matching[0]
.file_name()
.and_then(|n| n.to_str())
.ok_or("Could not determine session ID from origin-matched session")?
.to_string(),
n if n > 1 => {
let ids: Vec<String> = matching
.iter()
.filter_map(|p| p.file_name().and_then(|n| n.to_str()).map(String::from))
.collect();
return Err(format!(
"Multiple sessions belong to this worktree ({worktree_top}): {}. \
Pass --session-id to select one, or run verify-start from the agent \
session itself (it reads $TRACEVAULT_SESSION_ID, or $AMP_CURRENT_THREAD_ID in Amp).",
ids.join(", ")
));
}
_ => {
let session_dir = find_latest_session(&sessions_dir, &worktree_top).ok_or(
"No active session found for this worktree. Start a session by running an \
AI coding agent here first, or pass --session-id to target a specific session.",
)?;
let chosen = session_dir
.file_name()
.and_then(|n| n.to_str())
.ok_or("Could not determine session ID")?
.to_string();
eprintln!(
"Warning: no session matched this worktree by origin marker — \
falling back to most recently modified session ({chosen})."
);
chosen
}
}
};
let event = StreamEventRequest {
protocol_version: 2,
tool: Some("claude-code".to_string()),
event_type: StreamEventType::VerificationPhaseStart,
session_id: session_id.clone(),
timestamp: chrono::Utc::now(),
hook_event_name: None,
tool_name: None,
tool_use_id: None,
tool_input: None,
tool_response: None,
tool_is_error: None,
event_index: None,
event_uuid: None,
transcript_lines: None,
transcript_offset: None,
model: None,
cwd: Some(cwd.to_string_lossy().into_owned()),
final_stats: None,
flow_id: None,
labels: None,
params: None,
billing_mode: None,
};
let client = crate::api_client::resolve_client(project_root).map_err(|e| e.to_string())?;
let state = crate::session_state::load(&session_id);
let binding = crate::resolution::recorded_session_binding(
&sessions_dir.join(&session_id),
&state,
config
.as_ref()
.and_then(crate::resolution::binding_from_config),
crate::user_default::load(),
);
let repo_id = binding
.ok_or_else(|| {
format!(
"No repo resolved for session {session_id}: it is not bound with \
`tracevault repo switch` and no repo_id is configured, so its tool events \
are not sent to any repo. Run `tracevault repo switch <path>` or \
`tracevault init`."
)
})?
.repo_id;
client
.stream_event(&repo_id, &event)
.await
.map_err(|e| format!("Failed to send verification phase event: {e}"))?;
println!("✓ Verification phase opened for session {session_id}");
println!(" Tool calls from this point are evaluated by verification_phase-scoped policies.");
println!(" Run `tracevault verify-start` again to reset the phase if needed.");
Ok(())
}
fn invoking_session(
sessions_dir: &Path,
worktree_top: &str,
env_session_id: Option<&str>,
) -> Option<String> {
let id = env_session_id.filter(|s| crate::session_state::is_safe_session_id(s))?;
let dir = sessions_dir.join(id);
(dir.is_dir() && origin_match(&dir, worktree_top) != OriginMatch::Mismatch)
.then(|| id.to_string())
}
fn find_latest_session(sessions_dir: &Path, worktree_top: &str) -> Option<PathBuf> {
let entries = fs::read_dir(sessions_dir).ok()?;
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().is_dir())
.filter(|e| origin_match(&e.path(), worktree_top) != OriginMatch::Mismatch)
.max_by_key(|e| {
e.metadata()
.and_then(|m| m.modified())
.unwrap_or(std::time::SystemTime::UNIX_EPOCH)
})
.map(|e| e.path())
}
#[derive(Debug, PartialEq, Eq)]
enum OriginMatch {
Match,
Mismatch,
NoMarker,
}
fn origin_match(session_dir: &Path, worktree_top: &str) -> OriginMatch {
match fs::read_to_string(session_dir.join("origin")) {
Ok(s) if s.trim() == worktree_top => OriginMatch::Match,
Ok(_) => OriginMatch::Mismatch,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => OriginMatch::NoMarker,
Err(_) => OriginMatch::Mismatch,
}
}
fn find_sessions_by_origin(sessions_dir: &Path, worktree_top: &str) -> Vec<PathBuf> {
let Ok(entries) = fs::read_dir(sessions_dir) else {
return vec![];
};
entries
.filter_map(|e| e.ok())
.filter(|e| e.path().is_dir())
.filter(|e| {
let origin_file = e.path().join("origin");
fs::read_to_string(&origin_file)
.map(|s| s.trim() == worktree_top)
.unwrap_or(false)
})
.map(|e| e.path())
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_helpers::{add_worktree, init_git_repo};
fn make_session_dir(sessions_dir: &Path, session_id: &str, origin: Option<&str>) -> PathBuf {
let dir = sessions_dir.join(session_id);
std::fs::create_dir_all(&dir).unwrap();
if let Some(o) = origin {
std::fs::write(dir.join("origin"), o).unwrap();
}
dir
}
#[test]
fn find_by_origin_matches_exact() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
make_session_dir(&sessions, "sess-b", Some("/repo/sibling"));
make_session_dir(&sessions, "sess-c", None);
let matched = find_sessions_by_origin(&sessions, "/repo/primary");
assert_eq!(matched.len(), 1);
assert!(matched[0].ends_with("sess-a"));
}
#[test]
fn find_by_origin_no_match_returns_empty() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
make_session_dir(&sessions, "sess-a", Some("/repo/other"));
make_session_dir(&sessions, "sess-b", None);
let matched = find_sessions_by_origin(&sessions, "/repo/primary");
assert!(matched.is_empty());
}
#[test]
fn find_by_origin_multiple_match() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
make_session_dir(&sessions, "sess-a", Some("/repo/primary"));
make_session_dir(&sessions, "sess-b", Some("/repo/primary"));
make_session_dir(&sessions, "sess-c", Some("/other"));
let matched = find_sessions_by_origin(&sessions, "/repo/primary");
assert_eq!(matched.len(), 2);
}
#[test]
fn sessions_dir_from_sibling_worktree_is_under_primary() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let wt = tmp.path().join("sibling-wt");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
add_worktree(&repo, &wt);
let resolved = crate::paths::resolve_project_root(&wt);
assert_eq!(
resolved.root.canonicalize().unwrap(),
repo.canonicalize().unwrap(),
"sibling worktree must resolve to primary repo root"
);
let sessions_dir = resolved.root.join(".tracevault").join("sessions");
assert!(
sessions_dir.starts_with(&repo),
"sessions_dir must be under primary repo root"
);
}
#[test]
fn disambiguation_selects_current_worktree_session() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let wt = tmp.path().join("sibling-wt");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
add_worktree(&repo, &wt);
let primary_top = repo.canonicalize().unwrap().to_string_lossy().into_owned();
let wt_top = wt.canonicalize().unwrap().to_string_lossy().into_owned();
let sessions_dir = repo.join(".tracevault").join("sessions");
std::fs::create_dir_all(&sessions_dir).unwrap();
make_session_dir(&sessions_dir, "session-primary", Some(&primary_top));
make_session_dir(&sessions_dir, "session-sibling", Some(&wt_top));
let matched = find_sessions_by_origin(&sessions_dir, &wt_top);
assert_eq!(matched.len(), 1);
assert!(
matched[0].ends_with("session-sibling"),
"expected session-sibling, got {:?}",
matched[0]
);
let matched_primary = find_sessions_by_origin(&sessions_dir, &primary_top);
assert_eq!(matched_primary.len(), 1);
assert!(matched_primary[0].ends_with("session-primary"));
}
#[test]
fn disambiguation_errors_on_multiple_matches() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
make_session_dir(&sessions, "sess-a", Some("/worktree/top"));
make_session_dir(&sessions, "sess-b", Some("/worktree/top"));
let matched = find_sessions_by_origin(&sessions, "/worktree/top");
assert_eq!(
matched.len(),
2,
"both sessions must be returned for disambiguation"
);
}
#[test]
fn disambiguation_fallback_when_no_markers() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
make_session_dir(&sessions, "sess-legacy-1", None);
make_session_dir(&sessions, "sess-legacy-2", None);
let matched = find_sessions_by_origin(&sessions, "/any/worktree");
assert!(matched.is_empty(), "no markers means no matches");
let latest = find_latest_session(&sessions, "/any/worktree");
assert!(latest.is_some(), "fallback must find a session");
}
#[test]
fn fallback_never_picks_another_worktrees_session() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
make_session_dir(&sessions, "sess-legacy", None);
make_session_dir(&sessions, "sess-elsewhere", Some("/wt/b"));
let latest = find_latest_session(&sessions, "/wt/a").unwrap();
assert!(latest.ends_with("sess-legacy"), "{}", latest.display());
let only_elsewhere = tmp.path().join("only-elsewhere");
make_session_dir(&only_elsewhere, "sess-elsewhere", Some("/wt/b"));
assert_eq!(find_latest_session(&only_elsewhere, "/wt/a"), None);
}
#[test]
fn current_worktree_toplevel_returns_sibling_top_not_primary() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let wt = tmp.path().join("sibling-wt");
std::fs::create_dir_all(&repo).unwrap();
init_git_repo(&repo);
add_worktree(&repo, &wt);
let wt_top = crate::paths::worktree_toplevel(&wt);
let wt_canonical = wt.canonicalize().unwrap().to_string_lossy().into_owned();
let repo_canonical = repo.canonicalize().unwrap().to_string_lossy().into_owned();
assert_eq!(
wt_top, wt_canonical,
"current_worktree_toplevel from sibling must return sibling path"
);
assert_ne!(
wt_top, repo_canonical,
"current_worktree_toplevel from sibling must NOT return primary repo path"
);
}
#[test]
fn origin_match_classifies_marker_states() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
std::fs::create_dir_all(&sessions).unwrap();
let m = make_session_dir(&sessions, "match", Some("/wt/a"));
let x = make_session_dir(&sessions, "mismatch", Some("/wt/b"));
let n = make_session_dir(&sessions, "none", None);
assert_eq!(origin_match(&m, "/wt/a"), OriginMatch::Match);
assert_eq!(origin_match(&x, "/wt/a"), OriginMatch::Mismatch);
assert_eq!(origin_match(&n, "/wt/a"), OriginMatch::NoMarker);
}
#[test]
fn origin_match_unreadable_marker_is_mismatch_not_nomarker() {
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("sess-bad");
std::fs::create_dir_all(dir.join("origin")).unwrap();
assert_eq!(origin_match(&dir, "/wt/a"), OriginMatch::Mismatch);
}
#[tokio::test]
async fn a_committed_config_url_cannot_redirect_the_token() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let home = tempfile::tempdir().unwrap();
let mut guard = crate::test_helpers::EnvVarGuard::new();
guard.set("XDG_CONFIG_HOME", home.path());
guard.set("XDG_STATE_HOME", home.path());
guard.remove("TRACEVAULT_API_KEY");
guard.remove("TRACEVAULT_SERVER_URL");
let (login_server, rx) = crate::test_helpers::spawn_seq(vec![
crate::test_helpers::http_json(
"200 OK",
r#"{"session_db_id":"22222222-2222-4222-8222-222222222222","event_db_id":null,"status":"ok"}"#,
),
]);
let creds_dir = home.path().join("tracevault");
std::fs::create_dir_all(&creds_dir).unwrap();
std::fs::write(
creds_dir.join("credentials.json"),
format!(
r#"{{"server_url":"{login_server}","email":"a@b.com","auth":{{
"issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
"refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
),
)
.unwrap();
let repo = tempfile::tempdir().unwrap();
let tv = repo.path().join(".tracevault");
std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
std::fs::write(
tv.join("config.toml"),
"repo_id = \"11111111-1111-4111-8111-111111111111\"\n\
server_url = \"https://attacker.invalid\"\n",
)
.unwrap();
open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
.await
.expect("the event must go to the login's server");
let request = rx
.recv_timeout(crate::test_helpers::RECV_TIMEOUT)
.expect("no request reached the login's server — the config URL was used instead");
assert!(
request.contains("/api/v1/repos/11111111-1111-4111-8111-111111111111/stream"),
"unexpected request: {request}"
);
assert!(
request.contains("Bearer at"),
"must present the saved credential: {request}"
);
}
#[tokio::test]
async fn a_mismatched_env_server_url_refuses_before_sending() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let home = tempfile::tempdir().unwrap();
let mut guard = crate::test_helpers::EnvVarGuard::new();
guard.set("XDG_CONFIG_HOME", home.path());
guard.set("XDG_STATE_HOME", home.path());
guard.remove("TRACEVAULT_API_KEY");
guard.set("TRACEVAULT_SERVER_URL", "https://instance-a.example.com");
let creds_dir = home.path().join("tracevault");
std::fs::create_dir_all(&creds_dir).unwrap();
std::fs::write(
creds_dir.join("credentials.json"),
r#"{"server_url":"https://instance-b.example.com","email":"a@b.com","auth":{
"issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
"refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}"#,
)
.unwrap();
let repo = tempfile::tempdir().unwrap();
let tv = repo.path().join(".tracevault");
std::fs::create_dir_all(tv.join("sessions").join("sess-1")).unwrap();
std::fs::write(
tv.join("config.toml"),
"repo_id = \"11111111-1111-4111-8111-111111111111\"\n",
)
.unwrap();
let err = open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
.await
.expect_err("a mismatched server URL must be refused");
assert!(
err.contains("instance-a.example.com") && err.contains("instance-b.example.com"),
"the refusal must name both URLs: {err}"
);
assert!(
err.contains("refusing to use the saved credentials"),
"must be the credential-scoping refusal, not a connection error: {err}"
);
}
const CONFIG_REPO: &str = "11111111-1111-4111-8111-111111111111";
const SWITCHED_REPO: &str = "44444444-4444-4444-8444-444444444444";
fn login_to_one_shot_server() -> (
crate::test_helpers::EnvVarGuard,
tempfile::TempDir,
std::sync::mpsc::Receiver<String>,
) {
let home = tempfile::tempdir().unwrap();
let mut guard = crate::test_helpers::EnvVarGuard::new();
guard.set("XDG_CONFIG_HOME", home.path());
guard.set("XDG_STATE_HOME", home.path());
guard.remove("TRACEVAULT_API_KEY");
guard.remove("TRACEVAULT_SERVER_URL");
let (server, rx) = crate::test_helpers::spawn_seq(vec![crate::test_helpers::http_json(
"200 OK",
r#"{"session_db_id":"22222222-2222-4222-8222-222222222222","event_db_id":null,"status":"ok"}"#,
)]);
let creds_dir = home.path().join("tracevault");
std::fs::create_dir_all(&creds_dir).unwrap();
std::fs::write(
creds_dir.join("credentials.json"),
format!(
r#"{{"server_url":"{server}","email":"a@b.com","auth":{{
"issuer":"https://idp.example.com/realms/v","client_id":"tracing-cli",
"refresh_token":"rt","access_token":"at","access_expires_at":9999999999}}}}"#
),
)
.unwrap();
(guard, home, rx)
}
fn checkout_with_sessions(ids: &[&str]) -> tempfile::TempDir {
let repo = tempfile::tempdir().unwrap();
let tv = repo.path().join(".tracevault");
let top = crate::paths::worktree_toplevel(repo.path());
for id in ids {
make_session_dir(&tv.join("sessions"), id, Some(&top));
}
std::fs::write(
tv.join("config.toml"),
format!("repo_id = \"{CONFIG_REPO}\"\n"),
)
.unwrap();
repo
}
fn bind_with_repo_switch(session_id: &str, repo_id: &str) {
let state = crate::session_state::SessionState {
active: Some(crate::session_state::RepoBinding {
repo_id: repo_id.into(),
git_url: None,
remote_id: None,
codebase_name: None,
updated_at: "t".into(),
}),
..Default::default()
};
crate::session_state::save(session_id, &state).unwrap();
}
#[tokio::test]
async fn a_session_bound_with_repo_switch_opens_its_window_under_the_bound_repo() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let (_guard, _home, rx) = login_to_one_shot_server();
let repo = checkout_with_sessions(&["sess-1"]);
bind_with_repo_switch("sess-1", SWITCHED_REPO);
open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
.await
.unwrap();
let request = rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap();
assert!(
request.contains(&format!("/api/v1/repos/{SWITCHED_REPO}/stream")),
"the window must go where the session's tool events go, not to config.repo_id: \
{request}"
);
}
#[tokio::test]
async fn the_invoking_session_is_used_when_several_share_the_worktree() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let (_guard, _home, rx) = login_to_one_shot_server();
let repo = checkout_with_sessions(&["sess-other", "sess-me"]);
bind_with_repo_switch("sess-me", SWITCHED_REPO);
open_verification_phase(repo.path(), repo.path(), None, Some("sess-me"))
.await
.expect("must not ask for --session-id");
let request = rx.recv_timeout(crate::test_helpers::RECV_TIMEOUT).unwrap();
assert!(
request.contains(&format!("/api/v1/repos/{SWITCHED_REPO}/stream")),
"{request}"
);
assert!(
request.contains(r#""session_id":"sess-me""#),
"must open the window for the invoking session: {request}"
);
}
#[tokio::test]
async fn an_unbound_session_without_config_is_refused_without_sending() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let (_guard, _home, rx) = login_to_one_shot_server();
let repo = tempfile::tempdir().unwrap();
let top = crate::paths::worktree_toplevel(repo.path());
make_session_dir(
&repo.path().join(".tracevault").join("sessions"),
"sess-1",
Some(&top),
);
let err = open_verification_phase(repo.path(), repo.path(), Some("sess-1"), None)
.await
.expect_err("no repo resolves for this session");
assert!(err.contains("No repo resolved for session sess-1"), "{err}");
assert!(
rx.recv_timeout(std::time::Duration::from_millis(300))
.is_err(),
"nothing may be sent"
);
}
#[test]
fn invoking_session_needs_a_session_dir_in_this_worktree() {
let tmp = tempfile::tempdir().unwrap();
let sessions = tmp.path().join("sessions");
make_session_dir(&sessions, "here", Some("/wt/a"));
make_session_dir(&sessions, "legacy", None);
make_session_dir(&sessions, "elsewhere", Some("/wt/b"));
assert_eq!(
invoking_session(&sessions, "/wt/a", Some("here")).as_deref(),
Some("here")
);
assert_eq!(
invoking_session(&sessions, "/wt/a", Some("legacy")).as_deref(),
Some("legacy")
);
assert_eq!(
invoking_session(&sessions, "/wt/a", Some("elsewhere")),
None
);
assert_eq!(invoking_session(&sessions, "/wt/a", Some("missing")), None);
assert_eq!(invoking_session(&sessions, "/wt/a", Some("../here")), None);
assert_eq!(invoking_session(&sessions, "/wt/a", None), None);
}
}