1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use crate::resolution::{git_remote_url, git_repo_name, RegistrationPlan};
5use std::fs;
6use std::io::{self, BufRead, IsTerminal, Write};
7use std::path::{Path, PathBuf};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
11pub enum ClaudeSettingsTarget {
12 Shared,
14 Local,
16}
17
18impl ClaudeSettingsTarget {
19 pub fn filename(self) -> &'static str {
20 match self {
21 ClaudeSettingsTarget::Shared => "settings.json",
22 ClaudeSettingsTarget::Local => "settings.local.json",
23 }
24 }
25
26 pub fn gitignore_entry(self) -> &'static str {
27 match self {
28 ClaudeSettingsTarget::Shared => ".claude/settings.json",
29 ClaudeSettingsTarget::Local => ".claude/settings.local.json",
30 }
31 }
32}
33
34fn resolve_claude_target(
38 explicit: Option<ClaudeSettingsTarget>,
39) -> io::Result<ClaudeSettingsTarget> {
40 if let Some(target) = explicit {
41 return Ok(target);
42 }
43 if !io::stdin().is_terminal() {
44 return Ok(ClaudeSettingsTarget::Shared);
45 }
46
47 let stdout = io::stdout();
48 let mut stdout = stdout.lock();
49 write!(
50 stdout,
51 "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
52 )?;
53 stdout.flush()?;
54
55 let mut line = String::new();
56 io::stdin().lock().read_line(&mut line)?;
57 let answer = line.trim().to_lowercase();
58 Ok(match answer.as_str() {
59 "l" | "local" => ClaudeSettingsTarget::Local,
60 _ => ClaudeSettingsTarget::Shared,
61 })
62}
63
64fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
72 let output = std::process::Command::new("git")
73 .args(["rev-parse", "--git-dir", "--git-common-dir"])
74 .current_dir(dir)
75 .output()
76 .ok()?;
77 if !output.status.success() {
78 return None;
79 }
80 let stdout = String::from_utf8(output.stdout).ok()?;
81 let mut lines = stdout.lines();
82 let git_dir = lines.next()?.trim();
83 let git_common_dir = lines.next()?.trim();
84
85 let git_dir = dir.join(git_dir).canonicalize().ok()?;
88 let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
89
90 if git_dir == git_common_dir {
91 None } else {
93 git_common_dir.parent().map(Path::to_path_buf)
94 }
95}
96
97pub fn validate_init_flags(
103 agent: crate::agent::Agent,
104 claude_settings_set: bool,
105) -> Result<(), String> {
106 if matches!(
107 agent,
108 crate::agent::Agent::Codex | crate::agent::Agent::Gsd | crate::agent::Agent::OpenCode
109 ) && claude_settings_set
110 {
111 return Err("--claude-settings only applies to --agent claude-code".to_string());
112 }
113 Ok(())
114}
115
116pub async fn init_in_directory(
121 project_root: &Path,
122 server_url: Option<&str>,
123 claude_settings: Option<ClaudeSettingsTarget>,
124 no_gitignore: bool,
125 user_context: Option<UserContext>,
126 agent: crate::agent::Agent,
127) -> Result<String, io::Error> {
128 if !project_root.join(".git").exists() {
130 return Err(io::Error::new(
131 io::ErrorKind::NotFound,
132 "Not a git repository. Run 'git init' first.",
133 ));
134 }
135
136 if let Some(primary) = linked_worktree_primary(project_root) {
142 return Err(io::Error::new(
143 io::ErrorKind::Unsupported,
144 format!(
145 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
146 cd there and run it again — all worktrees share the primary's .tracevault/.",
147 primary.display()
148 ),
149 ));
150 }
151
152 let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
156 io::Error::new(
157 io::ErrorKind::InvalidData,
158 format!(
159 "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
160 then run `tracevault init` again."
161 ),
162 )
163 })?;
164
165 let (resolved_url, resolved_credential) =
174 crate::credentials::resolve_credentials_quiet(project_root)
175 .map_err(|e| io::Error::other(e.to_string()))?;
176 let effective_url = server_url.map(String::from).or(resolved_url);
177 if resolved_credential.is_none() {
178 return Err(io::Error::new(
179 io::ErrorKind::PermissionDenied,
180 not_logged_in_message(effective_url.as_deref()),
181 ));
182 }
183
184 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
187 {
188 crate::agent::Agent::ClaudeCode => {
189 let target = resolve_claude_target(claude_settings)?;
190 (Some(target), target.gitignore_entry().to_string())
191 }
192 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
193 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
199 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
204 };
205
206 let config_dir = TracevaultConfig::config_dir(project_root);
208 fs::create_dir_all(&config_dir)?;
209 fs::create_dir_all(config_dir.join("sessions"))?;
210 fs::create_dir_all(config_dir.join("cache"))?;
211 TracevaultConfig::ensure_gitignore(&config_dir)?;
214
215 if !no_gitignore {
217 update_root_gitignore(project_root, &hook_gitignore_entry)?;
218 }
219
220 let remote_url = git_remote_url(project_root);
222 if remote_url.is_none() {
223 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
224 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
225 }
226
227 let mut config = existing_config.unwrap_or_default();
232 if let Some(url) = server_url {
233 config.server_url = Some(url.to_string());
234 }
235 config.user_context = user_context
236 .or(config.user_context)
237 .or(Some(UserContext::Toggle(true)));
238 config.save(project_root)?;
239
240 let previous_repo_id = config
243 .repo_id
244 .as_deref()
245 .and_then(|id| id.parse::<uuid::Uuid>().ok());
246
247 match agent {
249 crate::agent::Agent::ClaudeCode => {
250 let target =
252 claude_target.expect("claude settings target is resolved for the Claude agent");
253 install_claude_hooks(project_root, target)?;
254 }
255 crate::agent::Agent::Codex => {
256 install_codex_hooks(project_root)?;
257 println!("{}", codex_hook_trust_notice());
258 }
259 crate::agent::Agent::Gsd => {
260 install_gsd_extension(Some(project_root))?;
268 }
269 crate::agent::Agent::OpenCode => {
270 install_opencode_plugin(Some(project_root))?;
271 }
272 }
273
274 install_git_hook(project_root)?;
276 install_post_commit_hook(project_root)?;
277
278 let detected = crate::hooks::detect_tools(project_root);
280 for tool in &detected {
281 println!(" Detected: {}", tool.name());
282 }
283
284 if let (Some(url), Some(remote)) = (effective_url, remote_url) {
285 let client = ApiClient::with_credential(&url, resolved_credential);
286 let repo_name = git_repo_name(project_root);
287 let origin_url = remote.clone();
290
291 match crate::resolution::plan_registration(
295 &client,
296 &origin_url,
297 &repo_name,
298 previous_repo_id,
299 )
300 .await
301 {
302 Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
303 println!(
304 "Bound to existing repo {} (id: {repo_id}); not registering another record \
305 for this codebase",
306 codebase
307 .repos
308 .iter()
309 .find(|r| r.id == repo_id)
310 .map_or("", |r| r.name.as_str())
311 );
312 println!(
313 "{}",
314 crate::resolution::codebase_line(
315 codebase.remote.name.as_deref(),
316 &codebase.remote.normalized_url,
317 &codebase.remote.clone_status
318 )
319 );
320 persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
321 }
322 Ok(RegistrationPlan::Ambiguous(codebase)) => {
323 eprintln!(
324 "Warning: codebase {} already has {} repo records ({}) and none is named \
325 '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
326 .tracevault/config.toml to the one this checkout belongs to.",
327 codebase.display_name(),
328 codebase.repos.len(),
329 codebase.repo_list()
330 );
331 }
332 Ok(RegistrationPlan::Register) => {
333 register_new_repo(&client, project_root, repo_name, origin_url).await;
334 }
335 Err(e) => {
338 eprintln!(
339 "Warning: could not check the server for an existing repo of this remote \
340 ({e}); not registering. Run `tracevault init` again once the server is \
341 reachable."
342 );
343 }
344 }
345 }
346
347 Ok(hook_gitignore_entry)
348}
349
350pub fn not_logged_in_message(url: Option<&str>) -> String {
355 let url = url.unwrap_or("<URL>");
356 format!(
357 "Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
358 would record nothing, so nothing was installed.\n\
359 Log in, then run init again:\n\
360 \n tracevault login --server-url {url}\n tracevault init\n\n\
361 (In CI, set TRACEVAULT_API_KEY instead of logging in.)"
362 )
363}
364
365pub(crate) fn persist_repo_binding(
372 project_root: &Path,
373 repo_id: uuid::Uuid,
374 codebase: Option<&crate::api_client::ResolveRemoteResponse>,
375) -> bool {
376 let Some(mut cfg) = TracevaultConfig::load(project_root) else {
377 return false;
378 };
379 cfg.repo_id = Some(repo_id.to_string());
380 if let Some(remote) = codebase {
381 cfg.remote_id = Some(remote.remote_id.to_string());
382 cfg.codebase_name = remote.name.clone();
383 }
384 cfg.save(project_root).is_ok()
385}
386
387async fn register_new_repo(
391 client: &ApiClient,
392 project_root: &Path,
393 repo_name: String,
394 origin_url: String,
395) {
396 match client
397 .register_repo(crate::api_client::RegisterRepoRequest {
398 repo_name,
399 github_url: Some(origin_url.clone()),
400 })
401 .await
402 {
403 Ok(resp) => {
404 println!("Repo registered on server (id: {})", resp.repo_id);
405 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
407 cfg.repo_id = Some(resp.repo_id.to_string());
408 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
414 println!(
415 "{}",
416 crate::resolution::codebase_line(
417 remote.name.as_deref(),
418 &remote.normalized_url,
419 &remote.clone_status
420 )
421 );
422 cfg.remote_id = Some(remote.remote_id.to_string());
423 cfg.codebase_name = remote.name.clone();
424 }
425 let _ = cfg.save(project_root);
426 }
427 }
428 Err(e) => {
429 eprintln!("{}", registration_failure_message(e.as_ref()));
430 }
431 }
432}
433
434fn registration_failure_message(err: &dyn std::error::Error) -> String {
449 let msg = err.to_string();
450 if msg.starts_with("Server returned 403 ") {
451 "Warning: you are not authorized to register this repo.".to_string()
452 } else if msg.starts_with("Server returned 404 ") {
453 "Warning: could not register repo on server (404) — this endpoint may not exist on \
454 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
455 once the server is upgraded."
456 .to_string()
457 } else {
458 format!("Warning: could not register repo on server: {err}")
459 }
460}
461
462fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
463 let path = project_root.join(".gitignore");
464 let existing = if path.exists() {
465 fs::read_to_string(&path)?
466 } else {
467 String::new()
468 };
469
470 let needed: Vec<&str> = [".tracevault/", settings_entry]
476 .iter()
477 .copied()
478 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
479 .collect();
480
481 if needed.is_empty() {
482 return Ok(());
483 }
484
485 let mut content = existing;
486 if !content.is_empty() && !content.ends_with('\n') {
487 content.push('\n');
488 }
489 content.push_str("\n# TraceVault — local only, do not commit\n");
490 for entry in needed {
491 content.push_str(entry);
492 content.push('\n');
493 }
494
495 fs::write(path, content)
496}
497
498const HOOK_MARKER: &str = "# tracevault:enforce";
499const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
500
501fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
502 let hooks_dir = project_root.join(".git/hooks");
503 fs::create_dir_all(&hooks_dir)?;
504
505 let hook_path = hooks_dir.join("pre-push");
506 let tracevault_block = format!(
513 "{HOOK_MARKER}\n\
514 # Capture git's pre-push ref list once; `check` uses it to determine\n\
515 # which files are being pushed.\n\
516 tracevault_prepush_stdin=$(cat)\n\
517 tracevault sync 2>/dev/null || true\n\
518 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
519 );
520
521 if hook_path.exists() {
522 let existing = fs::read_to_string(&hook_path)?;
523
524 if existing.contains(HOOK_MARKER) {
526 return Ok(());
527 }
528
529 if existing.contains(OLD_HOOK_MARKER) {
531 let mut new_content = String::new();
532 let mut skip = false;
533 for line in existing.lines() {
534 if line.contains(OLD_HOOK_MARKER) {
535 skip = true;
536 continue;
537 }
538 if skip {
539 if line.starts_with("tracevault ") {
541 continue;
542 }
543 skip = false;
544 }
545 new_content.push_str(line);
546 new_content.push('\n');
547 }
548 if !new_content.ends_with('\n') {
549 new_content.push('\n');
550 }
551 new_content.push_str(&tracevault_block);
552 fs::write(&hook_path, new_content)?;
553 } else {
554 let mut content = existing;
556 if !content.ends_with('\n') {
557 content.push('\n');
558 }
559 content.push_str(&tracevault_block);
560 fs::write(&hook_path, content)?;
561 }
562 } else {
563 let content = format!("#!/bin/sh\n{tracevault_block}");
564 fs::write(&hook_path, content)?;
565 }
566
567 #[cfg(unix)]
569 {
570 use std::os::unix::fs::PermissionsExt;
571 let mut perms = fs::metadata(&hook_path)?.permissions();
572 perms.set_mode(0o755);
573 fs::set_permissions(&hook_path, perms)?;
574 }
575
576 Ok(())
577}
578
579const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
580
581fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
582 let hooks_dir = project_root.join(".git/hooks");
583 fs::create_dir_all(&hooks_dir)?;
584
585 let hook_path = hooks_dir.join("post-commit");
586 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
587
588 if hook_path.exists() {
589 let existing = fs::read_to_string(&hook_path)?;
590
591 if existing.contains(POST_COMMIT_MARKER) {
592 return Ok(());
593 }
594
595 let mut content = existing;
596 if !content.ends_with('\n') {
597 content.push('\n');
598 }
599 content.push_str(&tracevault_block);
600 fs::write(&hook_path, content)?;
601 } else {
602 let content = format!("#!/bin/sh\n{tracevault_block}");
603 fs::write(&hook_path, content)?;
604 }
605
606 #[cfg(unix)]
607 {
608 use std::os::unix::fs::PermissionsExt;
609 let mut perms = fs::metadata(&hook_path)?.permissions();
610 perms.set_mode(0o755);
611 fs::set_permissions(&hook_path, perms)?;
612 }
613
614 Ok(())
615}
616
617fn install_claude_hooks(
618 project_root: &Path,
619 target: ClaudeSettingsTarget,
620) -> Result<(), io::Error> {
621 let claude_dir = project_root.join(".claude");
622 fs::create_dir_all(&claude_dir)?;
623 merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
624}
625
626pub fn tracevault_hooks() -> serde_json::Value {
627 serde_json::json!({
628 "PreToolUse": [{
629 "matcher": "Write|Edit|Bash",
630 "hooks": [{
631 "type": "command",
632 "command": "tracevault stream --event pre-tool-use",
633 "timeout": 10,
634 "statusMessage": "TraceVault: streaming pre-tool event"
635 }]
636 }],
637 "PostToolUse": [{
638 "matcher": "",
639 "hooks": [{
640 "type": "command",
641 "command": "tracevault stream --event post-tool-use",
642 "timeout": 10,
643 "statusMessage": "TraceVault: streaming post-tool event"
644 }]
645 }],
646 "Notification": [{
647 "matcher": "",
648 "hooks": [{
649 "type": "command",
650 "command": "tracevault stream --event notification",
651 "timeout": 10,
652 "statusMessage": "TraceVault: streaming notification"
653 }]
654 }],
655 "Stop": [{
656 "matcher": "",
657 "hooks": [{
658 "type": "command",
659 "command": "tracevault stream --event stop",
660 "timeout": 10,
661 "statusMessage": "TraceVault: finalizing session"
662 }]
663 }],
664 "SessionEnd": [{
667 "matcher": "",
668 "hooks": [{
669 "type": "command",
670 "command": "tracevault stream --event session-end",
671 "timeout": 10,
672 "statusMessage": "TraceVault: sending session cost"
673 }]
674 }],
675 "SubagentStop": [{
678 "matcher": "",
679 "hooks": [{
680 "type": "command",
681 "command": "tracevault stream --event subagent-stop",
682 "timeout": 10,
683 "statusMessage": "TraceVault: streaming subagent transcript"
684 }]
685 }],
686 "SessionStart": [{
687 "matcher": "",
688 "hooks": [{
689 "type": "command",
690 "command": "tracevault session-start",
691 "timeout": 10,
692 "statusMessage": "TraceVault: session start"
693 }]
694 }],
695 "UserPromptSubmit": [{
696 "matcher": "",
697 "hooks": [{
698 "type": "command",
699 "command": "tracevault user-prompt",
700 "timeout": 10,
701 "statusMessage": "TraceVault: policy reinforcement"
702 }]
703 }]
704 })
705}
706
707pub fn codex_hook_trust_notice() -> &'static str {
717 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
718 silently and no session is captured. Run `codex` once interactively in a repo and \
719 approve the hook-trust prompt; unattended runs (CI) can pass \
720 `--dangerously-bypass-hook-trust` instead."
721}
722
723pub fn codex_hooks() -> serde_json::Value {
733 serde_json::json!({
734 "SessionStart": [{
735 "matcher": "",
736 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
737 }],
738 "UserPromptSubmit": [{
739 "matcher": "",
740 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
741 }],
742 "PostToolUse": [{
743 "matcher": "",
744 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
745 }],
746 "Stop": [{
747 "matcher": "",
748 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
749 }]
750 })
751}
752
753const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
757const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
758const GSD_EXT_MANIFEST_JSON: &str =
759 include_str!("../../assets/gsd-extension/extension-manifest.json");
760
761fn gsd_extension_source_dir() -> io::Result<PathBuf> {
765 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
766 let config_dir = config_dir
767 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
768 Ok(config_dir.join("tracevault").join("gsd-extension"))
769}
770
771pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
795 let home =
796 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
797 let gsd_home = home.join(".gsd");
798
799 let source_dir = gsd_extension_source_dir()?;
800 fs::create_dir_all(&source_dir)?;
801 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
802 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
803 fs::write(
804 source_dir.join("extension-manifest.json"),
805 GSD_EXT_MANIFEST_JSON,
806 )?;
807
808 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
812 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
813 }
814
815 let local_flag = project_root.is_some();
819 let mut cmd = std::process::Command::new("gsd");
820 cmd.arg("install").arg(&source_dir);
821 if let Some(root) = project_root {
822 cmd.arg("-l");
823 cmd.current_dir(root);
824 }
825
826 let retry_hint = format!(
827 "gsd install {}{}",
828 source_dir.display(),
829 if local_flag { " -l" } else { "" }
830 );
831
832 match cmd.output() {
833 Ok(output) if output.status.success() => {
834 println!(
835 "TraceVault: installed and registered the GSD extension ({}).",
836 source_dir.display()
837 );
838 }
839 Ok(output) => {
840 eprintln!(
841 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
842 source_dir.display(),
843 String::from_utf8_lossy(&output.stderr),
844 );
845 }
846 Err(e) => {
847 eprintln!(
848 "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.",
849 source_dir.display(),
850 );
851 }
852 }
853
854 Ok(())
855}
856
857const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
860
861pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
877 let plugins_dir = match project_root {
878 Some(root) => root.join(".opencode").join("plugins"),
879 None => {
880 let config_dir =
881 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
882 config_dir
883 .ok_or_else(|| {
884 io::Error::new(
885 io::ErrorKind::NotFound,
886 "could not determine the config directory for the OpenCode plugin install",
887 )
888 })?
889 .join("opencode")
890 .join("plugins")
891 }
892 };
893
894 write_opencode_plugin_files(&plugins_dir)
895}
896
897fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
898 fs::create_dir_all(plugins_dir)?;
899 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
900 Ok(())
901}
902
903pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
915 let ext_root = gsd_home.join("extensions");
916 let reg_path = ext_root.join("registry.json");
917
918 let reg: Option<serde_json::Value> = if reg_path.exists() {
923 let content = fs::read_to_string(®_path)?;
924 let parsed: serde_json::Value = match serde_json::from_str(&content) {
925 Ok(v) => v,
926 Err(_) => return Ok(()), };
928 let corrupt = match parsed.as_object() {
929 None => true,
930 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
931 };
932 if corrupt {
933 return Ok(()); }
935 Some(parsed)
936 } else {
937 None
938 };
939
940 let stale = ext_root.join("tracevault-tracker");
942 if stale.exists() {
943 fs::remove_dir_all(&stale)?;
944 }
945
946 if let Some(mut reg) = reg {
948 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
949 let removed_tracker = entries.remove("tracevault-tracker").is_some();
950 let removed_inert = entries.remove("tracevault").is_some();
951 if removed_tracker || removed_inert {
952 let tmp = reg_path.with_extension("json.tmp");
954 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
955 fs::rename(&tmp, ®_path)?;
956 }
957 }
958 }
959 Ok(())
960}
961
962fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
972 update_json_file(hooks_path, "its hooks", |root| {
973 merge_hooks(root, ours, hooks_path)
974 })
975}
976
977pub(crate) fn update_json_file(
985 path: &Path,
986 what: &str,
987 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
988) -> io::Result<()> {
989 if path
994 .components()
995 .any(|c| c == std::path::Component::ParentDir)
996 {
997 return Err(io::Error::new(
998 io::ErrorKind::InvalidInput,
999 format!("refusing to use path with '..': {}", path.display()),
1000 ));
1001 }
1002 let target = match fs::symlink_metadata(path) {
1006 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
1007 _ => path.to_path_buf(),
1008 };
1009 for _ in 0..3 {
1015 let existing = read_existing(&target)?;
1016 let mut root: serde_json::Value = match &existing {
1017 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1018 io::Error::new(
1019 io::ErrorKind::InvalidData,
1020 format!("Failed to parse {}: {e}", path.display()),
1021 )
1022 })?,
1023 None => serde_json::json!({}),
1024 };
1025
1026 let before = existing.is_some().then(|| root.to_string());
1027 mutate(&mut root)?;
1028 if before.as_deref() == Some(root.to_string().as_str())
1029 || (existing.is_none() && root == serde_json::json!({}))
1030 {
1031 return Ok(());
1032 }
1033
1034 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1035 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1036 })?;
1037 let tmp = unique_temp_sibling(&target);
1038 let published = write_owner_only(&tmp, formatted.as_bytes())
1039 .and_then(|()| {
1040 match &existing {
1043 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1044 None => Ok(()),
1045 }
1046 })
1047 .and_then(|()| {
1048 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1049 == existing.as_ref().map(|(_, c)| c.clone());
1050 if unchanged {
1051 fs::rename(&tmp, &target).map(|()| true)
1052 } else {
1053 Ok(false)
1054 }
1055 });
1056 match published {
1057 Ok(true) => return Ok(()),
1058 Ok(false) => {
1059 let _ = fs::remove_file(&tmp);
1060 }
1061 Err(e) => {
1062 let _ = fs::remove_file(&tmp);
1063 return Err(e);
1064 }
1065 }
1066 }
1067 Err(io::Error::other(format!(
1068 "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1069 path.display()
1070 )))
1071}
1072
1073fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1075 let permissions = match fs::metadata(path) {
1076 Ok(meta) => meta.permissions(),
1077 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1078 Err(e) => return Err(e),
1079 };
1080 Ok(Some((permissions, fs::read_to_string(path)?)))
1081}
1082
1083fn unique_temp_sibling(target: &Path) -> PathBuf {
1087 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1088 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1089 let nanos = std::time::SystemTime::now()
1090 .duration_since(std::time::UNIX_EPOCH)
1091 .map(|d| d.subsec_nanos())
1092 .unwrap_or_default();
1093 let mut name = target.file_name().unwrap_or_default().to_os_string();
1094 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1095 target.with_file_name(name)
1096}
1097
1098fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1102 let mut options = fs::OpenOptions::new();
1103 options.write(true).create_new(true);
1104 #[cfg(unix)]
1105 {
1106 use std::os::unix::fs::OpenOptionsExt;
1107 options.mode(0o600);
1108 }
1109 options.open(path)?.write_all(contents)
1110}
1111
1112pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1116 let codex_dir = project_root.join(".codex");
1117 fs::create_dir_all(&codex_dir)?;
1118 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1119}
1120
1121pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1128 fs::create_dir_all(codex_dir)?;
1129 let base = codex_dir.canonicalize()?;
1131 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1132 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1133}
1134
1135const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1139
1140const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1141<!-- tracevault:workspace-mode -->
1142## TraceVault (workspace mode)
1143A session started in a registered repo's checkout is bound to that repo automatically. To work
1144on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1145policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1146one-off. Repos must already be registered with TraceVault.
1147";
1148
1149fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1155 if md_path
1157 .components()
1158 .any(|c| c == std::path::Component::ParentDir)
1159 {
1160 return Err(io::Error::new(
1161 io::ErrorKind::InvalidInput,
1162 format!("refusing to use path with '..': {}", md_path.display()),
1163 ));
1164 }
1165 let existing = if md_path.exists() {
1166 fs::read_to_string(md_path)?
1167 } else {
1168 String::new()
1169 };
1170 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1171 return Ok(());
1172 }
1173 let mut content = existing;
1174 if !content.is_empty() && !content.ends_with('\n') {
1175 content.push('\n');
1176 }
1177 if !content.is_empty() {
1178 content.push('\n');
1179 }
1180 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1181 fs::write(md_path, content)
1182}
1183
1184pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1188 let joined = base.join(name);
1189 if joined.parent() != Some(base) {
1190 return Err(io::Error::new(
1191 io::ErrorKind::InvalidInput,
1192 format!(
1193 "refusing to access path outside {}: {}",
1194 base.display(),
1195 joined.display()
1196 ),
1197 ));
1198 }
1199 Ok(joined)
1200}
1201
1202const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1208
1209fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1210 hook.get("command")
1211 .and_then(|c| c.as_str())
1212 .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1213}
1214
1215fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1222 let mut slot = None;
1223 let mut kept = Vec::with_capacity(entries.len());
1224 for mut entry in entries.drain(..) {
1225 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1226 let before = inner.len();
1227 inner.retain(|hook| !is_tracevault_hook(hook));
1228 if inner.is_empty() && before > 0 {
1229 slot.get_or_insert(kept.len());
1230 continue;
1231 }
1232 }
1233 kept.push(entry);
1234 }
1235 *entries = kept;
1236 slot
1237}
1238
1239fn merge_hooks(
1253 settings: &mut serde_json::Value,
1254 ours: &serde_json::Value,
1255 path: &Path,
1256) -> io::Result<()> {
1257 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1258 io::Error::new(
1259 io::ErrorKind::InvalidData,
1260 format!("{} is not a JSON object", path.display()),
1261 )
1262 })?;
1263
1264 let hooks_value = settings_obj
1265 .entry("hooks")
1266 .or_insert_with(|| serde_json::json!({}));
1267 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1268 io::Error::new(
1269 io::ErrorKind::InvalidData,
1270 format!("{} \"hooks\" key is not a JSON object", path.display()),
1271 )
1272 })?;
1273
1274 let empty = serde_json::Map::new();
1275 let ours_obj = ours.as_object().unwrap_or(&empty);
1276
1277 for event in ours_obj.keys() {
1279 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1280 return Err(io::Error::new(
1281 io::ErrorKind::InvalidData,
1282 format!(
1283 "{} \"hooks\".\"{event}\" is not a JSON array",
1284 path.display()
1285 ),
1286 ));
1287 }
1288 }
1289
1290 let mut emptied = Vec::new();
1291 for (event, value) in hooks_obj.iter_mut() {
1292 let Some(existing) = value.as_array_mut() else {
1293 continue;
1294 };
1295 let had_entries = !existing.is_empty();
1296 let slot = strip_tracevault_hooks(existing);
1297 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1298 match our_entries {
1299 Some(our_entries) => {
1300 let at = slot.unwrap_or(existing.len());
1301 existing.splice(at..at, our_entries.iter().cloned());
1302 }
1303 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1304 None => {}
1305 }
1306 }
1307 hooks_obj.retain(|event, _| !emptied.contains(event));
1309
1310 for (event, our_array) in ours_obj {
1311 if !hooks_obj.contains_key(event) {
1312 hooks_obj.insert(event.clone(), our_array.clone());
1313 }
1314 }
1315
1316 Ok(())
1317}
1318
1319pub(crate) fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
1323 let text = match fs::read_to_string(path) {
1324 Ok(text) => text,
1325 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
1326 Err(e) => return Err(e),
1327 };
1328 let settings: serde_json::Value =
1329 serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1330 Ok(settings
1331 .get("hooks")
1332 .and_then(|h| h.as_object())
1333 .into_iter()
1334 .flat_map(|events| events.values())
1335 .filter_map(|groups| groups.as_array())
1336 .flatten()
1337 .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
1338 .flatten()
1339 .any(is_tracevault_hook))
1340}
1341
1342pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
1346 merge_hooks_into_file(path, &tracevault_hooks())
1347}
1348
1349pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1355 fs::create_dir_all(claude_dir)?;
1356
1357 let base = claude_dir.canonicalize()?;
1360
1361 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1363
1364 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1366}
1367
1368pub fn write_global_user_config_in(
1378 config_root: &Path,
1379 requested: Option<UserContext>,
1380) -> io::Result<Option<PathBuf>> {
1381 fs::create_dir_all(config_root)?;
1382 let mut config = crate::config::try_load_user_config_in(config_root)
1384 .ok()
1385 .flatten()
1386 .unwrap_or_default();
1387 let user_context = requested
1389 .or_else(|| config.user_context.clone())
1390 .unwrap_or(UserContext::Toggle(true));
1391 let active = user_context
1392 .resolve()
1393 .map(|_| user_context.path_in(config_root));
1394 config.user_context = Some(user_context);
1395 fs::write(user_config_path_in(config_root), config.to_toml())?;
1396 if let Some(ref ctx_path) = active {
1397 if !ctx_path.exists() {
1398 Context::default().save_to(ctx_path)?;
1399 }
1400 }
1401 Ok(active)
1402}
1403
1404#[cfg(test)]
1405mod tests {
1406 use super::*;
1407 use std::io::{BufRead, BufReader, Write};
1408 use std::net::TcpListener;
1409 use std::thread;
1410
1411 #[test]
1417 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1418 let notice = codex_hook_trust_notice();
1419 assert!(
1420 notice.contains("hook trust"),
1421 "notice must name what is missing: {notice}"
1422 );
1423 assert!(
1424 notice.contains("codex") && notice.contains("approve"),
1425 "notice must tell the user to run codex and approve the prompt: {notice}"
1426 );
1427 assert!(
1428 notice.contains("--dangerously-bypass-hook-trust"),
1429 "notice must name the flag for unattended/CI runs: {notice}"
1430 );
1431 assert!(
1432 notice.contains("silently"),
1433 "notice must say the failure is silent, which is why it needs saying: {notice}"
1434 );
1435 }
1436
1437 fn spawn_once(response: String) -> String {
1440 let response: &'static str = Box::leak(response.into_boxed_str());
1441 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1442 let addr = listener.local_addr().unwrap();
1443 thread::spawn(move || {
1444 if let Ok((stream, _)) = listener.accept() {
1445 let mut reader = BufReader::new(stream);
1446 let mut request_line = String::new();
1447 let _ = reader.read_line(&mut request_line);
1448 let mut stream = reader.into_inner();
1449 let _ = stream.write_all(response.as_bytes());
1450 let _ = stream.flush();
1451 }
1452 });
1453 format!("http://{addr}")
1454 }
1455
1456 fn http_response(status: &str, body: &str) -> String {
1459 format!(
1460 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1461 status,
1462 body.len(),
1463 body
1464 )
1465 }
1466
1467 fn add_origin_remote(dir: &Path, url: &str) {
1468 let ok = std::process::Command::new("git")
1469 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1470 .status()
1471 .expect("git remote add failed")
1472 .success();
1473 assert!(ok, "git remote add must succeed");
1474 }
1475
1476 #[test]
1477 fn linked_worktree_primary_detects_linked_and_primary() {
1478 let tmp = tempfile::tempdir().unwrap();
1479 let repo = tmp.path().join("repo");
1480 let wt = tmp.path().join("linked-wt");
1481 std::fs::create_dir_all(&repo).unwrap();
1482 crate::test_helpers::init_git_repo(&repo);
1483 crate::test_helpers::add_worktree(&repo, &wt);
1484
1485 assert!(
1487 linked_worktree_primary(&repo).is_none(),
1488 "primary checkout must not be flagged as a linked worktree"
1489 );
1490 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1492 assert_eq!(
1493 primary.canonicalize().unwrap(),
1494 repo.canonicalize().unwrap(),
1495 "must resolve to the primary repo root"
1496 );
1497 }
1498
1499 #[test]
1500 fn linked_worktree_primary_none_for_non_git() {
1501 let tmp = tempfile::tempdir().unwrap();
1502 assert!(
1503 linked_worktree_primary(tmp.path()).is_none(),
1504 "a non-git directory is not a linked worktree"
1505 );
1506 }
1507
1508 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1510 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1511 }
1512
1513 #[test]
1514 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1515 let mut settings = serde_json::json!({});
1516 let ours = tracevault_hooks();
1517 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1518
1519 let hooks = settings.get("hooks").unwrap();
1520 for event in [
1521 "PreToolUse",
1522 "PostToolUse",
1523 "Notification",
1524 "Stop",
1525 "SessionEnd",
1526 "SubagentStop",
1527 "SessionStart",
1528 "UserPromptSubmit",
1529 ] {
1530 assert!(hooks.get(event).is_some(), "missing event {event}");
1531 }
1532 }
1533
1534 #[test]
1535 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1536 let mut settings = serde_json::json!({
1537 "model": "opus",
1538 "hooks": {
1539 "PreToolUse": [{
1540 "matcher": "",
1541 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1542 }]
1543 }
1544 });
1545 let ours = tracevault_hooks();
1546 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1547
1548 assert_eq!(settings.get("model").unwrap(), "opus");
1550
1551 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1552 assert_eq!(pre_tool_use.len(), 2);
1554 let commands: Vec<&str> = pre_tool_use
1555 .iter()
1556 .map(|e| entry_command(e).unwrap())
1557 .collect();
1558 assert!(commands.contains(&"my-own-hook"));
1559 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1560
1561 assert!(settings["hooks"]["SessionStart"].is_array());
1563 }
1564
1565 #[test]
1566 fn merge_hooks_is_idempotent() {
1567 let mut settings = serde_json::json!({});
1568 let ours = tracevault_hooks();
1569 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1570 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1571
1572 for event in [
1573 "PreToolUse",
1574 "PostToolUse",
1575 "Notification",
1576 "Stop",
1577 "SessionEnd",
1578 "SubagentStop",
1579 "SessionStart",
1580 "UserPromptSubmit",
1581 ] {
1582 let arr = settings["hooks"][event].as_array().unwrap();
1583 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1584 }
1585 }
1586
1587 #[test]
1588 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1589 let mut settings = serde_json::json!({
1593 "hooks": {
1594 "PreToolUse": [{
1595 "matcher": "Write|Edit|Bash",
1596 "hooks": [
1597 { "type": "command", "command": "other", "timeout": 3 },
1598 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1599 ]
1600 }]
1601 }
1602 });
1603 merge_hooks(
1604 &mut settings,
1605 &tracevault_hooks(),
1606 Path::new("settings.json"),
1607 )
1608 .unwrap();
1609
1610 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1611 assert_eq!(
1612 pre_tool_use[0],
1613 serde_json::json!({
1614 "matcher": "Write|Edit|Bash",
1615 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1616 })
1617 );
1618 assert_eq!(
1619 &pre_tool_use[1..],
1620 tracevault_hooks()["PreToolUse"].as_array().unwrap()
1621 );
1622 }
1623
1624 fn stale_tracevault_hooks() -> serde_json::Value {
1627 let entry = |matcher: &str, event: &str| {
1628 serde_json::json!([{
1629 "matcher": matcher,
1630 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1631 }])
1632 };
1633 serde_json::json!({
1634 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1635 "PostToolUse": entry("", "post-tool-use"),
1636 "Notification": entry("", "notification"),
1637 "Stop": entry("", "stop"),
1638 })
1639 }
1640
1641 #[test]
1642 fn merge_hooks_upgrades_stale_tracevault_entries() {
1643 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1644 merge_hooks(
1645 &mut settings,
1646 &tracevault_hooks(),
1647 Path::new("settings.json"),
1648 )
1649 .unwrap();
1650 assert_eq!(settings["hooks"], tracevault_hooks());
1651 }
1652
1653 #[test]
1654 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1655 let mut settings = serde_json::json!({
1658 "hooks": {
1659 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1660 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1661 "Custom": "left alone"
1662 }
1663 });
1664 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1665
1666 let hooks = settings["hooks"].as_object().unwrap();
1667 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
1668 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
1669 assert_eq!(hooks["Custom"], "left alone");
1670 for (event, entries) in codex_hooks().as_object().unwrap() {
1671 assert_eq!(&hooks[event], entries, "{event}");
1672 }
1673 }
1674
1675 #[test]
1676 fn merge_hooks_rerun_keeps_our_entry_in_place() {
1677 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
1680 settings["hooks"]["Stop"]
1681 .as_array_mut()
1682 .unwrap()
1683 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
1684 let before = settings.clone();
1685 merge_hooks(
1686 &mut settings,
1687 &tracevault_hooks(),
1688 Path::new("settings.json"),
1689 )
1690 .unwrap();
1691 assert_eq!(settings.to_string(), before.to_string());
1692 }
1693
1694 #[test]
1695 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
1696 let foreign = serde_json::json!({
1697 "matcher": "",
1698 "hooks": [
1699 { "type": "command", "command": "tracevault-wrapper stream" },
1700 { "type": "command", "command": "echo tracevault stream" },
1701 { "type": "command", "command": " tracevault check" }
1702 ]
1703 });
1704 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
1705 merge_hooks(
1706 &mut settings,
1707 &tracevault_hooks(),
1708 Path::new("settings.json"),
1709 )
1710 .unwrap();
1711 assert_eq!(settings["hooks"]["Stop"][0], foreign);
1712 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
1713 }
1714
1715 #[test]
1716 fn merge_hooks_errors_on_non_object_top_level() {
1717 let mut settings = serde_json::json!([1, 2, 3]);
1718 let ours = tracevault_hooks();
1719 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1720 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1721 assert!(err.to_string().contains("settings.json"));
1722 }
1723
1724 #[test]
1725 fn merge_hooks_errors_on_non_object_top_level_number() {
1726 let mut settings = serde_json::json!(42);
1727 let ours = tracevault_hooks();
1728 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1729 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1730 }
1731
1732 #[test]
1733 fn merge_hooks_errors_on_non_object_hooks() {
1734 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1735 let ours = tracevault_hooks();
1736 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1737 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1738 assert!(err.to_string().contains("hooks"));
1739 }
1740
1741 #[test]
1742 fn merge_hooks_errors_on_non_array_event_value() {
1743 let mut settings = serde_json::json!({
1744 "hooks": {
1745 "PreToolUse": "not-an-array"
1746 }
1747 });
1748 let ours = tracevault_hooks();
1749 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1750 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1751 assert!(err.to_string().contains("PreToolUse"));
1752 }
1753
1754 #[test]
1755 fn install_global_hooks_writes_settings_and_claude_md() {
1756 let tmp = tempfile::tempdir().unwrap();
1757 let claude_dir = tmp.path().join(".claude");
1758
1759 install_global_hooks(&claude_dir).unwrap();
1760
1761 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1762 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1763 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1764 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1765 }
1766
1767 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1768 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1769 }
1770
1771 #[test]
1772 fn install_global_hooks_is_idempotent() {
1773 let tmp = tempfile::tempdir().unwrap();
1774 let claude_dir = tmp.path().join(".claude");
1775
1776 install_global_hooks(&claude_dir).unwrap();
1777 install_global_hooks(&claude_dir).unwrap();
1778
1779 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1780 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1781 for event in [
1782 "PreToolUse",
1783 "PostToolUse",
1784 "Notification",
1785 "Stop",
1786 "SessionEnd",
1787 "SubagentStop",
1788 "SessionStart",
1789 "UserPromptSubmit",
1790 ] {
1791 let arr = settings["hooks"][event].as_array().unwrap();
1792 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1793 }
1794
1795 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1796 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1797 assert_eq!(
1798 marker_count, 1,
1799 "CLAUDE.md marker should appear exactly once"
1800 );
1801 }
1802
1803 #[test]
1804 fn install_global_hooks_preserves_existing_claude_md_content() {
1805 let tmp = tempfile::tempdir().unwrap();
1806 let claude_dir = tmp.path().join(".claude");
1807 fs::create_dir_all(&claude_dir).unwrap();
1808 fs::write(
1809 claude_dir.join("CLAUDE.md"),
1810 "# My existing notes\nSome content.\n",
1811 )
1812 .unwrap();
1813
1814 install_global_hooks(&claude_dir).unwrap();
1815
1816 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1817 assert!(claude_md.contains("# My existing notes"));
1818 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1819 }
1820
1821 #[test]
1822 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1823 let tmp = tempfile::tempdir().unwrap();
1824 let claude_dir = tmp.path().join(".claude");
1825
1826 install_global_hooks(&claude_dir).unwrap();
1827
1828 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1829 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1830 assert!(settings["hooks"].get("SessionStart").is_some());
1831
1832 let leftover = fs::read_dir(&claude_dir)
1833 .unwrap()
1834 .filter_map(|e| e.ok())
1835 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1836 assert!(
1837 !leftover,
1838 "no settings.json.tmp should remain after install"
1839 );
1840 }
1841
1842 #[test]
1843 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1844 let tmp = tempfile::tempdir().unwrap();
1845 let claude_dir = tmp.path().join(".claude");
1846 fs::create_dir_all(&claude_dir).unwrap();
1847 let settings_path = claude_dir.join("settings.json");
1848 let original = "[1, 2, 3]";
1849 fs::write(&settings_path, original).unwrap();
1850
1851 let err = install_global_hooks(&claude_dir).unwrap_err();
1852 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1853
1854 let after = fs::read_to_string(&settings_path).unwrap();
1857 assert_eq!(after, original);
1858 let leftover = fs::read_dir(&claude_dir)
1859 .unwrap()
1860 .filter_map(|e| e.ok())
1861 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1862 assert!(!leftover, "no tmp file should be left behind on error");
1863 }
1864
1865 #[test]
1866 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1867 let tmp = tempfile::tempdir().unwrap();
1868 let claude_dir = tmp.path().join(".claude");
1869 fs::create_dir_all(&claude_dir).unwrap();
1870 let settings_path = claude_dir.join("settings.json");
1871 let original = r#"{"hooks": "oops"}"#;
1872 fs::write(&settings_path, original).unwrap();
1873
1874 let err = install_global_hooks(&claude_dir).unwrap_err();
1875 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1876
1877 let after = fs::read_to_string(&settings_path).unwrap();
1878 assert_eq!(after, original);
1879 }
1880
1881 #[test]
1882 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1883 let tmp = tempfile::tempdir().unwrap();
1884 let claude_dir = tmp.path().join(".claude");
1885 fs::create_dir_all(&claude_dir).unwrap();
1886 let settings_path = claude_dir.join("settings.json");
1887 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1888 fs::write(&settings_path, original).unwrap();
1889
1890 let err = install_global_hooks(&claude_dir).unwrap_err();
1891 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1892
1893 let after = fs::read_to_string(&settings_path).unwrap();
1894 assert_eq!(after, original);
1895 }
1896
1897 #[test]
1898 fn safe_join_allows_direct_child_file() {
1899 let tmp = tempfile::tempdir().unwrap();
1900 let base = tmp.path();
1901 let result = safe_join(base, "settings.json").unwrap();
1902 assert_eq!(result.parent(), Some(base));
1903 assert_eq!(result.file_name().unwrap(), "settings.json");
1904 }
1905
1906 #[test]
1907 fn safe_join_rejects_path_traversal() {
1908 let tmp = tempfile::tempdir().unwrap();
1909 let base = tmp.path();
1910 let result = safe_join(base, "../evil");
1911 assert!(result.is_err());
1912 let err = result.unwrap_err();
1913 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1914 assert!(err.to_string().contains("refusing to access path outside"));
1915 }
1916
1917 #[test]
1918 fn safe_join_rejects_absolute_path() {
1919 let tmp = tempfile::tempdir().unwrap();
1920 let base = tmp.path();
1921 let result = safe_join(base, "/etc/passwd");
1922 assert!(result.is_err());
1925 }
1926
1927 #[test]
1928 fn write_global_user_config_enables_and_creates_context() {
1929 let root = tempfile::tempdir().unwrap();
1930 let active = write_global_user_config_in(root.path(), None).unwrap();
1931 let cfg = crate::config::try_load_user_config_in(root.path())
1932 .unwrap()
1933 .unwrap();
1934 assert_eq!(
1937 cfg.user_context.unwrap().resolve_in(root.path()),
1938 Some(crate::config::default_user_context_path_in(root.path()))
1939 );
1940 let ctx = crate::config::default_user_context_path_in(root.path());
1941 assert_eq!(active, Some(ctx.clone()));
1942 assert!(ctx.exists());
1943 }
1944
1945 #[test]
1946 fn write_global_user_config_can_disable() {
1947 let root = tempfile::tempdir().unwrap();
1948 let active = write_global_user_config_in(
1949 root.path(),
1950 Some(crate::config::UserContext::Toggle(false)),
1951 )
1952 .unwrap();
1953 let cfg = crate::config::try_load_user_config_in(root.path())
1954 .unwrap()
1955 .unwrap();
1956 assert!(matches!(
1957 cfg.user_context,
1958 Some(crate::config::UserContext::Toggle(false))
1959 ));
1960 assert_eq!(active, None, "disabled → no active context path");
1961 assert!(
1963 !crate::config::default_user_context_path_in(root.path()).exists(),
1964 "disabled user context must not create a context.json"
1965 );
1966 }
1967
1968 #[test]
1969 fn write_global_user_config_custom_path_seeds_that_file_only() {
1970 let root = tempfile::tempdir().unwrap();
1971 let custom = root.path().join("custom-ctx.json");
1972 let active = write_global_user_config_in(
1973 root.path(),
1974 Some(crate::config::UserContext::Path(
1975 custom.to_string_lossy().into_owned(),
1976 )),
1977 )
1978 .unwrap();
1979 assert_eq!(active, Some(custom.clone()));
1980 assert!(custom.exists(), "the configured custom path must be seeded");
1981 assert!(
1982 !crate::config::default_user_context_path_in(root.path()).exists(),
1983 "the default context.json must NOT be created when a custom path is configured"
1984 );
1985 }
1986
1987 #[test]
1988 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1989 let root = tempfile::tempdir().unwrap();
1990 let custom = root.path().join("custom-ctx.json");
1991 write_global_user_config_in(
1993 root.path(),
1994 Some(crate::config::UserContext::Path(
1995 custom.to_string_lossy().into_owned(),
1996 )),
1997 )
1998 .unwrap();
1999 let active = write_global_user_config_in(root.path(), None).unwrap();
2001 assert_eq!(
2002 active,
2003 Some(custom.clone()),
2004 "re-run without flags must preserve the custom path"
2005 );
2006 let cfg = crate::config::try_load_user_config_in(root.path())
2007 .unwrap()
2008 .unwrap();
2009 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
2010 }
2011
2012 #[test]
2013 fn install_global_codex_hooks_writes_and_is_idempotent() {
2014 let tmp = tempfile::tempdir().unwrap();
2015 let codex_dir = tmp.path().join(".codex");
2016
2017 install_global_codex_hooks(&codex_dir).unwrap();
2018 install_global_codex_hooks(&codex_dir).unwrap();
2019
2020 let v: serde_json::Value =
2021 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2022 .unwrap();
2023 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2024 let arr = v["hooks"][event].as_array().unwrap();
2025 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
2026 }
2027 assert!(v["hooks"].get("PreToolUse").is_none());
2028 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
2030 assert_eq!(
2031 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
2032 1,
2033 "AGENTS.md workspace-mode block must appear exactly once"
2034 );
2035 let leftover = fs::read_dir(&codex_dir)
2037 .unwrap()
2038 .filter_map(|e| e.ok())
2039 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2040 assert!(!leftover);
2041 }
2042
2043 #[test]
2044 fn codex_hooks_has_expected_events_and_commands() {
2045 let h = codex_hooks();
2046 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2047 assert!(h.get(event).is_some(), "missing codex event {event}");
2048 }
2049 assert!(h.get("PreToolUse").is_none());
2053 assert!(h.get("Notification").is_none());
2054 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2056 assert_eq!(
2057 cmd("PostToolUse"),
2058 "tracevault stream --event post-tool-use --agent codex"
2059 );
2060 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2061 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2062 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2063 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2065 }
2066
2067 #[test]
2068 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2069 let tmp = tempfile::tempdir().unwrap();
2070 install_codex_hooks(tmp.path()).unwrap();
2071 install_codex_hooks(tmp.path()).unwrap();
2072
2073 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2074 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2075 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2076 let arr = v["hooks"][event].as_array().unwrap();
2077 assert_eq!(
2078 arr.len(),
2079 1,
2080 "event {event} must not be duplicated on re-run"
2081 );
2082 }
2083 assert!(v["hooks"].get("PreToolUse").is_none());
2084 }
2085
2086 #[test]
2087 fn install_codex_hooks_preserves_existing_user_hook() {
2088 let tmp = tempfile::tempdir().unwrap();
2089 let codex_dir = tmp.path().join(".codex");
2090 fs::create_dir_all(&codex_dir).unwrap();
2091 fs::write(
2094 codex_dir.join("hooks.json"),
2095 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2096 )
2097 .unwrap();
2098
2099 install_codex_hooks(tmp.path()).unwrap();
2100
2101 let v: serde_json::Value =
2102 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2103 .unwrap();
2104 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2106 .as_array()
2107 .unwrap()
2108 .iter()
2109 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2110 .collect();
2111 assert!(
2112 post_cmds.contains(&"my-own"),
2113 "user PostToolUse hook preserved"
2114 );
2115 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2116 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2118 .as_array()
2119 .unwrap()
2120 .iter()
2121 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2122 .collect();
2123 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2124 }
2125
2126 const FOREIGN_SETTINGS: &str = r#"{
2130 "permissions": { "allow": ["Bash(ls)"] },
2131 "hooks": {
2132 "PreToolUse": [
2133 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2134 { "matcher": "Write|Edit", "hooks": [
2135 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2136 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2137 ] }
2138 ],
2139 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2140 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2141 },
2142 "model": "opus"
2143}"#;
2144
2145 fn expected_foreign_entries() -> Vec<String> {
2149 [
2150 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2151 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2152 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2153 ]
2154 .map(String::from)
2155 .to_vec()
2156 }
2157
2158 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2159 entry["hooks"]
2160 .as_array()
2161 .unwrap()
2162 .iter()
2163 .any(is_tracevault_hook)
2164 }
2165
2166 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2167 let v: serde_json::Value =
2168 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2169 assert_eq!(
2170 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2171 ["permissions", "hooks", "model"],
2172 "top-level keys kept, in their order"
2173 );
2174 assert_eq!(
2175 v["permissions"],
2176 serde_json::json!({ "allow": ["Bash(ls)"] })
2177 );
2178 let hooks = v["hooks"].as_object().unwrap();
2179 let foreign: Vec<String> = hooks
2180 .values()
2181 .flat_map(|entries| entries.as_array().unwrap())
2182 .filter(|e| !holds_tracevault_hook(e))
2183 .map(|e| e.to_string())
2184 .collect();
2185 assert_eq!(foreign, expected_foreign_entries());
2186 let ours = ours.as_object().unwrap();
2187 for (event, entries) in hooks {
2188 let mine: Vec<&serde_json::Value> = entries
2189 .as_array()
2190 .unwrap()
2191 .iter()
2192 .filter(|e| holds_tracevault_hook(e))
2193 .collect();
2194 let want: Vec<&serde_json::Value> = ours
2195 .get(event)
2196 .map(|o| o.as_array().unwrap().iter().collect())
2197 .unwrap_or_default();
2198 assert_eq!(mine, want, "TraceVault entries under {event}");
2199 }
2200 for event in ours.keys() {
2201 assert!(hooks.contains_key(event), "missing {event}");
2202 }
2203 }
2204
2205 #[test]
2206 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2207 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2208 let tmp = tempfile::tempdir().unwrap();
2209 let path = tmp.path().join(".claude").join(target.filename());
2210 fs::create_dir_all(path.parent().unwrap()).unwrap();
2211 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2212
2213 install_claude_hooks(tmp.path(), target).unwrap();
2214 assert_installed_over_foreign(&path, &tracevault_hooks());
2215
2216 let after_first = fs::read(&path).unwrap();
2218 install_claude_hooks(tmp.path(), target).unwrap();
2219 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2220 }
2221 }
2222
2223 #[test]
2224 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2225 let tmp = tempfile::tempdir().unwrap();
2226 let claude_dir = tmp.path().join(".claude");
2227 fs::create_dir_all(&claude_dir).unwrap();
2228 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2229
2230 install_global_hooks(&claude_dir).unwrap();
2231 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2232 }
2233
2234 #[test]
2235 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2236 for global in [false, true] {
2237 let tmp = tempfile::tempdir().unwrap();
2238 let codex_dir = tmp.path().join(".codex");
2239 fs::create_dir_all(&codex_dir).unwrap();
2240 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2241
2242 if global {
2243 install_global_codex_hooks(&codex_dir).unwrap();
2244 } else {
2245 install_codex_hooks(tmp.path()).unwrap();
2246 }
2247 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2248 }
2249 }
2250
2251 #[test]
2252 fn up_to_date_hook_file_is_not_rewritten() {
2253 let tmp = tempfile::tempdir().unwrap();
2255 let path = tmp.path().join(".claude/settings.json");
2256 fs::create_dir_all(path.parent().unwrap()).unwrap();
2257 let mut body = Vec::new();
2258 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
2259 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2260 serde::Serialize::serialize(
2261 &serde_json::json!({ "hooks": tracevault_hooks() }),
2262 &mut ser,
2263 )
2264 .unwrap();
2265 fs::write(&path, &body).unwrap();
2266
2267 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2268 assert_eq!(fs::read(&path).unwrap(), body);
2269 }
2270
2271 #[test]
2272 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2273 for (target, body) in [
2274 (ClaudeSettingsTarget::Shared, "{ not json"),
2275 (ClaudeSettingsTarget::Local, "[1, 2]"),
2276 (ClaudeSettingsTarget::Shared, "null"),
2277 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2278 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2279 ] {
2280 let tmp = tempfile::tempdir().unwrap();
2281 let path = tmp.path().join(".claude").join(target.filename());
2282 fs::create_dir_all(path.parent().unwrap()).unwrap();
2283 fs::write(&path, body).unwrap();
2284
2285 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2286 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2287 assert_eq!(
2288 fs::read_to_string(&path).unwrap(),
2289 body,
2290 "file must be untouched"
2291 );
2292 assert_eq!(
2293 fs::read_dir(path.parent().unwrap()).unwrap().count(),
2294 1,
2295 "no temp file left behind"
2296 );
2297 }
2298 }
2299
2300 #[test]
2301 fn concurrent_installs_never_publish_a_partial_file() {
2302 let tmp = tempfile::tempdir().unwrap();
2308 let path = tmp.path().join("settings.json");
2309 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2310 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2311 let reader = {
2312 let (path, done) = (path.clone(), done.clone());
2313 std::thread::spawn(move || {
2314 while !done.load(std::sync::atomic::Ordering::Relaxed) {
2315 let body = fs::read_to_string(&path).unwrap();
2316 serde_json::from_str::<serde_json::Value>(&body).unwrap();
2317 }
2318 })
2319 };
2320 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2321 .into_iter()
2322 .map(|ours| {
2323 let path = path.clone();
2324 std::thread::spawn(move || {
2325 for _ in 0..200 {
2326 if let Err(e) = merge_hooks_into_file(&path, &ours) {
2327 assert!(e.to_string().contains("kept changing"), "{e}");
2328 }
2329 }
2330 })
2331 })
2332 .collect();
2333 for writer in writers {
2334 writer.join().unwrap();
2335 }
2336 done.store(true, std::sync::atomic::Ordering::Relaxed);
2337 reader.join().unwrap();
2338 let v: serde_json::Value =
2339 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2340 assert_eq!(v["model"], "opus");
2341 assert_eq!(
2342 fs::read_dir(tmp.path()).unwrap().count(),
2343 1,
2344 "no temp file left"
2345 );
2346 }
2347
2348 #[cfg(unix)]
2349 #[test]
2350 fn install_claude_hooks_keeps_file_permissions() {
2351 use std::os::unix::fs::PermissionsExt;
2352 let tmp = tempfile::tempdir().unwrap();
2353 let path = tmp.path().join(".claude/settings.local.json");
2354 fs::create_dir_all(path.parent().unwrap()).unwrap();
2355 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2356 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2357
2358 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2359
2360 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2361 assert_eq!(mode, 0o600);
2362 assert_installed_over_foreign(&path, &tracevault_hooks());
2363 }
2364
2365 #[cfg(unix)]
2366 #[test]
2367 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2368 let tmp = tempfile::tempdir().unwrap();
2369 let central = tmp.path().join("central/claude-settings.json");
2370 fs::create_dir_all(central.parent().unwrap()).unwrap();
2371 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
2372 let link = tmp.path().join("repo/.claude/settings.json");
2373 fs::create_dir_all(link.parent().unwrap()).unwrap();
2374 std::os::unix::fs::symlink(¢ral, &link).unwrap();
2375
2376 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2377
2378 assert!(fs::symlink_metadata(&link)
2379 .unwrap()
2380 .file_type()
2381 .is_symlink());
2382 assert_installed_over_foreign(¢ral, &tracevault_hooks());
2383 }
2384
2385 #[cfg(unix)]
2386 #[test]
2387 fn install_claude_hooks_refuses_dangling_symlink() {
2388 let tmp = tempfile::tempdir().unwrap();
2389 let link = tmp.path().join(".claude/settings.json");
2390 fs::create_dir_all(link.parent().unwrap()).unwrap();
2391 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2392
2393 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2394 assert!(fs::symlink_metadata(&link)
2395 .unwrap()
2396 .file_type()
2397 .is_symlink());
2398 assert!(!tmp.path().join("gone.json").exists());
2399 }
2400
2401 #[test]
2402 fn validate_init_flags_rejects_claude_settings_with_codex() {
2403 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2404 }
2405
2406 #[test]
2407 fn validate_init_flags_allows_codex_without_claude_settings() {
2408 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2409 }
2410
2411 #[test]
2412 fn validate_init_flags_allows_claude_with_claude_settings() {
2413 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2414 }
2415
2416 #[test]
2417 fn merge_hooks_into_file_rejects_parent_dir() {
2418 let tmp = tempfile::tempdir().unwrap();
2419 let bad = tmp.path().join("..").join("hooks.json");
2420 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2421 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2422 }
2423
2424 #[test]
2425 fn append_workspace_md_rejects_parent_dir() {
2426 let tmp = tempfile::tempdir().unwrap();
2427 let bad = tmp.path().join("..").join("AGENTS.md");
2428 let err = append_workspace_md(&bad).unwrap_err();
2429 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2430 }
2431
2432 #[tokio::test]
2433 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2434 let tmp = tempfile::tempdir().unwrap();
2435 let root = tmp.path();
2436 crate::test_helpers::init_git_repo(root);
2437 fs::create_dir_all(root.join(".tracevault")).unwrap();
2440 fs::write(
2441 root.join(".tracevault/config.toml"),
2442 "api_key = \"tvk_test\"\n",
2443 )
2444 .unwrap();
2445
2446 let entry = init_in_directory(
2447 root,
2448 None,
2449 None,
2450 false,
2451 Some(crate::config::UserContext::Toggle(false)),
2452 crate::agent::Agent::Codex,
2453 )
2454 .await
2455 .unwrap();
2456
2457 assert!(root.join(".codex").join("hooks.json").exists());
2459 assert!(!root.join(".claude").join("settings.json").exists());
2460 assert_eq!(entry, ".codex/hooks.json");
2461
2462 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2464 assert!(gi.contains(".codex/hooks.json"));
2465 assert!(gi.contains(".tracevault/"));
2466 }
2467
2468 #[tokio::test]
2480 async fn init_in_directory_registers_repo_and_persists_repo_id() {
2481 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2482 let tmp = tempfile::tempdir().unwrap();
2483 let root = tmp.path();
2484 crate::test_helpers::init_git_repo(root);
2485 add_origin_remote(root, "git@github.com:org/repo.git");
2486
2487 let repo_id = "11111111-1111-4111-8111-111111111111";
2488 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2489 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2492 http_response("404 Not Found", NO_REMOTE),
2493 http_response("200 OK", &body),
2494 ]);
2495
2496 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2497 _guard.set("XDG_CONFIG_HOME", tmp.path());
2498 _guard.set("TRACEVAULT_API_KEY", "tok");
2499 _guard.remove("TRACEVAULT_SERVER_URL");
2500
2501 init_in_directory(
2502 root,
2503 Some(&base),
2504 None,
2505 true,
2506 Some(crate::config::UserContext::Toggle(false)),
2507 crate::agent::Agent::Codex,
2508 )
2509 .await
2510 .unwrap();
2511
2512 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2513 assert_eq!(
2514 cfg.repo_id,
2515 Some(repo_id.to_string()),
2516 "successful registration must persist repo_id to config.toml"
2517 );
2518 }
2519
2520 #[tokio::test]
2526 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2527 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2528 let tmp = tempfile::tempdir().unwrap();
2529 let root = tmp.path();
2530 crate::test_helpers::init_git_repo(root);
2531 add_origin_remote(root, "git@github.com:org/repo.git");
2532
2533 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2534 http_response("404 Not Found", NO_REMOTE),
2535 http_response("403 Forbidden", ""),
2536 ]);
2537
2538 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2539 _guard.set("XDG_CONFIG_HOME", tmp.path());
2540 _guard.set("TRACEVAULT_API_KEY", "tok");
2541 _guard.remove("TRACEVAULT_SERVER_URL");
2542
2543 let entry = init_in_directory(
2544 root,
2545 Some(&base),
2546 None,
2547 true,
2548 Some(crate::config::UserContext::Toggle(false)),
2549 crate::agent::Agent::Codex,
2550 )
2551 .await
2552 .expect("a registration failure (403) must not abort init itself");
2553 assert_eq!(entry, ".codex/hooks.json");
2554
2555 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2556 assert!(
2557 cfg.repo_id.is_none(),
2558 "a 403 registration failure must not persist a repo_id"
2559 );
2560 }
2561
2562 #[tokio::test]
2567 async fn registration_failure_message_flags_403_as_not_authorized() {
2568 let base = spawn_once(http_response("403 Forbidden", ""));
2569 let client = ApiClient::new(&base, Some("tok"));
2570 let err = client
2571 .register_repo(crate::api_client::RegisterRepoRequest {
2572 repo_name: "repo".into(),
2573 github_url: Some("git@github.com:org/repo.git".into()),
2574 })
2575 .await
2576 .unwrap_err();
2577 let msg = registration_failure_message(err.as_ref());
2578 assert!(
2579 msg.contains("not authorized"),
2580 "403 registration failure must surface a not-authorized message; got: {msg}"
2581 );
2582 }
2583
2584 #[tokio::test]
2587 async fn registration_failure_message_generic_for_non_403() {
2588 let base = spawn_once(http_response("500 Internal Server Error", ""));
2589 let client = ApiClient::new(&base, Some("tok"));
2590 let err = client
2591 .register_repo(crate::api_client::RegisterRepoRequest {
2592 repo_name: "repo".into(),
2593 github_url: Some("git@github.com:org/repo.git".into()),
2594 })
2595 .await
2596 .unwrap_err();
2597 let msg = registration_failure_message(err.as_ref());
2598 assert!(
2599 msg.contains("could not register repo on server"),
2600 "got: {msg}"
2601 );
2602 assert!(!msg.contains("not authorized"), "got: {msg}");
2603 }
2604
2605 #[tokio::test]
2610 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2611 let base = spawn_once(http_response(
2612 "500 Internal Server Error",
2613 "upstream error 403 from proxy",
2614 ));
2615 let client = ApiClient::new(&base, Some("tok"));
2616 let err = client
2617 .register_repo(crate::api_client::RegisterRepoRequest {
2618 repo_name: "repo".into(),
2619 github_url: Some("git@github.com:org/repo.git".into()),
2620 })
2621 .await
2622 .unwrap_err();
2623 let msg = registration_failure_message(err.as_ref());
2624 assert!(
2625 !msg.contains("not authorized"),
2626 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2627 );
2628 assert!(
2629 msg.contains("could not register repo on server"),
2630 "got: {msg}"
2631 );
2632 }
2633
2634 #[tokio::test]
2638 async fn registration_failure_message_flags_404_as_version_mismatch() {
2639 let base = spawn_once(http_response("404 Not Found", ""));
2640 let client = ApiClient::new(&base, Some("tok"));
2641 let err = client
2642 .register_repo(crate::api_client::RegisterRepoRequest {
2643 repo_name: "repo".into(),
2644 github_url: Some("git@github.com:org/repo.git".into()),
2645 })
2646 .await
2647 .unwrap_err();
2648 let msg = registration_failure_message(err.as_ref());
2649 assert!(
2650 msg.to_lowercase().contains("version mismatch"),
2651 "a 404 registration failure should hint at a version mismatch; got: {msg}"
2652 );
2653 }
2654
2655 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2659 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2660 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2661 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2662
2663 fn resolve_remote_ok() -> String {
2664 http_response(
2665 "200 OK",
2666 &format!(
2667 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2668 ),
2669 )
2670 }
2671
2672 fn remote_detail(repos: &[(&str, &str)]) -> String {
2673 let repos: Vec<String> = repos
2674 .iter()
2675 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2676 .collect();
2677 http_response(
2678 "200 OK",
2679 &format!(
2680 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2681 repos.join(",")
2682 ),
2683 )
2684 }
2685
2686 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2689 let (base, rx) = crate::test_helpers::spawn_seq(responses);
2690 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2691 _guard.set("XDG_CONFIG_HOME", root);
2692 _guard.set("TRACEVAULT_API_KEY", "tok");
2693 _guard.remove("TRACEVAULT_SERVER_URL");
2694
2695 init_in_directory(
2696 root,
2697 Some(&base),
2698 None,
2699 true,
2700 Some(crate::config::UserContext::Toggle(false)),
2701 crate::agent::Agent::Codex,
2702 )
2703 .await
2704 .expect("init succeeds");
2705
2706 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2707 (cfg.repo_id, rx.try_iter().collect())
2708 }
2709
2710 fn registered(requests: &[String]) -> bool {
2711 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2712 }
2713
2714 #[tokio::test]
2717 async fn init_binds_the_existing_repo_of_a_known_remote() {
2718 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2719 let tmp = tempfile::tempdir().unwrap();
2720 crate::test_helpers::init_git_repo(tmp.path());
2721 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2722
2723 let (repo_id, requests) = init_against(
2724 tmp.path(),
2725 vec![
2726 resolve_remote_ok(),
2727 remote_detail(&[(CANONICAL, "tracevault")]),
2728 ],
2729 )
2730 .await;
2731
2732 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2733 assert!(!registered(&requests), "requests: {requests:?}");
2734 }
2735
2736 #[tokio::test]
2739 async fn init_binds_the_record_named_like_the_checkout() {
2740 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2741 let tmp = tempfile::tempdir().unwrap();
2742 crate::test_helpers::init_git_repo(tmp.path());
2743 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2744 let dir_name = crate::resolution::git_repo_name(tmp.path());
2745
2746 let (repo_id, requests) = init_against(
2747 tmp.path(),
2748 vec![
2749 resolve_remote_ok(),
2750 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2751 ],
2752 )
2753 .await;
2754
2755 assert_eq!(repo_id.as_deref(), Some(STRAY));
2756 assert!(!registered(&requests));
2757 }
2758
2759 #[tokio::test]
2761 async fn init_rerun_keeps_the_previously_bound_repo() {
2762 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2763 let tmp = tempfile::tempdir().unwrap();
2764 crate::test_helpers::init_git_repo(tmp.path());
2765 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2766 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2767 fs::write(
2768 tmp.path().join(".tracevault/config.toml"),
2769 format!("repo_id = \"{STRAY}\"\n"),
2770 )
2771 .unwrap();
2772
2773 let (repo_id, requests) = init_against(
2774 tmp.path(),
2775 vec![
2776 resolve_remote_ok(),
2777 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2778 ],
2779 )
2780 .await;
2781
2782 assert_eq!(repo_id.as_deref(), Some(STRAY));
2783 assert!(!registered(&requests));
2784 }
2785
2786 #[tokio::test]
2789 async fn init_binding_keeps_the_rest_of_the_config() {
2790 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2791 let tmp = tempfile::tempdir().unwrap();
2792 crate::test_helpers::init_git_repo(tmp.path());
2793 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2794 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2795 fs::write(
2796 tmp.path().join(".tracevault/config.toml"),
2797 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
2798 )
2799 .unwrap();
2800
2801 let (repo_id, _) = init_against(
2802 tmp.path(),
2803 vec![
2804 resolve_remote_ok(),
2805 remote_detail(&[(CANONICAL, "tracevault")]),
2806 ],
2807 )
2808 .await;
2809
2810 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2811 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
2812 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
2813 assert_eq!(cfg.default_project.as_deref(), Some("payments"));
2814 }
2815
2816 #[tokio::test]
2819 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
2820 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2821 let tmp = tempfile::tempdir().unwrap();
2822 crate::test_helpers::init_git_repo(tmp.path());
2823 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2824 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2825 fs::write(
2826 tmp.path().join(".tracevault/config.toml"),
2827 format!("repo_id = \"{STRAY}\"\n"),
2828 )
2829 .unwrap();
2830
2831 let (repo_id, requests) = init_against(
2832 tmp.path(),
2833 vec![http_response("500 Internal Server Error", "{}")],
2834 )
2835 .await;
2836
2837 assert_eq!(repo_id.as_deref(), Some(STRAY));
2838 assert!(!registered(&requests));
2839 }
2840
2841 #[tokio::test]
2843 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2844 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2845 let tmp = tempfile::tempdir().unwrap();
2846 crate::test_helpers::init_git_repo(tmp.path());
2847 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2848
2849 let (repo_id, requests) = init_against(
2850 tmp.path(),
2851 vec![
2852 resolve_remote_ok(),
2853 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2854 ],
2855 )
2856 .await;
2857
2858 assert_eq!(repo_id, None);
2859 assert!(!registered(&requests));
2860 }
2861
2862 #[tokio::test]
2865 async fn init_registers_for_a_codebase_without_live_repos() {
2866 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2867 let tmp = tempfile::tempdir().unwrap();
2868 crate::test_helpers::init_git_repo(tmp.path());
2869 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2870
2871 let (repo_id, requests) = init_against(
2872 tmp.path(),
2873 vec![
2874 resolve_remote_ok(),
2875 remote_detail(&[]),
2876 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2877 ],
2878 )
2879 .await;
2880
2881 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2882 assert!(registered(&requests));
2883 }
2884
2885 #[tokio::test]
2887 async fn init_does_not_register_when_the_remote_check_fails() {
2888 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2889 let tmp = tempfile::tempdir().unwrap();
2890 crate::test_helpers::init_git_repo(tmp.path());
2891 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2892
2893 let (repo_id, requests) = init_against(
2894 tmp.path(),
2895 vec![http_response("500 Internal Server Error", "{}")],
2896 )
2897 .await;
2898
2899 assert_eq!(repo_id, None);
2900 assert!(!registered(&requests));
2901 }
2902}