use crate::api_client::ApiClient;
use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
use crate::context::Context;
use crate::resolution::{git_remote_url, git_repo_name, RegistrationPlan};
use std::fs;
use std::io::{self, BufRead, IsTerminal, Write};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ClaudeSettingsTarget {
Shared,
Local,
}
impl ClaudeSettingsTarget {
pub fn filename(self) -> &'static str {
match self {
ClaudeSettingsTarget::Shared => "settings.json",
ClaudeSettingsTarget::Local => "settings.local.json",
}
}
pub fn gitignore_entry(self) -> &'static str {
match self {
ClaudeSettingsTarget::Shared => ".claude/settings.json",
ClaudeSettingsTarget::Local => ".claude/settings.local.json",
}
}
}
fn resolve_claude_target(
explicit: Option<ClaudeSettingsTarget>,
) -> io::Result<ClaudeSettingsTarget> {
if let Some(target) = explicit {
return Ok(target);
}
if !io::stdin().is_terminal() {
return Ok(ClaudeSettingsTarget::Shared);
}
let stdout = io::stdout();
let mut stdout = stdout.lock();
write!(
stdout,
"Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
)?;
stdout.flush()?;
let mut line = String::new();
io::stdin().lock().read_line(&mut line)?;
let answer = line.trim().to_lowercase();
Ok(match answer.as_str() {
"l" | "local" => ClaudeSettingsTarget::Local,
_ => ClaudeSettingsTarget::Shared,
})
}
fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
let output = std::process::Command::new("git")
.args(["rev-parse", "--git-dir", "--git-common-dir"])
.current_dir(dir)
.output()
.ok()?;
if !output.status.success() {
return None;
}
let stdout = String::from_utf8(output.stdout).ok()?;
let mut lines = stdout.lines();
let git_dir = lines.next()?.trim();
let git_common_dir = lines.next()?.trim();
let git_dir = dir.join(git_dir).canonicalize().ok()?;
let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
if git_dir == git_common_dir {
None } else {
git_common_dir.parent().map(Path::to_path_buf)
}
}
pub fn validate_init_flags(
agent: crate::agent::Agent,
claude_settings_set: bool,
) -> Result<(), String> {
if matches!(
agent,
crate::agent::Agent::Codex
| crate::agent::Agent::Gsd
| crate::agent::Agent::OpenCode
| crate::agent::Agent::Amp
) && claude_settings_set
{
return Err("--claude-settings only applies to --agent claude-code".to_string());
}
Ok(())
}
pub async fn init_in_directory(
project_root: &Path,
server_url: Option<&str>,
claude_settings: Option<ClaudeSettingsTarget>,
no_gitignore: bool,
user_context: Option<UserContext>,
agent: crate::agent::Agent,
) -> Result<String, io::Error> {
if !project_root.join(".git").exists() {
return Err(io::Error::new(
io::ErrorKind::NotFound,
"Not a git repository. Run 'git init' first.",
));
}
if let Some(primary) = linked_worktree_primary(project_root) {
return Err(io::Error::new(
io::ErrorKind::Unsupported,
format!(
"Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
cd there and run it again — all worktrees share the primary's .tracevault/.",
primary.display()
),
));
}
let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
then run `tracevault init` again."
),
)
})?;
let (resolved_url, resolved_credential) =
crate::credentials::resolve_credentials_quiet(project_root)
.map_err(|e| io::Error::other(e.to_string()))?;
let effective_url = server_url.map(String::from).or(resolved_url.clone());
if resolved_credential.is_none() {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
not_logged_in_message(effective_url.as_deref()),
));
}
let mut existing_config = existing_config;
if let (Some(cfg), Some(url)) = (existing_config.as_mut(), effective_url.as_deref()) {
if cfg.default_project.is_some() {
match credential_url_mismatch(resolved_url.as_deref(), server_url) {
Some(msg) => eprintln!(
"Warning: not migrating default_project: {msg}. Run `tracevault sync` \
once logged in to that server."
),
None => {
let client = ApiClient::with_credential(url, resolved_credential.clone());
migrate_config_in_init(cfg, &client).await?;
}
}
}
}
let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
{
crate::agent::Agent::ClaudeCode => {
let target = resolve_claude_target(claude_settings)?;
(Some(target), target.gitignore_entry().to_string())
}
crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
crate::agent::Agent::Amp => (None, AMP_PLUGIN_GITIGNORE_ENTRY.to_string()),
};
let config_dir = TracevaultConfig::config_dir(project_root);
fs::create_dir_all(&config_dir)?;
fs::create_dir_all(config_dir.join("sessions"))?;
fs::create_dir_all(config_dir.join("cache"))?;
TracevaultConfig::ensure_gitignore(&config_dir)?;
if !no_gitignore {
update_root_gitignore(project_root, &hook_gitignore_entry)?;
}
let remote_url = git_remote_url(project_root);
if remote_url.is_none() {
eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
}
let mut config = existing_config.unwrap_or_default();
if let Some(url) = server_url {
config.server_url = Some(url.to_string());
}
config.user_context = user_context
.or(config.user_context)
.or(Some(UserContext::Toggle(true)));
config.save(project_root)?;
let previous_repo_id = config
.repo_id
.as_deref()
.and_then(|id| id.parse::<uuid::Uuid>().ok());
match agent {
crate::agent::Agent::ClaudeCode => {
let target =
claude_target.expect("claude settings target is resolved for the Claude agent");
install_claude_hooks(project_root, target)?;
}
crate::agent::Agent::Codex => {
install_codex_hooks(project_root)?;
println!("{}", codex_hook_trust_notice());
}
crate::agent::Agent::Gsd => {
install_gsd_extension(Some(project_root))?;
}
crate::agent::Agent::OpenCode => {
install_opencode_plugin(Some(project_root))?;
}
crate::agent::Agent::Amp => {
let path = install_amp_plugin(Some(project_root))?;
println!("Installed the TraceVault Amp plugin in {}", path.display());
println!("{}", amp_headless_notice());
}
}
install_git_hook(project_root)?;
install_post_commit_hook(project_root)?;
let detected = crate::hooks::detect_tools(project_root);
for tool in &detected {
println!(" Detected: {}", tool.name());
}
if let (Some(url), Some(remote)) = (effective_url, remote_url) {
let client = ApiClient::with_credential(&url, resolved_credential);
let repo_name = git_repo_name(project_root);
let origin_url = remote.clone();
match crate::resolution::plan_registration(
&client,
&origin_url,
&repo_name,
previous_repo_id,
)
.await
{
Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
println!(
"Bound to existing repo {} (id: {repo_id}); not registering another record \
for this codebase",
codebase
.repos
.iter()
.find(|r| r.id == repo_id)
.map_or("", |r| r.name.as_str())
);
println!(
"{}",
crate::resolution::codebase_line(
codebase.remote.name.as_deref(),
&codebase.remote.normalized_url,
&codebase.remote.clone_status
)
);
persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
}
Ok(RegistrationPlan::Ambiguous(codebase)) => {
eprintln!(
"Warning: codebase {} already has {} repo records ({}) and none is named \
'{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
.tracevault/config.toml to the one this checkout belongs to.",
codebase.display_name(),
codebase.repos.len(),
codebase.repo_list()
);
}
Ok(RegistrationPlan::Register) => {
register_new_repo(&client, project_root, repo_name, origin_url).await;
}
Err(e) => {
eprintln!(
"Warning: could not check the server for an existing repo of this remote \
({e}); not registering. Run `tracevault init` again once the server is \
reachable."
);
}
}
}
Ok(hook_gitignore_entry)
}
async fn migrate_config_in_init(
config: &mut TracevaultConfig,
client: &ApiClient,
) -> Result<(), io::Error> {
use crate::commands::migrate::{migrate_default_project, migration_report, ResolveNameError};
match migrate_default_project(config, client).await {
Ok(migration) => {
if let Some(line) = migration_report(&migration) {
println!("{line}");
}
Ok(())
}
Err(ResolveNameError::Unreachable(e)) => {
eprintln!(
"Warning: could not migrate default_project (could not list projects: {e}); \
it stays unused for capture until `tracevault sync` succeeds."
);
Ok(())
}
Err(e @ ResolveNameError::Name(_)) => {
Err(io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))
}
}
}
pub async fn migrate_cwd_config(cwd: &Path) -> Result<(), io::Error> {
let root = crate::paths::resolve_project_root(cwd).root;
let Ok(Some(mut config)) = TracevaultConfig::try_load(&root) else {
return Ok(());
};
if config.default_project.is_none() {
return Ok(());
}
let Ok((Some(url), credential @ Some(_))) =
crate::credentials::resolve_credentials_quiet(&root)
else {
eprintln!(
"Warning: {} has a legacy default_project that needs a login to migrate; run \
`tracevault sync` there once logged in.",
TracevaultConfig::config_path(&root).display()
);
return Ok(());
};
let client = ApiClient::with_credential(&url, credential);
migrate_config_in_init(&mut config, &client).await?;
if config.default_project.is_none() {
config.save(&root)?;
}
Ok(())
}
fn credential_url_mismatch(resolved: Option<&str>, explicit: Option<&str>) -> Option<String> {
let env_key = std::env::var("TRACEVAULT_API_KEY")
.ok()
.is_some_and(|k| !k.trim().is_empty());
if env_key {
return None;
}
let (resolved, explicit) = (resolved?, explicit?);
(!crate::credentials::same_server(resolved, explicit)).then(|| {
format!(
"the credential in use is for {resolved}, not --server-url {explicit}; log in \
there first (`tracevault login --server-url {explicit}`) or omit --server-url"
)
})
}
#[derive(Debug)]
pub struct WorkspaceInit {
pub project_id: uuid::Uuid,
pub project_name: String,
pub config_path: PathBuf,
}
pub async fn init_workspace(
dir: &Path,
project_name: &str,
server_url: Option<&str>,
) -> Result<WorkspaceInit, io::Error> {
let resolved = crate::paths::resolve_project_root(dir);
if resolved.source == crate::paths::ProjectRootSource::Git {
let same = match (resolved.root.canonicalize(), dir.canonicalize()) {
(Ok(a), Ok(b)) => a == b,
_ => resolved.root == dir,
};
if !same {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"{} is inside the git repo {}; sessions here read that repo's \
.tracevault/config.toml, so a workspace binding here would never be used. \
Run `tracevault init --workspace` from the repo root or from a directory \
that is not inside a repo.",
dir.display(),
resolved.root.display()
),
));
}
}
let existing = TracevaultConfig::try_load(dir).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!(
"cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
then run `tracevault init --workspace` again."
),
)
})?;
let (resolved_url, credential) = crate::credentials::resolve_credentials_quiet(dir)
.map_err(|e| io::Error::other(e.to_string()))?;
if let Some(msg) = credential_url_mismatch(resolved_url.as_deref(), server_url) {
return Err(io::Error::new(io::ErrorKind::PermissionDenied, msg));
}
let url = server_url.map(String::from).or(resolved_url);
let (Some(url), Some(_)) = (url.as_deref(), credential.as_ref()) else {
return Err(io::Error::new(
io::ErrorKind::PermissionDenied,
format!(
"Not logged in. `init --workspace` resolves the project name on the server, \
so nothing was written.\nLog in, then run it again:\n\n \
tracevault login --server-url {}\n \
tracevault init --workspace --project {project_name}",
url.as_deref().unwrap_or("<URL>")
),
));
};
let client = ApiClient::with_credential(url, credential);
let project = crate::commands::migrate::resolve_project_by_name(&client, project_name)
.await
.map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
let config_dir = TracevaultConfig::config_dir(dir);
fs::create_dir_all(&config_dir)?;
TracevaultConfig::ensure_gitignore(&config_dir)?;
let mut config = existing.unwrap_or_default();
if let Some(url) = server_url {
config.server_url = Some(url.to_string());
}
config.project_id = Some(project.id.to_string());
config.project_name = Some(project.name.clone());
config.default_project = None;
config.save(dir)?;
Ok(WorkspaceInit {
project_id: project.id,
project_name: project.name,
config_path: TracevaultConfig::config_path(dir),
})
}
pub fn not_logged_in_message(url: Option<&str>) -> String {
let url = url.unwrap_or("<URL>");
format!(
"Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
would record nothing, so nothing was installed.\n\
Log in, then run init again:\n\
\n tracevault login --server-url {url}\n tracevault init\n\n\
(In CI, set TRACEVAULT_API_KEY instead of logging in.)"
)
}
pub(crate) fn persist_repo_binding(
project_root: &Path,
repo_id: uuid::Uuid,
codebase: Option<&crate::api_client::ResolveRemoteResponse>,
) -> bool {
let Some(mut cfg) = TracevaultConfig::load(project_root) else {
return false;
};
cfg.repo_id = Some(repo_id.to_string());
if let Some(remote) = codebase {
cfg.remote_id = Some(remote.remote_id.to_string());
cfg.codebase_name = remote.name.clone();
}
cfg.save(project_root).is_ok()
}
async fn register_new_repo(
client: &ApiClient,
project_root: &Path,
repo_name: String,
origin_url: String,
) {
match client
.register_repo(crate::api_client::RegisterRepoRequest {
repo_name,
github_url: Some(origin_url.clone()),
})
.await
{
Ok(resp) => {
println!("Repo registered on server (id: {})", resp.repo_id);
if let Some(mut cfg) = TracevaultConfig::load(project_root) {
cfg.repo_id = Some(resp.repo_id.to_string());
if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
println!(
"{}",
crate::resolution::codebase_line(
remote.name.as_deref(),
&remote.normalized_url,
&remote.clone_status
)
);
cfg.remote_id = Some(remote.remote_id.to_string());
cfg.codebase_name = remote.name.clone();
}
let _ = cfg.save(project_root);
}
}
Err(e) => {
eprintln!("{}", registration_failure_message(e.as_ref()));
}
}
}
fn registration_failure_message(err: &dyn std::error::Error) -> String {
let msg = err.to_string();
if msg.starts_with("Server returned 403 ") {
"Warning: you are not authorized to register this repo.".to_string()
} else if msg.starts_with("Server returned 404 ") {
"Warning: could not register repo on server (404) — this endpoint may not exist on \
this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
once the server is upgraded."
.to_string()
} else {
format!("Warning: could not register repo on server: {err}")
}
}
fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
let path = project_root.join(".gitignore");
let existing = if path.exists() {
fs::read_to_string(&path)?
} else {
String::new()
};
let needed: Vec<&str> = [".tracevault/", settings_entry]
.iter()
.copied()
.filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
.collect();
if needed.is_empty() {
return Ok(());
}
let mut content = existing;
if !content.is_empty() && !content.ends_with('\n') {
content.push('\n');
}
content.push_str("\n# TraceVault — local only, do not commit\n");
for entry in needed {
content.push_str(entry);
content.push('\n');
}
fs::write(path, content)
}
pub const PRE_PUSH_MARKER: &str = "# tracevault:enforce";
const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
let hooks_dir = project_root.join(".git/hooks");
fs::create_dir_all(&hooks_dir)?;
let hook_path = hooks_dir.join("pre-push");
let tracevault_block = format!(
"{PRE_PUSH_MARKER}\n\
# Capture git's pre-push ref list once; `check` uses it to determine\n\
# which files are being pushed.\n\
tracevault_prepush_stdin=$(cat)\n\
tracevault sync 2>/dev/null || true\n\
printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
);
if hook_path.exists() {
let existing = fs::read_to_string(&hook_path)?;
if existing.contains(PRE_PUSH_MARKER) {
return Ok(());
}
if existing.contains(OLD_HOOK_MARKER) {
let mut new_content = String::new();
let mut skip = false;
for line in existing.lines() {
if line.contains(OLD_HOOK_MARKER) {
skip = true;
continue;
}
if skip {
if line.starts_with("tracevault ") {
continue;
}
skip = false;
}
new_content.push_str(line);
new_content.push('\n');
}
if !new_content.ends_with('\n') {
new_content.push('\n');
}
new_content.push_str(&tracevault_block);
fs::write(&hook_path, new_content)?;
} else {
let mut content = existing;
if !content.ends_with('\n') {
content.push('\n');
}
content.push_str(&tracevault_block);
fs::write(&hook_path, content)?;
}
} else {
let content = format!("#!/bin/sh\n{tracevault_block}");
fs::write(&hook_path, content)?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&hook_path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&hook_path, perms)?;
}
Ok(())
}
pub const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
let hooks_dir = project_root.join(".git/hooks");
fs::create_dir_all(&hooks_dir)?;
let hook_path = hooks_dir.join("post-commit");
let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
if hook_path.exists() {
let existing = fs::read_to_string(&hook_path)?;
if existing.contains(POST_COMMIT_MARKER) {
return Ok(());
}
let mut content = existing;
if !content.ends_with('\n') {
content.push('\n');
}
content.push_str(&tracevault_block);
fs::write(&hook_path, content)?;
} else {
let content = format!("#!/bin/sh\n{tracevault_block}");
fs::write(&hook_path, content)?;
}
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
let mut perms = fs::metadata(&hook_path)?.permissions();
perms.set_mode(0o755);
fs::set_permissions(&hook_path, perms)?;
}
Ok(())
}
fn install_claude_hooks(
project_root: &Path,
target: ClaudeSettingsTarget,
) -> Result<(), io::Error> {
let claude_dir = project_root.join(".claude");
fs::create_dir_all(&claude_dir)?;
merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
}
pub fn tracevault_hooks() -> serde_json::Value {
serde_json::json!({
"PreToolUse": [{
"matcher": "Write|Edit|Bash",
"hooks": [{
"type": "command",
"command": "tracevault stream --event pre-tool-use",
"timeout": 10,
"statusMessage": "TraceVault: streaming pre-tool event"
}]
}],
"PostToolUse": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault stream --event post-tool-use",
"timeout": 10,
"statusMessage": "TraceVault: streaming post-tool event"
}]
}],
"Notification": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault stream --event notification",
"timeout": 10,
"statusMessage": "TraceVault: streaming notification"
}]
}],
"Stop": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault stream --event stop",
"timeout": 10,
"statusMessage": "TraceVault: finalizing session"
}]
}],
"SessionEnd": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault stream --event session-end",
"timeout": 10,
"statusMessage": "TraceVault: sending session cost"
}]
}],
"SubagentStop": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault stream --event subagent-stop",
"timeout": 10,
"statusMessage": "TraceVault: streaming subagent transcript"
}]
}],
"SessionStart": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault session-start",
"timeout": 10,
"statusMessage": "TraceVault: session start"
}]
}],
"UserPromptSubmit": [{
"matcher": "",
"hooks": [{
"type": "command",
"command": "tracevault user-prompt",
"timeout": 10,
"statusMessage": "TraceVault: policy reinforcement"
}]
}]
})
}
pub fn codex_hook_trust_notice() -> &'static str {
"Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
silently and no session is captured. Run `codex` once interactively in a repo and \
approve the hook-trust prompt; unattended runs (CI) can pass \
`--dangerously-bypass-hook-trust` instead."
}
pub fn codex_hooks() -> serde_json::Value {
serde_json::json!({
"SessionStart": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
}],
"UserPromptSubmit": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
}],
"PostToolUse": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
}],
"Stop": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
}]
})
}
const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
const GSD_EXT_MANIFEST_JSON: &str =
include_str!("../../assets/gsd-extension/extension-manifest.json");
fn gsd_extension_source_dir() -> io::Result<PathBuf> {
let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
let config_dir = config_dir
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
Ok(config_dir.join("tracevault").join("gsd-extension"))
}
pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
let home =
dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
let gsd_home = home.join(".gsd");
let source_dir = gsd_extension_source_dir()?;
fs::create_dir_all(&source_dir)?;
fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
fs::write(
source_dir.join("extension-manifest.json"),
GSD_EXT_MANIFEST_JSON,
)?;
if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
}
let local_flag = project_root.is_some();
let mut cmd = std::process::Command::new("gsd");
cmd.arg("install").arg(&source_dir);
if let Some(root) = project_root {
cmd.arg("-l");
cmd.current_dir(root);
}
let retry_hint = format!(
"gsd install {}{}",
source_dir.display(),
if local_flag { " -l" } else { "" }
);
match cmd.output() {
Ok(output) if output.status.success() => {
println!(
"TraceVault: installed and registered the GSD extension ({}).",
source_dir.display()
);
}
Ok(output) => {
eprintln!(
"TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
source_dir.display(),
String::from_utf8_lossy(&output.stderr),
);
}
Err(e) => {
eprintln!(
"TraceVault: installed the GSD extension source to {}, but could not run `gsd install` ({e}). Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
source_dir.display(),
);
}
}
Ok(())
}
const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
let plugins_dir = match project_root {
Some(root) => root.join(".opencode").join("plugins"),
None => {
let config_dir =
dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
config_dir
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"could not determine the config directory for the OpenCode plugin install",
)
})?
.join("opencode")
.join("plugins")
}
};
write_opencode_plugin_files(&plugins_dir)
}
fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
fs::create_dir_all(plugins_dir)?;
fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
Ok(())
}
pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");
const AMP_PLUGIN_GITIGNORE_ENTRY: &str = ".amp/plugins/tracevault/";
pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
let plugins_dir = match project_root {
Some(root) => root.join(".amp").join("plugins"),
None => amp_user_config_dir()
.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
"could not determine the config directory for the Amp plugin install",
)
})?
.join("plugins"),
};
let plugin_dir = plugins_dir.join("tracevault");
fs::create_dir_all(&plugin_dir)?;
let path = plugin_dir.join("index.ts");
fs::write(&path, AMP_PLUGIN_INDEX)?;
Ok(path)
}
fn amp_user_config_dir() -> Option<PathBuf> {
let xdg = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.filter(|p| p.is_absolute());
xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
.map(|c| c.join("amp"))
}
pub fn amp_headless_notice() -> &'static str {
"Amp loads the plugin in interactive sessions. For headless runs use \
`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
path), so allow what it needs up front.\n\
The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
ampcode.com, or exports it, can read them."
}
pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
let ext_root = gsd_home.join("extensions");
let reg_path = ext_root.join("registry.json");
let reg: Option<serde_json::Value> = if reg_path.exists() {
let content = fs::read_to_string(®_path)?;
let parsed: serde_json::Value = match serde_json::from_str(&content) {
Ok(v) => v,
Err(_) => return Ok(()), };
let corrupt = match parsed.as_object() {
None => true,
Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
};
if corrupt {
return Ok(()); }
Some(parsed)
} else {
None
};
let stale = ext_root.join("tracevault-tracker");
if stale.exists() {
fs::remove_dir_all(&stale)?;
}
if let Some(mut reg) = reg {
if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
let removed_tracker = entries.remove("tracevault-tracker").is_some();
let removed_inert = entries.remove("tracevault").is_some();
if removed_tracker || removed_inert {
let tmp = reg_path.with_extension("json.tmp");
fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
fs::rename(&tmp, ®_path)?;
}
}
}
Ok(())
}
fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
update_json_file(hooks_path, "its hooks", |root| {
merge_hooks(root, ours, hooks_path)
})
}
pub(crate) fn update_json_file(
path: &Path,
what: &str,
mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
) -> io::Result<()> {
if path
.components()
.any(|c| c == std::path::Component::ParentDir)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("refusing to use path with '..': {}", path.display()),
));
}
let target = match fs::symlink_metadata(path) {
Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
_ => path.to_path_buf(),
};
for _ in 0..3 {
let existing = read_existing(&target)?;
let mut root: serde_json::Value = match &existing {
Some((_, content)) => serde_json::from_str(content).map_err(|e| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("Failed to parse {}: {e}", path.display()),
)
})?,
None => serde_json::json!({}),
};
let before = existing.is_some().then(|| root.to_string());
mutate(&mut root)?;
if before.as_deref() == Some(root.to_string().as_str())
|| (existing.is_none() && root == serde_json::json!({}))
{
return Ok(());
}
let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
})?;
let tmp = unique_temp_sibling(&target);
let published = write_owner_only(&tmp, formatted.as_bytes())
.and_then(|()| {
match &existing {
Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
None => Ok(()),
}
})
.and_then(|()| {
let unchanged = read_existing(&target)?.map(|(_, c)| c)
== existing.as_ref().map(|(_, c)| c.clone());
if unchanged {
fs::rename(&tmp, &target).map(|()| true)
} else {
Ok(false)
}
});
match published {
Ok(true) => return Ok(()),
Ok(false) => {
let _ = fs::remove_file(&tmp);
}
Err(e) => {
let _ = fs::remove_file(&tmp);
return Err(e);
}
}
}
Err(io::Error::other(format!(
"{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
path.display()
)))
}
fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
let permissions = match fs::metadata(path) {
Ok(meta) => meta.permissions(),
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
Err(e) => return Err(e),
};
Ok(Some((permissions, fs::read_to_string(path)?)))
}
fn unique_temp_sibling(target: &Path) -> PathBuf {
static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.subsec_nanos())
.unwrap_or_default();
let mut name = target.file_name().unwrap_or_default().to_os_string();
name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
target.with_file_name(name)
}
fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
options.open(path)?.write_all(contents)
}
pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
let codex_dir = project_root.join(".codex");
fs::create_dir_all(&codex_dir)?;
merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
}
pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
fs::create_dir_all(codex_dir)?;
let base = codex_dir.canonicalize()?;
merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
append_workspace_md(&safe_join(&base, "AGENTS.md")?)
}
const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
A session started in a registered repo's checkout is bound to that repo automatically. To work
on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
one-off. Repos must already be registered with TraceVault. In a directory bound to a project
with `tracevault init --workspace`, sessions are recorded to that project without it, so
`repo switch` there is optional: it only adds the repo and its policies.
";
const PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS: &[&str] = &[
"\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
You may be running detached from any single repository. Before working on a repo, run
`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
already be registered with TraceVault.
",
"\
<!-- tracevault:workspace-mode -->
## TraceVault (workspace mode)
A session started in a registered repo's checkout is bound to that repo automatically. To work
on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
one-off. Repos must already be registered with TraceVault.
",
];
fn replace_managed_block(content: &str) -> String {
if content.contains(GLOBAL_CLAUDE_MD_BLOCK) {
return content.to_string();
}
PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS
.iter()
.find(|old| content.contains(*old))
.map_or_else(
|| content.to_string(),
|old| content.replacen(old, GLOBAL_CLAUDE_MD_BLOCK, 1),
)
}
fn append_workspace_md(md_path: &Path) -> io::Result<()> {
if md_path
.components()
.any(|c| c == std::path::Component::ParentDir)
{
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!("refusing to use path with '..': {}", md_path.display()),
));
}
let existing = if md_path.exists() {
fs::read_to_string(md_path)?
} else {
String::new()
};
if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
let replaced = replace_managed_block(&existing);
if replaced != existing {
fs::write(md_path, replaced)?;
}
return Ok(());
}
let mut content = existing;
if !content.is_empty() && !content.ends_with('\n') {
content.push('\n');
}
if !content.is_empty() {
content.push('\n');
}
content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
fs::write(md_path, content)
}
pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
let joined = base.join(name);
if joined.parent() != Some(base) {
return Err(io::Error::new(
io::ErrorKind::InvalidInput,
format!(
"refusing to access path outside {}: {}",
base.display(),
joined.display()
),
));
}
Ok(joined)
}
const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
hook.get("command")
.and_then(|c| c.as_str())
.is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
}
fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
let mut slot = None;
let mut kept = Vec::with_capacity(entries.len());
for mut entry in entries.drain(..) {
if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
let before = inner.len();
inner.retain(|hook| !is_tracevault_hook(hook));
if inner.is_empty() && before > 0 {
slot.get_or_insert(kept.len());
continue;
}
}
kept.push(entry);
}
*entries = kept;
slot
}
fn merge_hooks(
settings: &mut serde_json::Value,
ours: &serde_json::Value,
path: &Path,
) -> io::Result<()> {
let settings_obj = settings.as_object_mut().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("{} is not a JSON object", path.display()),
)
})?;
let hooks_value = settings_obj
.entry("hooks")
.or_insert_with(|| serde_json::json!({}));
let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidData,
format!("{} \"hooks\" key is not a JSON object", path.display()),
)
})?;
let empty = serde_json::Map::new();
let ours_obj = ours.as_object().unwrap_or(&empty);
for event in ours_obj.keys() {
if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
return Err(io::Error::new(
io::ErrorKind::InvalidData,
format!(
"{} \"hooks\".\"{event}\" is not a JSON array",
path.display()
),
));
}
}
let mut emptied = Vec::new();
for (event, value) in hooks_obj.iter_mut() {
let Some(existing) = value.as_array_mut() else {
continue;
};
let had_entries = !existing.is_empty();
let slot = strip_tracevault_hooks(existing);
let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
match our_entries {
Some(our_entries) => {
let at = slot.unwrap_or(existing.len());
existing.splice(at..at, our_entries.iter().cloned());
}
None if had_entries && existing.is_empty() => emptied.push(event.clone()),
None => {}
}
}
hooks_obj.retain(|event, _| !emptied.contains(event));
for (event, our_array) in ours_obj {
if !hooks_obj.contains_key(event) {
hooks_obj.insert(event.clone(), our_array.clone());
}
}
Ok(())
}
pub fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
let text = match fs::read_to_string(path) {
Ok(text) => text,
Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
Err(e) => return Err(e),
};
let settings: serde_json::Value =
serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
Ok(settings
.get("hooks")
.and_then(|h| h.as_object())
.into_iter()
.flat_map(|events| events.values())
.filter_map(|groups| groups.as_array())
.flatten()
.filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
.flatten()
.any(is_tracevault_hook))
}
pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
merge_hooks_into_file(path, &tracevault_hooks())
}
pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
fs::create_dir_all(claude_dir)?;
let base = claude_dir.canonicalize()?;
merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
}
pub fn write_global_user_config_in(
config_root: &Path,
requested: Option<UserContext>,
) -> io::Result<Option<PathBuf>> {
fs::create_dir_all(config_root)?;
let mut config = crate::config::try_load_user_config_in(config_root)
.ok()
.flatten()
.unwrap_or_default();
let user_context = requested
.or_else(|| config.user_context.clone())
.unwrap_or(UserContext::Toggle(true));
let active = user_context
.resolve()
.map(|_| user_context.path_in(config_root));
config.user_context = Some(user_context);
fs::write(user_config_path_in(config_root), config.to_toml())?;
if let Some(ref ctx_path) = active {
if !ctx_path.exists() {
Context::default().save_to(ctx_path)?;
}
}
Ok(active)
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::thread;
#[test]
fn codex_hook_trust_notice_explains_how_to_grant_trust() {
let notice = codex_hook_trust_notice();
assert!(
notice.contains("hook trust"),
"notice must name what is missing: {notice}"
);
assert!(
notice.contains("codex") && notice.contains("approve"),
"notice must tell the user to run codex and approve the prompt: {notice}"
);
assert!(
notice.contains("--dangerously-bypass-hook-trust"),
"notice must name the flag for unattended/CI runs: {notice}"
);
assert!(
notice.contains("silently"),
"notice must say the failure is silent, which is why it needs saying: {notice}"
);
}
fn spawn_once(response: String) -> String {
let response: &'static str = Box::leak(response.into_boxed_str());
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
thread::spawn(move || {
if let Ok((stream, _)) = listener.accept() {
let mut reader = BufReader::new(stream);
let mut request_line = String::new();
let _ = reader.read_line(&mut request_line);
let mut stream = reader.into_inner();
let _ = stream.write_all(response.as_bytes());
let _ = stream.flush();
}
});
format!("http://{addr}")
}
fn http_response(status: &str, body: &str) -> String {
format!(
"HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
status,
body.len(),
body
)
}
fn add_origin_remote(dir: &Path, url: &str) {
let ok = std::process::Command::new("git")
.args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
.status()
.expect("git remote add failed")
.success();
assert!(ok, "git remote add must succeed");
}
#[test]
fn linked_worktree_primary_detects_linked_and_primary() {
let tmp = tempfile::tempdir().unwrap();
let repo = tmp.path().join("repo");
let wt = tmp.path().join("linked-wt");
std::fs::create_dir_all(&repo).unwrap();
crate::test_helpers::init_git_repo(&repo);
crate::test_helpers::add_worktree(&repo, &wt);
assert!(
linked_worktree_primary(&repo).is_none(),
"primary checkout must not be flagged as a linked worktree"
);
let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
assert_eq!(
primary.canonicalize().unwrap(),
repo.canonicalize().unwrap(),
"must resolve to the primary repo root"
);
}
#[test]
fn linked_worktree_primary_none_for_non_git() {
let tmp = tempfile::tempdir().unwrap();
assert!(
linked_worktree_primary(tmp.path()).is_none(),
"a non-git directory is not a linked worktree"
);
}
fn entry_command(entry: &serde_json::Value) -> Option<&str> {
entry.get("hooks")?.get(0)?.get("command")?.as_str()
}
#[test]
fn merge_hooks_into_empty_settings_adds_all_our_events() {
let mut settings = serde_json::json!({});
let ours = tracevault_hooks();
merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
let hooks = settings.get("hooks").unwrap();
for event in [
"PreToolUse",
"PostToolUse",
"Notification",
"Stop",
"SessionEnd",
"SubagentStop",
"SessionStart",
"UserPromptSubmit",
] {
assert!(hooks.get(event).is_some(), "missing event {event}");
}
}
#[test]
fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
let mut settings = serde_json::json!({
"model": "opus",
"hooks": {
"PreToolUse": [{
"matcher": "",
"hooks": [{ "type": "command", "command": "my-own-hook" }]
}]
}
});
let ours = tracevault_hooks();
merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
assert_eq!(settings.get("model").unwrap(), "opus");
let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
assert_eq!(pre_tool_use.len(), 2);
let commands: Vec<&str> = pre_tool_use
.iter()
.map(|e| entry_command(e).unwrap())
.collect();
assert!(commands.contains(&"my-own-hook"));
assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
assert!(settings["hooks"]["SessionStart"].is_array());
}
#[test]
fn merge_hooks_is_idempotent() {
let mut settings = serde_json::json!({});
let ours = tracevault_hooks();
merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
for event in [
"PreToolUse",
"PostToolUse",
"Notification",
"Stop",
"SessionEnd",
"SubagentStop",
"SessionStart",
"UserPromptSubmit",
] {
let arr = settings["hooks"][event].as_array().unwrap();
assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
}
}
#[test]
fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
let mut settings = serde_json::json!({
"hooks": {
"PreToolUse": [{
"matcher": "Write|Edit|Bash",
"hooks": [
{ "type": "command", "command": "other", "timeout": 3 },
{ "type": "command", "command": "tracevault stream --event pre-tool-use" }
]
}]
}
});
merge_hooks(
&mut settings,
&tracevault_hooks(),
Path::new("settings.json"),
)
.unwrap();
let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
assert_eq!(
pre_tool_use[0],
serde_json::json!({
"matcher": "Write|Edit|Bash",
"hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
})
);
assert_eq!(
&pre_tool_use[1..],
tracevault_hooks()["PreToolUse"].as_array().unwrap()
);
}
fn stale_tracevault_hooks() -> serde_json::Value {
let entry = |matcher: &str, event: &str| {
serde_json::json!([{
"matcher": matcher,
"hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
}])
};
serde_json::json!({
"PreToolUse": entry("Write|Edit", "pre-tool-use"),
"PostToolUse": entry("", "post-tool-use"),
"Notification": entry("", "notification"),
"Stop": entry("", "stop"),
})
}
#[test]
fn merge_hooks_upgrades_stale_tracevault_entries() {
let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
merge_hooks(
&mut settings,
&tracevault_hooks(),
Path::new("settings.json"),
)
.unwrap();
assert_eq!(settings["hooks"], tracevault_hooks());
}
#[test]
fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
let mut settings = serde_json::json!({
"hooks": {
"PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
"SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
"Custom": "left alone"
}
});
merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
let hooks = settings["hooks"].as_object().unwrap();
assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
assert_eq!(hooks["Custom"], "left alone");
for (event, entries) in codex_hooks().as_object().unwrap() {
assert_eq!(&hooks[event], entries, "{event}");
}
}
#[test]
fn merge_hooks_rerun_keeps_our_entry_in_place() {
let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
settings["hooks"]["Stop"]
.as_array_mut()
.unwrap()
.push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
let before = settings.clone();
merge_hooks(
&mut settings,
&tracevault_hooks(),
Path::new("settings.json"),
)
.unwrap();
assert_eq!(settings.to_string(), before.to_string());
}
#[test]
fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
let foreign = serde_json::json!({
"matcher": "",
"hooks": [
{ "type": "command", "command": "tracevault-wrapper stream" },
{ "type": "command", "command": "echo tracevault stream" },
{ "type": "command", "command": " tracevault check" }
]
});
let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
merge_hooks(
&mut settings,
&tracevault_hooks(),
Path::new("settings.json"),
)
.unwrap();
assert_eq!(settings["hooks"]["Stop"][0], foreign);
assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
}
#[test]
fn merge_hooks_errors_on_non_object_top_level() {
let mut settings = serde_json::json!([1, 2, 3]);
let ours = tracevault_hooks();
let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("settings.json"));
}
#[test]
fn merge_hooks_errors_on_non_object_top_level_number() {
let mut settings = serde_json::json!(42);
let ours = tracevault_hooks();
let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
}
#[test]
fn merge_hooks_errors_on_non_object_hooks() {
let mut settings = serde_json::json!({ "hooks": "not-an-object" });
let ours = tracevault_hooks();
let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("hooks"));
}
#[test]
fn merge_hooks_errors_on_non_array_event_value() {
let mut settings = serde_json::json!({
"hooks": {
"PreToolUse": "not-an-array"
}
});
let ours = tracevault_hooks();
let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
assert!(err.to_string().contains("PreToolUse"));
}
#[test]
fn install_global_hooks_writes_settings_and_claude_md() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
install_global_hooks(&claude_dir).unwrap();
let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
assert!(settings["hooks"].get(event).is_some(), "missing {event}");
}
let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
}
#[test]
fn install_global_hooks_is_idempotent() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
install_global_hooks(&claude_dir).unwrap();
install_global_hooks(&claude_dir).unwrap();
let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
for event in [
"PreToolUse",
"PostToolUse",
"Notification",
"Stop",
"SessionEnd",
"SubagentStop",
"SessionStart",
"UserPromptSubmit",
] {
let arr = settings["hooks"][event].as_array().unwrap();
assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
}
let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
assert_eq!(
marker_count, 1,
"CLAUDE.md marker should appear exactly once"
);
}
#[test]
fn install_global_hooks_preserves_existing_claude_md_content() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
fs::write(
claude_dir.join("CLAUDE.md"),
"# My existing notes\nSome content.\n",
)
.unwrap();
install_global_hooks(&claude_dir).unwrap();
let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
assert!(claude_md.contains("# My existing notes"));
assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
}
#[test]
fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
install_global_hooks(&claude_dir).unwrap();
let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
assert!(settings["hooks"].get("SessionStart").is_some());
let leftover = fs::read_dir(&claude_dir)
.unwrap()
.filter_map(|e| e.ok())
.any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
assert!(
!leftover,
"no settings.json.tmp should remain after install"
);
}
#[test]
fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
let settings_path = claude_dir.join("settings.json");
let original = "[1, 2, 3]";
fs::write(&settings_path, original).unwrap();
let err = install_global_hooks(&claude_dir).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
let after = fs::read_to_string(&settings_path).unwrap();
assert_eq!(after, original);
let leftover = fs::read_dir(&claude_dir)
.unwrap()
.filter_map(|e| e.ok())
.any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
assert!(!leftover, "no tmp file should be left behind on error");
}
#[test]
fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
let settings_path = claude_dir.join("settings.json");
let original = r#"{"hooks": "oops"}"#;
fs::write(&settings_path, original).unwrap();
let err = install_global_hooks(&claude_dir).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
let after = fs::read_to_string(&settings_path).unwrap();
assert_eq!(after, original);
}
#[test]
fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
let settings_path = claude_dir.join("settings.json");
let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
fs::write(&settings_path, original).unwrap();
let err = install_global_hooks(&claude_dir).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData);
let after = fs::read_to_string(&settings_path).unwrap();
assert_eq!(after, original);
}
#[test]
fn safe_join_allows_direct_child_file() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let result = safe_join(base, "settings.json").unwrap();
assert_eq!(result.parent(), Some(base));
assert_eq!(result.file_name().unwrap(), "settings.json");
}
#[test]
fn safe_join_rejects_path_traversal() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let result = safe_join(base, "../evil");
assert!(result.is_err());
let err = result.unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
assert!(err.to_string().contains("refusing to access path outside"));
}
#[test]
fn safe_join_rejects_absolute_path() {
let tmp = tempfile::tempdir().unwrap();
let base = tmp.path();
let result = safe_join(base, "/etc/passwd");
assert!(result.is_err());
}
#[test]
fn write_global_user_config_enables_and_creates_context() {
let root = tempfile::tempdir().unwrap();
let active = write_global_user_config_in(root.path(), None).unwrap();
let cfg = crate::config::try_load_user_config_in(root.path())
.unwrap()
.unwrap();
assert_eq!(
cfg.user_context.unwrap().resolve_in(root.path()),
Some(crate::config::default_user_context_path_in(root.path()))
);
let ctx = crate::config::default_user_context_path_in(root.path());
assert_eq!(active, Some(ctx.clone()));
assert!(ctx.exists());
}
#[test]
fn write_global_user_config_can_disable() {
let root = tempfile::tempdir().unwrap();
let active = write_global_user_config_in(
root.path(),
Some(crate::config::UserContext::Toggle(false)),
)
.unwrap();
let cfg = crate::config::try_load_user_config_in(root.path())
.unwrap()
.unwrap();
assert!(matches!(
cfg.user_context,
Some(crate::config::UserContext::Toggle(false))
));
assert_eq!(active, None, "disabled → no active context path");
assert!(
!crate::config::default_user_context_path_in(root.path()).exists(),
"disabled user context must not create a context.json"
);
}
#[test]
fn write_global_user_config_custom_path_seeds_that_file_only() {
let root = tempfile::tempdir().unwrap();
let custom = root.path().join("custom-ctx.json");
let active = write_global_user_config_in(
root.path(),
Some(crate::config::UserContext::Path(
custom.to_string_lossy().into_owned(),
)),
)
.unwrap();
assert_eq!(active, Some(custom.clone()));
assert!(custom.exists(), "the configured custom path must be seeded");
assert!(
!crate::config::default_user_context_path_in(root.path()).exists(),
"the default context.json must NOT be created when a custom path is configured"
);
}
#[test]
fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
let root = tempfile::tempdir().unwrap();
let custom = root.path().join("custom-ctx.json");
write_global_user_config_in(
root.path(),
Some(crate::config::UserContext::Path(
custom.to_string_lossy().into_owned(),
)),
)
.unwrap();
let active = write_global_user_config_in(root.path(), None).unwrap();
assert_eq!(
active,
Some(custom.clone()),
"re-run without flags must preserve the custom path"
);
let cfg = crate::config::try_load_user_config_in(root.path())
.unwrap()
.unwrap();
assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
}
#[test]
fn install_global_codex_hooks_writes_and_is_idempotent() {
let tmp = tempfile::tempdir().unwrap();
let codex_dir = tmp.path().join(".codex");
install_global_codex_hooks(&codex_dir).unwrap();
install_global_codex_hooks(&codex_dir).unwrap();
let v: serde_json::Value =
serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
.unwrap();
for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
let arr = v["hooks"][event].as_array().unwrap();
assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
}
assert!(v["hooks"].get("PreToolUse").is_none());
let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
assert_eq!(
agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1,
"AGENTS.md workspace-mode block must appear exactly once"
);
let leftover = fs::read_dir(&codex_dir)
.unwrap()
.filter_map(|e| e.ok())
.any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
assert!(!leftover);
}
#[test]
fn has_tracevault_hooks_reads_codex_hooks_json() {
let tmp = tempfile::tempdir().unwrap();
let codex_dir = tmp.path().join(".codex");
install_global_codex_hooks(&codex_dir).unwrap();
assert!(has_tracevault_hooks(&codex_dir.join("hooks.json")).unwrap());
let foreign = tmp.path().join("foreign.json");
fs::write(
&foreign,
r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"other-tool stop"}]}]}}"#,
)
.unwrap();
assert!(!has_tracevault_hooks(&foreign).unwrap());
}
#[test]
fn codex_hooks_has_expected_events_and_commands() {
let h = codex_hooks();
for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
assert!(h.get(event).is_some(), "missing codex event {event}");
}
assert!(h.get("PreToolUse").is_none());
assert!(h.get("Notification").is_none());
let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
assert_eq!(
cmd("PostToolUse"),
"tracevault stream --event post-tool-use --agent codex"
);
assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
assert_eq!(cmd("SessionStart"), "tracevault session-start");
assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
}
#[test]
fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
let tmp = tempfile::tempdir().unwrap();
install_codex_hooks(tmp.path()).unwrap();
install_codex_hooks(tmp.path()).unwrap();
let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
let v: serde_json::Value = serde_json::from_str(&content).unwrap();
for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
let arr = v["hooks"][event].as_array().unwrap();
assert_eq!(
arr.len(),
1,
"event {event} must not be duplicated on re-run"
);
}
assert!(v["hooks"].get("PreToolUse").is_none());
}
#[test]
fn install_codex_hooks_preserves_existing_user_hook() {
let tmp = tempfile::tempdir().unwrap();
let codex_dir = tmp.path().join(".codex");
fs::create_dir_all(&codex_dir).unwrap();
fs::write(
codex_dir.join("hooks.json"),
r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
)
.unwrap();
install_codex_hooks(tmp.path()).unwrap();
let v: serde_json::Value =
serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
.unwrap();
let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
.as_array()
.unwrap()
.iter()
.map(|e| e["hooks"][0]["command"].as_str().unwrap())
.collect();
assert!(
post_cmds.contains(&"my-own"),
"user PostToolUse hook preserved"
);
assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
.as_array()
.unwrap()
.iter()
.map(|e| e["hooks"][0]["command"].as_str().unwrap())
.collect();
assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
}
const FOREIGN_SETTINGS: &str = r#"{
"permissions": { "allow": ["Bash(ls)"] },
"hooks": {
"PreToolUse": [
{ "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
{ "matcher": "Write|Edit", "hooks": [
{ "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
{ "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
] }
],
"Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
"SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
},
"model": "opus"
}"#;
fn expected_foreign_entries() -> Vec<String> {
[
r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
]
.map(String::from)
.to_vec()
}
fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
entry["hooks"]
.as_array()
.unwrap()
.iter()
.any(is_tracevault_hook)
}
fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
let v: serde_json::Value =
serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
assert_eq!(
v.as_object().unwrap().keys().collect::<Vec<_>>(),
["permissions", "hooks", "model"],
"top-level keys kept, in their order"
);
assert_eq!(
v["permissions"],
serde_json::json!({ "allow": ["Bash(ls)"] })
);
let hooks = v["hooks"].as_object().unwrap();
let foreign: Vec<String> = hooks
.values()
.flat_map(|entries| entries.as_array().unwrap())
.filter(|e| !holds_tracevault_hook(e))
.map(|e| e.to_string())
.collect();
assert_eq!(foreign, expected_foreign_entries());
let ours = ours.as_object().unwrap();
for (event, entries) in hooks {
let mine: Vec<&serde_json::Value> = entries
.as_array()
.unwrap()
.iter()
.filter(|e| holds_tracevault_hook(e))
.collect();
let want: Vec<&serde_json::Value> = ours
.get(event)
.map(|o| o.as_array().unwrap().iter().collect())
.unwrap_or_default();
assert_eq!(mine, want, "TraceVault entries under {event}");
}
for event in ours.keys() {
assert!(hooks.contains_key(event), "missing {event}");
}
}
#[test]
fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join(".claude").join(target.filename());
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, FOREIGN_SETTINGS).unwrap();
install_claude_hooks(tmp.path(), target).unwrap();
assert_installed_over_foreign(&path, &tracevault_hooks());
let after_first = fs::read(&path).unwrap();
install_claude_hooks(tmp.path(), target).unwrap();
assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
}
}
#[test]
fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
let tmp = tempfile::tempdir().unwrap();
let claude_dir = tmp.path().join(".claude");
fs::create_dir_all(&claude_dir).unwrap();
fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
install_global_hooks(&claude_dir).unwrap();
assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
}
#[test]
fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
for global in [false, true] {
let tmp = tempfile::tempdir().unwrap();
let codex_dir = tmp.path().join(".codex");
fs::create_dir_all(&codex_dir).unwrap();
fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
if global {
install_global_codex_hooks(&codex_dir).unwrap();
} else {
install_codex_hooks(tmp.path()).unwrap();
}
assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
}
}
#[test]
fn up_to_date_hook_file_is_not_rewritten() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join(".claude/settings.json");
fs::create_dir_all(path.parent().unwrap()).unwrap();
let mut body = Vec::new();
let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
serde::Serialize::serialize(
&serde_json::json!({ "hooks": tracevault_hooks() }),
&mut ser,
)
.unwrap();
fs::write(&path, &body).unwrap();
install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
assert_eq!(fs::read(&path).unwrap(), body);
}
#[test]
fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
for (target, body) in [
(ClaudeSettingsTarget::Shared, "{ not json"),
(ClaudeSettingsTarget::Local, "[1, 2]"),
(ClaudeSettingsTarget::Shared, "null"),
(ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
(ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
] {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join(".claude").join(target.filename());
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, body).unwrap();
let err = install_claude_hooks(tmp.path(), target).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
assert_eq!(
fs::read_to_string(&path).unwrap(),
body,
"file must be untouched"
);
assert_eq!(
fs::read_dir(path.parent().unwrap()).unwrap().count(),
1,
"no temp file left behind"
);
}
}
#[test]
fn concurrent_installs_never_publish_a_partial_file() {
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join("settings.json");
fs::write(&path, FOREIGN_SETTINGS).unwrap();
let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
let reader = {
let (path, done) = (path.clone(), done.clone());
std::thread::spawn(move || {
while !done.load(std::sync::atomic::Ordering::Relaxed) {
let body = fs::read_to_string(&path).unwrap();
serde_json::from_str::<serde_json::Value>(&body).unwrap();
}
})
};
let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
.into_iter()
.map(|ours| {
let path = path.clone();
std::thread::spawn(move || {
for _ in 0..200 {
if let Err(e) = merge_hooks_into_file(&path, &ours) {
assert!(e.to_string().contains("kept changing"), "{e}");
}
}
})
})
.collect();
for writer in writers {
writer.join().unwrap();
}
done.store(true, std::sync::atomic::Ordering::Relaxed);
reader.join().unwrap();
let v: serde_json::Value =
serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
assert_eq!(v["model"], "opus");
assert_eq!(
fs::read_dir(tmp.path()).unwrap().count(),
1,
"no temp file left"
);
}
#[cfg(unix)]
#[test]
fn install_claude_hooks_keeps_file_permissions() {
use std::os::unix::fs::PermissionsExt;
let tmp = tempfile::tempdir().unwrap();
let path = tmp.path().join(".claude/settings.local.json");
fs::create_dir_all(path.parent().unwrap()).unwrap();
fs::write(&path, FOREIGN_SETTINGS).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
assert_installed_over_foreign(&path, &tracevault_hooks());
}
#[cfg(unix)]
#[test]
fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
let tmp = tempfile::tempdir().unwrap();
let central = tmp.path().join("central/claude-settings.json");
fs::create_dir_all(central.parent().unwrap()).unwrap();
fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
let link = tmp.path().join("repo/.claude/settings.json");
fs::create_dir_all(link.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(¢ral, &link).unwrap();
install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
assert!(fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink());
assert_installed_over_foreign(¢ral, &tracevault_hooks());
}
#[cfg(unix)]
#[test]
fn install_claude_hooks_refuses_dangling_symlink() {
let tmp = tempfile::tempdir().unwrap();
let link = tmp.path().join(".claude/settings.json");
fs::create_dir_all(link.parent().unwrap()).unwrap();
std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
assert!(fs::symlink_metadata(&link)
.unwrap()
.file_type()
.is_symlink());
assert!(!tmp.path().join("gone.json").exists());
}
#[test]
fn validate_init_flags_rejects_claude_settings_with_codex() {
assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
}
#[test]
fn validate_init_flags_allows_codex_without_claude_settings() {
assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
}
#[test]
fn validate_init_flags_allows_claude_with_claude_settings() {
assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
}
#[test]
fn merge_hooks_into_file_rejects_parent_dir() {
let tmp = tempfile::tempdir().unwrap();
let bad = tmp.path().join("..").join("hooks.json");
let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn append_workspace_md_rejects_parent_dir() {
let tmp = tempfile::tempdir().unwrap();
let bad = tmp.path().join("..").join("AGENTS.md");
let err = append_workspace_md(&bad).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[tokio::test]
async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
crate::test_helpers::init_git_repo(root);
fs::create_dir_all(root.join(".tracevault")).unwrap();
fs::write(
root.join(".tracevault/config.toml"),
"api_key = \"tvk_test\"\n",
)
.unwrap();
let entry = init_in_directory(
root,
None,
None,
false,
Some(crate::config::UserContext::Toggle(false)),
crate::agent::Agent::Codex,
)
.await
.unwrap();
assert!(root.join(".codex").join("hooks.json").exists());
assert!(!root.join(".claude").join("settings.json").exists());
assert_eq!(entry, ".codex/hooks.json");
let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
assert!(gi.contains(".codex/hooks.json"));
assert!(gi.contains(".tracevault/"));
}
#[tokio::test]
async fn init_in_directory_registers_repo_and_persists_repo_id() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
crate::test_helpers::init_git_repo(root);
add_origin_remote(root, "git@github.com:org/repo.git");
let repo_id = "11111111-1111-4111-8111-111111111111";
let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
let (base, _rx) = crate::test_helpers::spawn_seq(vec![
http_response("404 Not Found", NO_REMOTE),
http_response("200 OK", &body),
]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
init_in_directory(
root,
Some(&base),
None,
true,
Some(crate::config::UserContext::Toggle(false)),
crate::agent::Agent::Codex,
)
.await
.unwrap();
let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
assert_eq!(
cfg.repo_id,
Some(repo_id.to_string()),
"successful registration must persist repo_id to config.toml"
);
}
#[tokio::test]
async fn init_in_directory_registration_403_does_not_persist_repo_id() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let root = tmp.path();
crate::test_helpers::init_git_repo(root);
add_origin_remote(root, "git@github.com:org/repo.git");
let (base, _rx) = crate::test_helpers::spawn_seq(vec![
http_response("404 Not Found", NO_REMOTE),
http_response("403 Forbidden", ""),
]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
let entry = init_in_directory(
root,
Some(&base),
None,
true,
Some(crate::config::UserContext::Toggle(false)),
crate::agent::Agent::Codex,
)
.await
.expect("a registration failure (403) must not abort init itself");
assert_eq!(entry, ".codex/hooks.json");
let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
assert!(
cfg.repo_id.is_none(),
"a 403 registration failure must not persist a repo_id"
);
}
#[tokio::test]
async fn registration_failure_message_flags_403_as_not_authorized() {
let base = spawn_once(http_response("403 Forbidden", ""));
let client = ApiClient::new(&base, Some("tok"));
let err = client
.register_repo(crate::api_client::RegisterRepoRequest {
repo_name: "repo".into(),
github_url: Some("git@github.com:org/repo.git".into()),
})
.await
.unwrap_err();
let msg = registration_failure_message(err.as_ref());
assert!(
msg.contains("not authorized"),
"403 registration failure must surface a not-authorized message; got: {msg}"
);
}
#[tokio::test]
async fn registration_failure_message_generic_for_non_403() {
let base = spawn_once(http_response("500 Internal Server Error", ""));
let client = ApiClient::new(&base, Some("tok"));
let err = client
.register_repo(crate::api_client::RegisterRepoRequest {
repo_name: "repo".into(),
github_url: Some("git@github.com:org/repo.git".into()),
})
.await
.unwrap_err();
let msg = registration_failure_message(err.as_ref());
assert!(
msg.contains("could not register repo on server"),
"got: {msg}"
);
assert!(!msg.contains("not authorized"), "got: {msg}");
}
#[tokio::test]
async fn registration_failure_message_does_not_misclassify_403_in_body() {
let base = spawn_once(http_response(
"500 Internal Server Error",
"upstream error 403 from proxy",
));
let client = ApiClient::new(&base, Some("tok"));
let err = client
.register_repo(crate::api_client::RegisterRepoRequest {
repo_name: "repo".into(),
github_url: Some("git@github.com:org/repo.git".into()),
})
.await
.unwrap_err();
let msg = registration_failure_message(err.as_ref());
assert!(
!msg.contains("not authorized"),
"a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
);
assert!(
msg.contains("could not register repo on server"),
"got: {msg}"
);
}
#[tokio::test]
async fn registration_failure_message_flags_404_as_version_mismatch() {
let base = spawn_once(http_response("404 Not Found", ""));
let client = ApiClient::new(&base, Some("tok"));
let err = client
.register_repo(crate::api_client::RegisterRepoRequest {
repo_name: "repo".into(),
github_url: Some("git@github.com:org/repo.git".into()),
})
.await
.unwrap_err();
let msg = registration_failure_message(err.as_ref());
assert!(
msg.to_lowercase().contains("version mismatch"),
"a 404 registration failure should hint at a version mismatch; got: {msg}"
);
}
const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
fn resolve_remote_ok() -> String {
http_response(
"200 OK",
&format!(
r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
),
)
}
fn remote_detail(repos: &[(&str, &str)]) -> String {
let repos: Vec<String> = repos
.iter()
.map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
.collect();
http_response(
"200 OK",
&format!(
r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
repos.join(",")
),
)
}
async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
let (base, rx) = crate::test_helpers::spawn_seq(responses);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", root);
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
init_in_directory(
root,
Some(&base),
None,
true,
Some(crate::config::UserContext::Toggle(false)),
crate::agent::Agent::Codex,
)
.await
.expect("init succeeds");
let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
(cfg.repo_id, rx.try_iter().collect())
}
fn registered(requests: &[String]) -> bool {
requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
}
#[tokio::test]
async fn init_binds_the_existing_repo_of_a_known_remote() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
let (repo_id, requests) = init_against(
tmp.path(),
vec![
resolve_remote_ok(),
remote_detail(&[(CANONICAL, "tracevault")]),
],
)
.await;
assert_eq!(repo_id.as_deref(), Some(CANONICAL));
assert!(!registered(&requests), "requests: {requests:?}");
}
#[tokio::test]
async fn init_binds_the_record_named_like_the_checkout() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
let dir_name = crate::resolution::git_repo_name(tmp.path());
let (repo_id, requests) = init_against(
tmp.path(),
vec![
resolve_remote_ok(),
remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
],
)
.await;
assert_eq!(repo_id.as_deref(), Some(STRAY));
assert!(!registered(&requests));
}
#[tokio::test]
async fn init_rerun_keeps_the_previously_bound_repo() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
fs::write(
tmp.path().join(".tracevault/config.toml"),
format!("repo_id = \"{STRAY}\"\n"),
)
.unwrap();
let (repo_id, requests) = init_against(
tmp.path(),
vec![
resolve_remote_ok(),
remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
],
)
.await;
assert_eq!(repo_id.as_deref(), Some(STRAY));
assert!(!registered(&requests));
}
#[tokio::test]
async fn init_binding_keeps_the_rest_of_the_config() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
fs::write(
tmp.path().join(".tracevault/config.toml"),
"api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
)
.unwrap();
let (repo_id, requests) = init_against(
tmp.path(),
vec![
http_response(
"200 OK",
&format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
),
resolve_remote_ok(),
remote_detail(&[(CANONICAL, "tracevault")]),
],
)
.await;
assert_eq!(repo_id.as_deref(), Some(CANONICAL));
assert!(
requests[0].starts_with("GET /api/v1/projects"),
"{requests:?}"
);
let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
assert_eq!(cfg.default_project, None);
assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
assert_eq!(cfg.project_name.as_deref(), Some("payments"));
}
const PROJECT: &str = "00000000-0000-4000-8000-0000000000aa";
#[tokio::test]
async fn init_unknown_default_project_errors_and_writes_nothing() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
let content = "default_project = \"typo\"\n";
fs::write(tmp.path().join(".tracevault/config.toml"), content).unwrap();
let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
"200 OK",
&format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
)]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
let err = init_in_directory(
tmp.path(),
Some(&base),
None,
true,
None,
crate::agent::Agent::Codex,
)
.await
.unwrap_err();
assert!(err.to_string().contains("'typo'"), "{err}");
assert_eq!(
fs::read_to_string(tmp.path().join(".tracevault/config.toml")).unwrap(),
content
);
assert!(!tmp.path().join(".codex/hooks.json").exists());
}
#[tokio::test]
async fn init_workspace_binds_a_non_git_dir_to_a_project() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("umbrella");
fs::create_dir_all(&dir).unwrap();
let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response(
"200 OK",
&format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
)]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
let bound = init_workspace(&dir, "visdom", Some(&base)).await.unwrap();
assert_eq!(bound.project_id.to_string(), PROJECT);
assert_eq!(bound.project_name, "visdom");
let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
assert_eq!(cfg.repo_id, None);
assert_eq!(cfg.server_url.as_deref(), Some(base.as_str()));
assert!(dir.join(".tracevault/.gitignore").exists());
let requests: Vec<String> = rx.try_iter().collect();
assert_eq!(requests.len(), 1, "{requests:?}");
let sub = dir.join("notes");
fs::create_dir_all(&sub).unwrap();
assert_eq!(
crate::paths::resolve_project_root(&sub)
.root
.canonicalize()
.unwrap(),
dir.canonicalize().unwrap()
);
}
#[tokio::test]
async fn init_workspace_rebinds_and_keeps_other_keys() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path();
fs::create_dir_all(dir.join(".tracevault")).unwrap();
fs::write(
dir.join(".tracevault/config.toml"),
"default_project = \"old\"\nproject_id = \"00000000-0000-4000-8000-000000000001\"\nuser_context = false\n",
)
.unwrap();
let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
"200 OK",
&format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
)]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", dir);
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
init_workspace(dir, "visdom", Some(&base)).await.unwrap();
let cfg = crate::config::TracevaultConfig::load(dir).unwrap();
assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
assert_eq!(cfg.default_project, None);
assert!(matches!(
cfg.user_context,
Some(crate::config::UserContext::Toggle(false))
));
}
#[test]
fn append_workspace_md_upgrades_an_older_block_in_place() {
let tmp = tempfile::tempdir().unwrap();
let md = tmp.path().join("CLAUDE.md");
for old in PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS {
fs::write(
&md,
format!("# Mine\nkeep me\n\n{old}## After\nalso keep\n"),
)
.unwrap();
append_workspace_md(&md).unwrap();
let got = fs::read_to_string(&md).unwrap();
assert_eq!(
got,
format!("# Mine\nkeep me\n\n{GLOBAL_CLAUDE_MD_BLOCK}## After\nalso keep\n")
);
append_workspace_md(&md).unwrap();
assert_eq!(fs::read_to_string(&md).unwrap(), got);
}
let edited = "x\n\n<!-- tracevault:workspace-mode -->\n## T\nmy own words\n";
fs::write(&md, edited).unwrap();
append_workspace_md(&md).unwrap();
assert_eq!(fs::read_to_string(&md).unwrap(), edited);
}
#[tokio::test]
async fn init_workspace_refuses_a_server_url_the_credential_is_not_for() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response("200 OK", "[]")]);
fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
fs::write(
tmp.path().join(".tracevault/config.toml"),
"server_url = \"http://other.example.invalid\"\napi_key = \"tvk_x\"\n",
)
.unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_API_KEY");
_guard.remove("TRACEVAULT_SERVER_URL");
let err = init_workspace(tmp.path(), "visdom", Some(&base))
.await
.unwrap_err();
assert!(err.to_string().contains("not --server-url"), "{err}");
assert_eq!(rx.try_iter().count(), 0, "no request may be sent");
}
#[tokio::test]
async fn credential_url_mismatch_only_for_a_different_explicit_server() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.remove("TRACEVAULT_API_KEY");
assert!(credential_url_mismatch(Some("https://a/"), Some("https://a")).is_none());
assert!(credential_url_mismatch(None, Some("https://b")).is_none());
assert!(credential_url_mismatch(Some("https://a"), None).is_none());
assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_some());
_guard.set("TRACEVAULT_API_KEY", "tvk_for_b");
assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_none());
}
#[tokio::test]
async fn migrate_cwd_config_migrates_the_dirs_config() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
let dir = tmp.path().join("umbrella");
fs::create_dir_all(dir.join(".tracevault")).unwrap();
let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
"200 OK",
&format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
)]);
fs::write(
dir.join(".tracevault/config.toml"),
format!("server_url = \"{base}\"\napi_key = \"tvk_x\"\ndefault_project = \"visdom\"\n"),
)
.unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.remove("TRACEVAULT_API_KEY");
_guard.remove("TRACEVAULT_SERVER_URL");
migrate_cwd_config(&dir).await.unwrap();
let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
assert_eq!(cfg.default_project, None);
}
#[tokio::test]
async fn init_workspace_unknown_or_ambiguous_name_writes_nothing() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
for name in ["nope", "dup"] {
let tmp = tempfile::tempdir().unwrap();
let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
"200 OK",
r#"[{"id":"00000000-0000-4000-8000-000000000001","name":"dup"},{"id":"00000000-0000-4000-8000-000000000002","name":"dup"}]"#,
)]);
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
let err = init_workspace(tmp.path(), name, Some(&base))
.await
.unwrap_err();
assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
assert!(!tmp.path().join(".tracevault").exists(), "{name}");
}
}
#[tokio::test]
async fn init_workspace_refuses_a_git_subdirectory() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
let sub = tmp.path().join("pkg");
fs::create_dir_all(&sub).unwrap();
let mut _guard = crate::test_helpers::EnvVarGuard::new();
_guard.set("XDG_CONFIG_HOME", tmp.path());
_guard.set("TRACEVAULT_API_KEY", "tok");
_guard.remove("TRACEVAULT_SERVER_URL");
let err = init_workspace(&sub, "visdom", Some("http://127.0.0.1:9"))
.await
.unwrap_err();
assert!(err.to_string().contains("inside the git repo"), "{err}");
assert!(!sub.join(".tracevault").exists());
}
#[tokio::test]
async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
fs::write(
tmp.path().join(".tracevault/config.toml"),
format!("repo_id = \"{STRAY}\"\n"),
)
.unwrap();
let (repo_id, requests) = init_against(
tmp.path(),
vec![http_response("500 Internal Server Error", "{}")],
)
.await;
assert_eq!(repo_id.as_deref(), Some(STRAY));
assert!(!registered(&requests));
}
#[tokio::test]
async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
let (repo_id, requests) = init_against(
tmp.path(),
vec![
resolve_remote_ok(),
remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
],
)
.await;
assert_eq!(repo_id, None);
assert!(!registered(&requests));
}
#[tokio::test]
async fn init_registers_for_a_codebase_without_live_repos() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
let (repo_id, requests) = init_against(
tmp.path(),
vec![
resolve_remote_ok(),
remote_detail(&[]),
http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
],
)
.await;
assert_eq!(repo_id.as_deref(), Some(CANONICAL));
assert!(registered(&requests));
}
#[tokio::test]
async fn init_does_not_register_when_the_remote_check_fails() {
let _env_lock = crate::test_helpers::lock_env_mutation().await;
let tmp = tempfile::tempdir().unwrap();
crate::test_helpers::init_git_repo(tmp.path());
add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
let (repo_id, requests) = init_against(
tmp.path(),
vec![http_response("500 Internal Server Error", "{}")],
)
.await;
assert_eq!(repo_id, None);
assert!(!registered(&requests));
}
}