use std::fs;
use tempfile::TempDir;
use tracevault_cli::agent::Agent;
use tracevault_cli::commands::init::ClaudeSettingsTarget;
use tracevault_cli::config::UserContext;
fn tmp_git_repo() -> TempDir {
let tmp = TempDir::new().unwrap();
fs::create_dir(tmp.path().join(".git")).unwrap();
write_repo_config(tmp.path(), "api_key = \"tvk_test\"\n");
tmp
}
fn write_repo_config(root: &std::path::Path, content: &str) {
fs::create_dir_all(root.join(".tracevault")).unwrap();
fs::write(root.join(".tracevault/config.toml"), content).unwrap();
}
fn read_repo_config(root: &std::path::Path) -> String {
fs::read_to_string(root.join(".tracevault/config.toml")).unwrap()
}
fn real_git_repo_with_origin() -> TempDir {
let tmp = TempDir::new().unwrap();
for args in [
&["init", "-q"][..],
&["remote", "add", "origin", "git@github.com:org/repo.git"][..],
] {
let status = std::process::Command::new("git")
.args(args)
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success(), "git {args:?} failed");
}
tmp
}
fn run_init_isolated(
cwd: &std::path::Path,
home: &std::path::Path,
args: &[&str],
) -> std::process::Output {
std::process::Command::new(env!("CARGO_BIN_EXE_tracevault"))
.arg("init")
.args(args)
.env("HOME", home)
.env("XDG_CONFIG_HOME", home.join(".config"))
.env_remove("TRACEVAULT_API_KEY")
.env_remove("TRACEVAULT_SERVER_URL")
.current_dir(cwd)
.stdin(std::process::Stdio::null())
.output()
.expect("failed to run tracevault binary")
}
#[test]
fn init_without_credentials_fails_and_installs_nothing() {
let repo = real_git_repo_with_origin();
let home = TempDir::new().unwrap();
let output = run_init_isolated(repo.path(), home.path(), &["--claude-settings", "shared"]);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "stderr={stderr}");
assert!(stderr.contains("Not logged in"), "stderr={stderr}");
assert!(
stderr.contains("tracevault login --server-url <URL>"),
"must name the exact login command: {stderr}"
);
assert!(
stderr.contains("tracevault init"),
"must say to re-run init: {stderr}"
);
assert!(!repo.path().join(".tracevault").exists());
assert!(!repo.path().join(".claude").exists());
assert!(!repo.path().join(".gitignore").exists());
assert!(!repo.path().join(".git/hooks/pre-push").exists());
assert!(!repo.path().join(".git/hooks/post-commit").exists());
}
#[test]
fn init_without_credentials_names_the_known_server_url() {
let repo = real_git_repo_with_origin();
let home = TempDir::new().unwrap();
let output = run_init_isolated(
repo.path(),
home.path(),
&[
"--claude-settings",
"shared",
"--server-url",
"https://tv.example.com",
],
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "stderr={stderr}");
assert!(
stderr.contains("tracevault login --server-url https://tv.example.com"),
"stderr={stderr}"
);
assert!(!repo.path().join(".tracevault").exists());
}
#[test]
fn init_without_credentials_names_the_env_server_url() {
let repo = real_git_repo_with_origin();
let home = TempDir::new().unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_tracevault"))
.args(["init", "--claude-settings", "shared"])
.env("HOME", home.path())
.env("XDG_CONFIG_HOME", home.path().join(".config"))
.env_remove("TRACEVAULT_API_KEY")
.env("TRACEVAULT_SERVER_URL", "https://env.example.com")
.current_dir(repo.path())
.stdin(std::process::Stdio::null())
.output()
.expect("failed to run tracevault binary");
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "stderr={stderr}");
assert!(
stderr.contains("tracevault login --server-url https://env.example.com"),
"stderr={stderr}"
);
}
#[test]
fn init_without_credentials_leaves_existing_files_unchanged() {
let repo = real_git_repo_with_origin();
let home = TempDir::new().unwrap();
let files = [
(
".tracevault/config.toml",
"agent = \"claude-code\"\nrepo_id = \"r\"\n",
),
(".claude/settings.json", "{\"hooks\":{\"Stop\":[]}}\n"),
(".git/hooks/pre-push", "#!/bin/sh\necho mine\n"),
(".gitignore", "target/\n"),
];
for (path, content) in files {
let p = repo.path().join(path);
fs::create_dir_all(p.parent().unwrap()).unwrap();
fs::write(p, content).unwrap();
}
let output = run_init_isolated(repo.path(), home.path(), &["--claude-settings", "shared"]);
assert_eq!(output.status.code(), Some(1));
for (path, content) in files {
assert_eq!(
fs::read_to_string(repo.path().join(path)).unwrap(),
content,
"{path} must be untouched"
);
}
assert!(!repo.path().join(".git/hooks/post-commit").exists());
}
#[test]
fn init_error_exits_non_zero() {
let not_a_repo = TempDir::new().unwrap();
let home = TempDir::new().unwrap();
let output = std::process::Command::new(env!("CARGO_BIN_EXE_tracevault"))
.args(["init", "--claude-settings", "shared"])
.env("HOME", home.path())
.env("XDG_CONFIG_HOME", home.path().join(".config"))
.env("TRACEVAULT_API_KEY", "tvk_test")
.env_remove("TRACEVAULT_SERVER_URL")
.current_dir(not_a_repo.path())
.output()
.expect("failed to run tracevault binary");
let stderr = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "stderr={stderr}");
assert!(stderr.contains("Not a git repository"), "stderr={stderr}");
}
#[tokio::test]
async fn init_fails_without_git() {
let tmp = TempDir::new().unwrap();
let result = tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await;
assert!(result.is_err());
assert!(result
.unwrap_err()
.to_string()
.contains("Not a git repository"));
}
#[tokio::test]
async fn init_creates_tracevault_config() {
let tmp = tmp_git_repo();
let config_path = tmp.path().join(".tracevault").join("config.toml");
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
assert!(config_path.exists());
let content = fs::read_to_string(&config_path).unwrap();
assert!(content.contains("claude-code"));
}
#[tokio::test]
async fn init_creates_directory_structure() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
assert!(tmp.path().join(".tracevault").exists());
assert!(tmp.path().join(".tracevault/sessions").exists());
assert!(tmp.path().join(".tracevault/cache").exists());
let gitignore = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert!(gitignore.contains(".tracevault/"));
assert!(gitignore.contains(".claude/settings.json"));
assert!(!gitignore.contains(".claude/settings.local.json"));
}
#[tokio::test]
async fn init_installs_claude_hooks() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let settings_path = tmp.path().join(".claude/settings.json");
assert!(settings_path.exists());
let content = fs::read_to_string(&settings_path).unwrap();
let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
let hooks = settings.get("hooks").unwrap();
assert!(hooks.get("PreToolUse").is_some());
assert!(hooks.get("PostToolUse").is_some());
assert!(hooks.get("Notification").is_some());
}
#[tokio::test]
async fn init_installs_session_hooks() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let settings_path = tmp.path().join(".claude/settings.json");
assert!(settings_path.exists());
let content = fs::read_to_string(&settings_path).unwrap();
let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
let hooks = settings.get("hooks").unwrap();
assert!(
hooks.get("SessionStart").is_some(),
"missing SessionStart hook"
);
assert!(
hooks["SessionStart"].is_array(),
"SessionStart should be an array"
);
let session_start_entry = &hooks["SessionStart"][0];
let session_start_cmd = session_start_entry
.get("hooks")
.and_then(|h| h.get(0))
.and_then(|h| h.get("command"))
.and_then(|c| c.as_str());
assert_eq!(
session_start_cmd,
Some("tracevault session-start"),
"SessionStart hook should run 'tracevault session-start'"
);
assert!(
hooks.get("UserPromptSubmit").is_some(),
"missing UserPromptSubmit hook"
);
assert!(
hooks["UserPromptSubmit"].is_array(),
"UserPromptSubmit should be an array"
);
let user_prompt_entry = &hooks["UserPromptSubmit"][0];
let user_prompt_cmd = user_prompt_entry
.get("hooks")
.and_then(|h| h.get(0))
.and_then(|h| h.get("command"))
.and_then(|c| c.as_str());
assert_eq!(
user_prompt_cmd,
Some("tracevault user-prompt"),
"UserPromptSubmit hook should run 'tracevault user-prompt'"
);
}
#[tokio::test]
async fn init_merges_into_existing_settings() {
let tmp = tmp_git_repo();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
fs::write(claude_dir.join("settings.json"), r#"{"model": "opus"}"#).unwrap();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
assert!(settings.get("hooks").is_some());
assert_eq!(settings.get("model").unwrap(), "opus");
}
#[test]
fn tracevault_hooks_has_pre_post_and_notification() {
let hooks = tracevault_cli::commands::init::tracevault_hooks();
assert!(hooks.get("PreToolUse").is_some());
assert!(hooks.get("PostToolUse").is_some());
assert!(hooks.get("Notification").is_some());
assert_eq!(
hooks["SubagentStop"][0]["hooks"][0]["command"],
"tracevault stream --event subagent-stop"
);
assert_eq!(
hooks["SessionEnd"][0]["hooks"][0]["command"],
"tracevault stream --event session-end"
);
assert!(hooks.get("SessionStart").is_some());
assert!(hooks.get("UserPromptSubmit").is_some());
}
#[tokio::test]
async fn init_installs_git_pre_push_hook() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let hook_path = tmp.path().join(".git/hooks/pre-push");
assert!(hook_path.exists());
let content = fs::read_to_string(&hook_path).unwrap();
assert!(content.contains("#!/bin/sh"));
assert!(content.contains("# tracevault:enforce"));
assert!(content.contains("tracevault sync"));
assert!(content.contains("tracevault check"));
assert!(!content.contains("tracevault push"));
assert!(
content.contains("tracevault_prepush_stdin=$(cat)"),
"hook must capture git's pre-push stdin: {content}"
);
assert!(
content.contains("| tracevault check"),
"hook must pipe the captured stdin into `tracevault check`: {content}"
);
let status = std::process::Command::new("sh")
.arg("-n")
.arg(&hook_path)
.status()
.expect("sh available");
assert!(
status.success(),
"generated pre-push hook must be valid shell"
);
}
#[tokio::test]
async fn init_preserves_existing_pre_push_hook() {
let tmp = tmp_git_repo();
let hooks_dir = tmp.path().join(".git/hooks");
fs::create_dir_all(&hooks_dir).unwrap();
fs::write(
hooks_dir.join("pre-push"),
"#!/bin/sh\necho 'existing hook'\n",
)
.unwrap();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let content = fs::read_to_string(hooks_dir.join("pre-push")).unwrap();
assert!(content.contains("echo 'existing hook'"));
assert!(content.contains("# tracevault:enforce"));
assert!(content.contains("tracevault check"));
assert!(!content.contains("tracevault push"));
}
#[tokio::test]
async fn init_does_not_duplicate_hook_on_reinit() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let content = fs::read_to_string(tmp.path().join(".git/hooks/pre-push")).unwrap();
let marker_count = content.matches("# tracevault:enforce").count();
assert_eq!(
marker_count, 1,
"Marker should appear exactly once, found {marker_count}"
);
}
#[tokio::test]
async fn init_installs_post_commit_hook() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let hook_path = tmp.path().join(".git/hooks/post-commit");
assert!(hook_path.exists());
let content = fs::read_to_string(&hook_path).unwrap();
assert!(content.contains("#!/bin/sh"));
assert!(content.contains("# tracevault:post-commit"));
assert!(content.contains("tracevault commit-push 2>/dev/null &"));
}
#[tokio::test]
async fn init_does_not_duplicate_post_commit_hook_on_reinit() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let content = fs::read_to_string(tmp.path().join(".git/hooks/post-commit")).unwrap();
let marker_count = content.matches("# tracevault:post-commit").count();
assert_eq!(
marker_count, 1,
"Post-commit marker should appear exactly once, found {marker_count}"
);
}
#[tokio::test]
async fn init_local_target_writes_to_settings_local_json() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Local),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let local_path = tmp.path().join(".claude/settings.local.json");
let shared_path = tmp.path().join(".claude/settings.json");
assert!(local_path.exists(), "settings.local.json should exist");
assert!(
!shared_path.exists(),
"settings.json should not be created when local target chosen"
);
let content = fs::read_to_string(&local_path).unwrap();
let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
assert!(settings.get("hooks").is_some());
}
#[tokio::test]
async fn init_local_target_gitignores_settings_local_json() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Local),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let gitignore = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert!(gitignore.contains(".claude/settings.local.json"));
assert!(!gitignore.contains(".claude/settings.json"));
}
#[tokio::test]
async fn init_local_target_merges_into_existing_settings_local_json() {
let tmp = tmp_git_repo();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
fs::write(
claude_dir.join("settings.local.json"),
r#"{"model": "opus"}"#,
)
.unwrap();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Local),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let content = fs::read_to_string(claude_dir.join("settings.local.json")).unwrap();
let settings: serde_json::Value = serde_json::from_str(&content).unwrap();
assert!(settings.get("hooks").is_some());
assert_eq!(settings.get("model").unwrap(), "opus");
}
#[tokio::test]
async fn init_writes_server_url_to_config() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
Some("https://tv.example.com"),
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let config_path = tmp.path().join(".tracevault/config.toml");
let content = fs::read_to_string(&config_path).unwrap();
assert!(content.contains("server_url = \"https://tv.example.com\""));
}
#[tokio::test]
async fn init_no_gitignore_skips_gitignore_update() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
true,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let gitignore_path = tmp.path().join(".gitignore");
if gitignore_path.exists() {
let content = fs::read_to_string(&gitignore_path).unwrap();
assert!(
!content.contains(".tracevault/"),
".gitignore should not have been modified with --no-gitignore"
);
assert!(!content.contains(".claude/settings.json"));
}
assert!(tmp.path().join(".tracevault").exists());
assert!(tmp.path().join(".claude/settings.json").exists());
}
#[tokio::test]
async fn init_default_writes_user_context_true() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Toggle(true)),
Agent::ClaudeCode,
)
.await
.unwrap();
let config_path = tmp.path().join(".tracevault/config.toml");
let content = fs::read_to_string(&config_path).unwrap();
assert!(
content.contains("user_context = true"),
"expected user_context = true, got: {content}"
);
}
#[test]
fn cleanup_stale_gsd_registration_removes_tracker_and_inert_entries() {
let tmp = TempDir::new().unwrap();
let gsd_home = tmp.path().join(".gsd");
fs::create_dir_all(gsd_home.join("extensions").join("tracevault-tracker")).unwrap();
fs::write(
gsd_home.join("extensions").join("registry.json"),
r#"{"version":1,"entries":{"tracevault-tracker":{"id":"tracevault-tracker","enabled":true,"source":"user"},"tracevault":{"id":"tracevault","enabled":true,"source":"user"},"other-ext":{"id":"other-ext","enabled":true,"source":"bundled"}}}"#,
)
.unwrap();
tracevault_cli::commands::init::cleanup_stale_gsd_registration(&gsd_home).unwrap();
let reg: serde_json::Value = serde_json::from_str(
&fs::read_to_string(gsd_home.join("extensions").join("registry.json")).unwrap(),
)
.unwrap();
assert!(
reg["entries"].get("tracevault-tracker").is_none(),
"stale tracker entry removed"
);
assert!(
reg["entries"].get("tracevault").is_none(),
"stale inert tracevault registry entry removed (gsd install manages registration now)"
);
assert!(
!gsd_home
.join("extensions")
.join("tracevault-tracker")
.exists(),
"stale tracker dir removed"
);
assert!(
reg["entries"].get("other-ext").is_some(),
"other-ext should be preserved during cleanup"
);
assert_eq!(
reg["entries"]["other-ext"]["id"],
serde_json::json!("other-ext")
);
assert_eq!(
reg["entries"]["other-ext"]["enabled"],
serde_json::json!(true)
);
assert_eq!(
reg["entries"]["other-ext"]["source"],
serde_json::json!("bundled")
);
}
#[test]
fn cleanup_stale_gsd_registration_is_noop_when_registry_missing() {
let tmp = TempDir::new().unwrap();
let gsd_home = tmp.path().join(".gsd");
tracevault_cli::commands::init::cleanup_stale_gsd_registration(&gsd_home).unwrap();
assert!(!gsd_home.join("extensions").join("registry.json").exists());
}
#[test]
fn cleanup_stale_gsd_registration_skips_corrupt_registry_without_overwriting() {
let tmp = TempDir::new().unwrap();
let gsd_home = tmp.path().join(".gsd");
let ext_root = gsd_home.join("extensions");
fs::create_dir_all(&ext_root).unwrap();
let reg_path = ext_root.join("registry.json");
let tracker_dir = ext_root.join("tracevault-tracker");
fs::create_dir_all(&tracker_dir).unwrap();
let corrupt_content = "{ this is not json";
fs::write(®_path, corrupt_content).unwrap();
let result = tracevault_cli::commands::init::cleanup_stale_gsd_registration(&gsd_home);
assert!(
result.is_ok(),
"cleanup must not fail the install on a corrupt existing registry"
);
let content_after = fs::read_to_string(®_path).unwrap();
assert_eq!(
content_after, corrupt_content,
"corrupt registry.json must be left byte-for-byte unchanged"
);
assert!(
tracker_dir.exists(),
"a corrupt registry must be validated before any fs mutation — the \
stale tracker dir must NOT be removed (zero mutation under ~/.gsd)"
);
}
#[cfg(target_os = "linux")]
#[test]
fn init_gsd_repo_local_installs_extension_and_gitignores_gsd_dir() {
let repo = tmp_git_repo();
let home = TempDir::new().unwrap();
let bin = env!("CARGO_BIN_EXE_tracevault");
let output = std::process::Command::new(bin)
.args(["init", "--agent", "gsd"])
.env("HOME", home.path())
.env("XDG_CONFIG_HOME", home.path().join(".config"))
.current_dir(repo.path())
.output()
.expect("failed to run tracevault binary");
assert!(
output.status.success(),
"tracevault init --agent gsd should succeed (even if `gsd install` itself can't run); stdout={}\nstderr={}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let source_dir = home.path().join(".config/tracevault/gsd-extension");
assert!(source_dir.join("index.ts").exists());
assert!(source_dir.join("package.json").exists());
assert!(
source_dir.join("extension-manifest.json").exists(),
"extension-manifest.json is required for GSD to load the extension"
);
let gitignore = fs::read_to_string(repo.path().join(".gitignore")).unwrap();
assert!(gitignore.contains(".tracevault/"));
assert!(
gitignore.contains(".gsd/"),
"gsd's project-local install state must be gitignored: {gitignore}"
);
let blank_lines = gitignore.lines().filter(|l| l.is_empty()).count();
assert_eq!(
blank_lines, 1,
"expected exactly the one intentional separator blank line, got: {gitignore:?}"
);
}
#[tokio::test]
async fn init_opencode_repo_local_installs_plugin_and_gitignores_opencode_dir() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
None,
false,
Some(UserContext::Toggle(false)),
Agent::OpenCode,
)
.await
.unwrap();
let plugin_file = tmp.path().join(".opencode/plugins/tracevault.ts");
assert!(
plugin_file.exists(),
"opencode plugin must be installed as a flat .ts module: {}",
plugin_file.display()
);
let gitignore = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert!(gitignore.contains(".tracevault/"));
assert!(
gitignore.contains(".opencode/"),
"opencode plugin dir must be gitignored: {gitignore}"
);
}
#[tokio::test]
async fn init_explicit_user_context_path_written() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
Some(UserContext::Path("/tmp/my-context.json".to_string())),
Agent::ClaudeCode,
)
.await
.unwrap();
let config_path = tmp.path().join(".tracevault/config.toml");
let content = fs::read_to_string(&config_path).unwrap();
assert!(
content.contains("user_context = \"/tmp/my-context.json\""),
"expected explicit path, got: {content}"
);
}
fn real_git_repo_without_remote() -> TempDir {
let tmp = TempDir::new().unwrap();
let status = std::process::Command::new("git")
.args(["init", "-q"])
.current_dir(tmp.path())
.status()
.unwrap();
assert!(status.success(), "git init failed");
tmp
}
const TUNED_CONFIG: &str = "\
agent = \"claude-code\"
server_url = \"https://tv.example.com\"
api_key = \"tvk_tuned==\"
repo_id = \"11111111-1111-4111-8111-111111111111\"
user_context = \"/home/me/ctx.json\"
remote_id = \"22222222-2222-4222-8222-222222222222\"
codebase_name = \"org/repo\"
default_project = \"payments\"
future_setting = true
";
#[test]
fn init_rerun_without_flags_keeps_the_existing_config() {
let repo = real_git_repo_without_remote();
let home = TempDir::new().unwrap();
write_repo_config(repo.path(), TUNED_CONFIG);
let output = run_init_isolated(repo.path(), home.path(), &["--claude-settings", "shared"]);
assert!(
output.status.success(),
"init failed: {}",
String::from_utf8_lossy(&output.stderr)
);
assert_eq!(
read_repo_config(repo.path()),
format!("# TraceVault configuration\n{TUNED_CONFIG}")
);
}
#[test]
fn init_rerun_flags_override_only_their_own_fields() {
let repo = real_git_repo_without_remote();
let home = TempDir::new().unwrap();
write_repo_config(repo.path(), TUNED_CONFIG);
let output = run_init_isolated(
repo.path(),
home.path(),
&[
"--claude-settings",
"shared",
"--server-url",
"https://other.example.com",
"--no-user-context",
],
);
assert!(
output.status.success(),
"init failed: {}",
String::from_utf8_lossy(&output.stderr)
);
let expected = TUNED_CONFIG
.replace("https://tv.example.com", "https://other.example.com")
.replace(
"user_context = \"/home/me/ctx.json\"",
"user_context = false",
);
assert_eq!(
read_repo_config(repo.path()),
format!("# TraceVault configuration\n{expected}")
);
}
#[tokio::test]
async fn init_fills_only_missing_fields_with_defaults() {
let tmp = tmp_git_repo();
write_repo_config(
tmp.path(),
"api_key = \"tvk_test\"\ndefault_project = \"payments\"\n",
);
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
None,
Agent::ClaudeCode,
)
.await
.unwrap();
let cfg = tracevault_cli::config::TracevaultConfig::load(tmp.path()).unwrap();
assert_eq!(cfg.api_key.as_deref(), Some("tvk_test"));
assert_eq!(cfg.default_project.as_deref(), Some("payments"));
assert_eq!(cfg.agent, "claude-code");
assert!(matches!(cfg.user_context, Some(UserContext::Toggle(true))));
}
#[tokio::test]
async fn init_refuses_to_overwrite_a_malformed_config() {
let tmp = tmp_git_repo();
write_repo_config(tmp.path(), "api_key = \"tvk_test\"\nrepo_id = [unclosed\n");
let err = tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
Some(ClaudeSettingsTarget::Shared),
false,
None,
Agent::ClaudeCode,
)
.await
.expect_err("a malformed config must stop init");
assert!(err.to_string().contains(".tracevault/config.toml"), "{err}");
assert_eq!(
read_repo_config(tmp.path()),
"api_key = \"tvk_test\"\nrepo_id = [unclosed\n"
);
assert!(!tmp.path().join(".git/hooks/pre-push").exists());
}
#[tokio::test]
async fn init_amp_repo_local_installs_plugin_and_gitignores_its_dir() {
let tmp = tmp_git_repo();
tracevault_cli::commands::init::init_in_directory(
tmp.path(),
None,
None,
false,
Some(UserContext::Toggle(false)),
Agent::Amp,
)
.await
.unwrap();
let plugin_file = tmp.path().join(".amp/plugins/tracevault/index.ts");
assert_eq!(
fs::read_to_string(&plugin_file).unwrap(),
tracevault_cli::commands::init::AMP_PLUGIN_INDEX
);
let gitignore = fs::read_to_string(tmp.path().join(".gitignore")).unwrap();
assert!(gitignore.contains(".tracevault/"));
assert!(
gitignore.lines().any(|l| l == ".amp/plugins/tracevault/"),
"amp plugin dir must be gitignored: {gitignore}"
);
assert!(
!gitignore.lines().any(|l| l == ".amp/"),
"all of .amp/ must not be ignored: {gitignore}"
);
assert!(tmp.path().join(".git/hooks/pre-push").exists());
assert!(tmp.path().join(".git/hooks/post-commit").exists());
}
#[test]
fn init_amp_rejects_claude_settings() {
let err = tracevault_cli::commands::init::validate_init_flags(Agent::Amp, true).unwrap_err();
assert!(err.contains("--claude-settings"), "{err}");
assert!(tracevault_cli::commands::init::validate_init_flags(Agent::Amp, false).is_ok());
}
fn run_global_amp_init(home: &std::path::Path, xdg: Option<&str>) -> std::process::Output {
let mut cmd = std::process::Command::new(env!("CARGO_BIN_EXE_tracevault"));
cmd.args(["init", "--global", "--agent", "amp"])
.env("HOME", home)
.env_remove("XDG_CONFIG_HOME")
.env_remove("TRACEVAULT_API_KEY")
.env_remove("TRACEVAULT_SERVER_URL")
.current_dir(home)
.stdin(std::process::Stdio::null());
if let Some(xdg) = xdg {
cmd.env("XDG_CONFIG_HOME", xdg);
}
cmd.output().expect("failed to run tracevault binary")
}
#[cfg(unix)]
#[test]
fn init_global_amp_writes_to_xdg_config_home() {
let home = TempDir::new().unwrap();
let xdg = home.path().join("xdg");
let output = run_global_amp_init(home.path(), Some(xdg.to_str().unwrap()));
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(
output.status.success(),
"stdout={stdout} stderr={}",
String::from_utf8_lossy(&output.stderr)
);
let plugin = xdg.join("amp/plugins/tracevault/index.ts");
assert_eq!(
fs::read_to_string(&plugin).unwrap(),
tracevault_cli::commands::init::AMP_PLUGIN_INDEX
);
assert!(!home.path().join(".config/amp").exists());
assert!(stdout.contains(&plugin.display().to_string()), "{stdout}");
assert!(stdout.contains("ALL Amp sessions"), "{stdout}");
assert!(stdout.contains("--plugin-ready-timeout"), "{stdout}");
assert!(stdout.contains("stores them in the thread"), "{stdout}");
}
#[cfg(unix)]
#[test]
fn init_global_amp_defaults_to_dot_config() {
for xdg in [None, Some("relative/dir")] {
let home = TempDir::new().unwrap();
let output = run_global_amp_init(home.path(), xdg);
assert!(
output.status.success(),
"{xdg:?}: stderr={}",
String::from_utf8_lossy(&output.stderr)
);
let plugin = home.path().join(".config/amp/plugins/tracevault/index.ts");
assert!(plugin.exists(), "{xdg:?}: {} missing", plugin.display());
}
}