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 "SubagentStop": [{
667 "matcher": "",
668 "hooks": [{
669 "type": "command",
670 "command": "tracevault stream --event subagent-stop",
671 "timeout": 10,
672 "statusMessage": "TraceVault: streaming subagent transcript"
673 }]
674 }],
675 "SessionStart": [{
676 "matcher": "",
677 "hooks": [{
678 "type": "command",
679 "command": "tracevault session-start",
680 "timeout": 10,
681 "statusMessage": "TraceVault: session start"
682 }]
683 }],
684 "UserPromptSubmit": [{
685 "matcher": "",
686 "hooks": [{
687 "type": "command",
688 "command": "tracevault user-prompt",
689 "timeout": 10,
690 "statusMessage": "TraceVault: policy reinforcement"
691 }]
692 }]
693 })
694}
695
696pub fn codex_hook_trust_notice() -> &'static str {
706 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
707 silently and no session is captured. Run `codex` once interactively in a repo and \
708 approve the hook-trust prompt; unattended runs (CI) can pass \
709 `--dangerously-bypass-hook-trust` instead."
710}
711
712pub fn codex_hooks() -> serde_json::Value {
722 serde_json::json!({
723 "SessionStart": [{
724 "matcher": "",
725 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
726 }],
727 "UserPromptSubmit": [{
728 "matcher": "",
729 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
730 }],
731 "PostToolUse": [{
732 "matcher": "",
733 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
734 }],
735 "Stop": [{
736 "matcher": "",
737 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
738 }]
739 })
740}
741
742const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
746const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
747const GSD_EXT_MANIFEST_JSON: &str =
748 include_str!("../../assets/gsd-extension/extension-manifest.json");
749
750fn gsd_extension_source_dir() -> io::Result<PathBuf> {
754 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
755 let config_dir = config_dir
756 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
757 Ok(config_dir.join("tracevault").join("gsd-extension"))
758}
759
760pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
784 let home =
785 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
786 let gsd_home = home.join(".gsd");
787
788 let source_dir = gsd_extension_source_dir()?;
789 fs::create_dir_all(&source_dir)?;
790 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
791 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
792 fs::write(
793 source_dir.join("extension-manifest.json"),
794 GSD_EXT_MANIFEST_JSON,
795 )?;
796
797 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
801 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
802 }
803
804 let local_flag = project_root.is_some();
808 let mut cmd = std::process::Command::new("gsd");
809 cmd.arg("install").arg(&source_dir);
810 if let Some(root) = project_root {
811 cmd.arg("-l");
812 cmd.current_dir(root);
813 }
814
815 let retry_hint = format!(
816 "gsd install {}{}",
817 source_dir.display(),
818 if local_flag { " -l" } else { "" }
819 );
820
821 match cmd.output() {
822 Ok(output) if output.status.success() => {
823 println!(
824 "TraceVault: installed and registered the GSD extension ({}).",
825 source_dir.display()
826 );
827 }
828 Ok(output) => {
829 eprintln!(
830 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
831 source_dir.display(),
832 String::from_utf8_lossy(&output.stderr),
833 );
834 }
835 Err(e) => {
836 eprintln!(
837 "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.",
838 source_dir.display(),
839 );
840 }
841 }
842
843 Ok(())
844}
845
846const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
849
850pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
866 let plugins_dir = match project_root {
867 Some(root) => root.join(".opencode").join("plugins"),
868 None => {
869 let config_dir =
870 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
871 config_dir
872 .ok_or_else(|| {
873 io::Error::new(
874 io::ErrorKind::NotFound,
875 "could not determine the config directory for the OpenCode plugin install",
876 )
877 })?
878 .join("opencode")
879 .join("plugins")
880 }
881 };
882
883 write_opencode_plugin_files(&plugins_dir)
884}
885
886fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
887 fs::create_dir_all(plugins_dir)?;
888 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
889 Ok(())
890}
891
892pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
904 let ext_root = gsd_home.join("extensions");
905 let reg_path = ext_root.join("registry.json");
906
907 let reg: Option<serde_json::Value> = if reg_path.exists() {
912 let content = fs::read_to_string(®_path)?;
913 let parsed: serde_json::Value = match serde_json::from_str(&content) {
914 Ok(v) => v,
915 Err(_) => return Ok(()), };
917 let corrupt = match parsed.as_object() {
918 None => true,
919 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
920 };
921 if corrupt {
922 return Ok(()); }
924 Some(parsed)
925 } else {
926 None
927 };
928
929 let stale = ext_root.join("tracevault-tracker");
931 if stale.exists() {
932 fs::remove_dir_all(&stale)?;
933 }
934
935 if let Some(mut reg) = reg {
937 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
938 let removed_tracker = entries.remove("tracevault-tracker").is_some();
939 let removed_inert = entries.remove("tracevault").is_some();
940 if removed_tracker || removed_inert {
941 let tmp = reg_path.with_extension("json.tmp");
943 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
944 fs::rename(&tmp, ®_path)?;
945 }
946 }
947 }
948 Ok(())
949}
950
951fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
961 update_json_file(hooks_path, "its hooks", |root| {
962 merge_hooks(root, ours, hooks_path)
963 })
964}
965
966pub(crate) fn update_json_file(
974 path: &Path,
975 what: &str,
976 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
977) -> io::Result<()> {
978 if path
983 .components()
984 .any(|c| c == std::path::Component::ParentDir)
985 {
986 return Err(io::Error::new(
987 io::ErrorKind::InvalidInput,
988 format!("refusing to use path with '..': {}", path.display()),
989 ));
990 }
991 let target = match fs::symlink_metadata(path) {
995 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
996 _ => path.to_path_buf(),
997 };
998 for _ in 0..3 {
1004 let existing = read_existing(&target)?;
1005 let mut root: serde_json::Value = match &existing {
1006 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1007 io::Error::new(
1008 io::ErrorKind::InvalidData,
1009 format!("Failed to parse {}: {e}", path.display()),
1010 )
1011 })?,
1012 None => serde_json::json!({}),
1013 };
1014
1015 let before = existing.is_some().then(|| root.to_string());
1016 mutate(&mut root)?;
1017 if before.as_deref() == Some(root.to_string().as_str())
1018 || (existing.is_none() && root == serde_json::json!({}))
1019 {
1020 return Ok(());
1021 }
1022
1023 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1024 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1025 })?;
1026 let tmp = unique_temp_sibling(&target);
1027 let published = write_owner_only(&tmp, formatted.as_bytes())
1028 .and_then(|()| {
1029 match &existing {
1032 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1033 None => Ok(()),
1034 }
1035 })
1036 .and_then(|()| {
1037 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1038 == existing.as_ref().map(|(_, c)| c.clone());
1039 if unchanged {
1040 fs::rename(&tmp, &target).map(|()| true)
1041 } else {
1042 Ok(false)
1043 }
1044 });
1045 match published {
1046 Ok(true) => return Ok(()),
1047 Ok(false) => {
1048 let _ = fs::remove_file(&tmp);
1049 }
1050 Err(e) => {
1051 let _ = fs::remove_file(&tmp);
1052 return Err(e);
1053 }
1054 }
1055 }
1056 Err(io::Error::other(format!(
1057 "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1058 path.display()
1059 )))
1060}
1061
1062fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1064 let permissions = match fs::metadata(path) {
1065 Ok(meta) => meta.permissions(),
1066 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1067 Err(e) => return Err(e),
1068 };
1069 Ok(Some((permissions, fs::read_to_string(path)?)))
1070}
1071
1072fn unique_temp_sibling(target: &Path) -> PathBuf {
1076 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1077 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1078 let nanos = std::time::SystemTime::now()
1079 .duration_since(std::time::UNIX_EPOCH)
1080 .map(|d| d.subsec_nanos())
1081 .unwrap_or_default();
1082 let mut name = target.file_name().unwrap_or_default().to_os_string();
1083 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1084 target.with_file_name(name)
1085}
1086
1087fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1091 let mut options = fs::OpenOptions::new();
1092 options.write(true).create_new(true);
1093 #[cfg(unix)]
1094 {
1095 use std::os::unix::fs::OpenOptionsExt;
1096 options.mode(0o600);
1097 }
1098 options.open(path)?.write_all(contents)
1099}
1100
1101pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1105 let codex_dir = project_root.join(".codex");
1106 fs::create_dir_all(&codex_dir)?;
1107 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1108}
1109
1110pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1117 fs::create_dir_all(codex_dir)?;
1118 let base = codex_dir.canonicalize()?;
1120 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1121 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1122}
1123
1124const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1128
1129const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1130<!-- tracevault:workspace-mode -->
1131## TraceVault (workspace mode)
1132A session started in a registered repo's checkout is bound to that repo automatically. To work
1133on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1134policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1135one-off. Repos must already be registered with TraceVault.
1136";
1137
1138fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1144 if md_path
1146 .components()
1147 .any(|c| c == std::path::Component::ParentDir)
1148 {
1149 return Err(io::Error::new(
1150 io::ErrorKind::InvalidInput,
1151 format!("refusing to use path with '..': {}", md_path.display()),
1152 ));
1153 }
1154 let existing = if md_path.exists() {
1155 fs::read_to_string(md_path)?
1156 } else {
1157 String::new()
1158 };
1159 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1160 return Ok(());
1161 }
1162 let mut content = existing;
1163 if !content.is_empty() && !content.ends_with('\n') {
1164 content.push('\n');
1165 }
1166 if !content.is_empty() {
1167 content.push('\n');
1168 }
1169 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1170 fs::write(md_path, content)
1171}
1172
1173pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1177 let joined = base.join(name);
1178 if joined.parent() != Some(base) {
1179 return Err(io::Error::new(
1180 io::ErrorKind::InvalidInput,
1181 format!(
1182 "refusing to access path outside {}: {}",
1183 base.display(),
1184 joined.display()
1185 ),
1186 ));
1187 }
1188 Ok(joined)
1189}
1190
1191const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1197
1198fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1199 hook.get("command")
1200 .and_then(|c| c.as_str())
1201 .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1202}
1203
1204fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1211 let mut slot = None;
1212 let mut kept = Vec::with_capacity(entries.len());
1213 for mut entry in entries.drain(..) {
1214 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1215 let before = inner.len();
1216 inner.retain(|hook| !is_tracevault_hook(hook));
1217 if inner.is_empty() && before > 0 {
1218 slot.get_or_insert(kept.len());
1219 continue;
1220 }
1221 }
1222 kept.push(entry);
1223 }
1224 *entries = kept;
1225 slot
1226}
1227
1228fn merge_hooks(
1242 settings: &mut serde_json::Value,
1243 ours: &serde_json::Value,
1244 path: &Path,
1245) -> io::Result<()> {
1246 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1247 io::Error::new(
1248 io::ErrorKind::InvalidData,
1249 format!("{} is not a JSON object", path.display()),
1250 )
1251 })?;
1252
1253 let hooks_value = settings_obj
1254 .entry("hooks")
1255 .or_insert_with(|| serde_json::json!({}));
1256 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1257 io::Error::new(
1258 io::ErrorKind::InvalidData,
1259 format!("{} \"hooks\" key is not a JSON object", path.display()),
1260 )
1261 })?;
1262
1263 let empty = serde_json::Map::new();
1264 let ours_obj = ours.as_object().unwrap_or(&empty);
1265
1266 for event in ours_obj.keys() {
1268 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1269 return Err(io::Error::new(
1270 io::ErrorKind::InvalidData,
1271 format!(
1272 "{} \"hooks\".\"{event}\" is not a JSON array",
1273 path.display()
1274 ),
1275 ));
1276 }
1277 }
1278
1279 let mut emptied = Vec::new();
1280 for (event, value) in hooks_obj.iter_mut() {
1281 let Some(existing) = value.as_array_mut() else {
1282 continue;
1283 };
1284 let had_entries = !existing.is_empty();
1285 let slot = strip_tracevault_hooks(existing);
1286 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1287 match our_entries {
1288 Some(our_entries) => {
1289 let at = slot.unwrap_or(existing.len());
1290 existing.splice(at..at, our_entries.iter().cloned());
1291 }
1292 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1293 None => {}
1294 }
1295 }
1296 hooks_obj.retain(|event, _| !emptied.contains(event));
1298
1299 for (event, our_array) in ours_obj {
1300 if !hooks_obj.contains_key(event) {
1301 hooks_obj.insert(event.clone(), our_array.clone());
1302 }
1303 }
1304
1305 Ok(())
1306}
1307
1308pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1314 fs::create_dir_all(claude_dir)?;
1315
1316 let base = claude_dir.canonicalize()?;
1319
1320 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1322
1323 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1325}
1326
1327pub fn write_global_user_config_in(
1337 config_root: &Path,
1338 requested: Option<UserContext>,
1339) -> io::Result<Option<PathBuf>> {
1340 fs::create_dir_all(config_root)?;
1341 let mut config = crate::config::try_load_user_config_in(config_root)
1343 .ok()
1344 .flatten()
1345 .unwrap_or_default();
1346 let user_context = requested
1348 .or_else(|| config.user_context.clone())
1349 .unwrap_or(UserContext::Toggle(true));
1350 let active = user_context
1351 .resolve()
1352 .map(|_| user_context.path_in(config_root));
1353 config.user_context = Some(user_context);
1354 fs::write(user_config_path_in(config_root), config.to_toml())?;
1355 if let Some(ref ctx_path) = active {
1356 if !ctx_path.exists() {
1357 Context::default().save_to(ctx_path)?;
1358 }
1359 }
1360 Ok(active)
1361}
1362
1363#[cfg(test)]
1364mod tests {
1365 use super::*;
1366 use std::io::{BufRead, BufReader, Write};
1367 use std::net::TcpListener;
1368 use std::thread;
1369
1370 #[test]
1376 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1377 let notice = codex_hook_trust_notice();
1378 assert!(
1379 notice.contains("hook trust"),
1380 "notice must name what is missing: {notice}"
1381 );
1382 assert!(
1383 notice.contains("codex") && notice.contains("approve"),
1384 "notice must tell the user to run codex and approve the prompt: {notice}"
1385 );
1386 assert!(
1387 notice.contains("--dangerously-bypass-hook-trust"),
1388 "notice must name the flag for unattended/CI runs: {notice}"
1389 );
1390 assert!(
1391 notice.contains("silently"),
1392 "notice must say the failure is silent, which is why it needs saying: {notice}"
1393 );
1394 }
1395
1396 fn spawn_once(response: String) -> String {
1399 let response: &'static str = Box::leak(response.into_boxed_str());
1400 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1401 let addr = listener.local_addr().unwrap();
1402 thread::spawn(move || {
1403 if let Ok((stream, _)) = listener.accept() {
1404 let mut reader = BufReader::new(stream);
1405 let mut request_line = String::new();
1406 let _ = reader.read_line(&mut request_line);
1407 let mut stream = reader.into_inner();
1408 let _ = stream.write_all(response.as_bytes());
1409 let _ = stream.flush();
1410 }
1411 });
1412 format!("http://{addr}")
1413 }
1414
1415 fn http_response(status: &str, body: &str) -> String {
1418 format!(
1419 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1420 status,
1421 body.len(),
1422 body
1423 )
1424 }
1425
1426 fn add_origin_remote(dir: &Path, url: &str) {
1427 let ok = std::process::Command::new("git")
1428 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1429 .status()
1430 .expect("git remote add failed")
1431 .success();
1432 assert!(ok, "git remote add must succeed");
1433 }
1434
1435 #[test]
1436 fn linked_worktree_primary_detects_linked_and_primary() {
1437 let tmp = tempfile::tempdir().unwrap();
1438 let repo = tmp.path().join("repo");
1439 let wt = tmp.path().join("linked-wt");
1440 std::fs::create_dir_all(&repo).unwrap();
1441 crate::test_helpers::init_git_repo(&repo);
1442 crate::test_helpers::add_worktree(&repo, &wt);
1443
1444 assert!(
1446 linked_worktree_primary(&repo).is_none(),
1447 "primary checkout must not be flagged as a linked worktree"
1448 );
1449 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1451 assert_eq!(
1452 primary.canonicalize().unwrap(),
1453 repo.canonicalize().unwrap(),
1454 "must resolve to the primary repo root"
1455 );
1456 }
1457
1458 #[test]
1459 fn linked_worktree_primary_none_for_non_git() {
1460 let tmp = tempfile::tempdir().unwrap();
1461 assert!(
1462 linked_worktree_primary(tmp.path()).is_none(),
1463 "a non-git directory is not a linked worktree"
1464 );
1465 }
1466
1467 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1469 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1470 }
1471
1472 #[test]
1473 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1474 let mut settings = serde_json::json!({});
1475 let ours = tracevault_hooks();
1476 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1477
1478 let hooks = settings.get("hooks").unwrap();
1479 for event in [
1480 "PreToolUse",
1481 "PostToolUse",
1482 "Notification",
1483 "Stop",
1484 "SubagentStop",
1485 "SessionStart",
1486 "UserPromptSubmit",
1487 ] {
1488 assert!(hooks.get(event).is_some(), "missing event {event}");
1489 }
1490 }
1491
1492 #[test]
1493 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1494 let mut settings = serde_json::json!({
1495 "model": "opus",
1496 "hooks": {
1497 "PreToolUse": [{
1498 "matcher": "",
1499 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1500 }]
1501 }
1502 });
1503 let ours = tracevault_hooks();
1504 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1505
1506 assert_eq!(settings.get("model").unwrap(), "opus");
1508
1509 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1510 assert_eq!(pre_tool_use.len(), 2);
1512 let commands: Vec<&str> = pre_tool_use
1513 .iter()
1514 .map(|e| entry_command(e).unwrap())
1515 .collect();
1516 assert!(commands.contains(&"my-own-hook"));
1517 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1518
1519 assert!(settings["hooks"]["SessionStart"].is_array());
1521 }
1522
1523 #[test]
1524 fn merge_hooks_is_idempotent() {
1525 let mut settings = serde_json::json!({});
1526 let ours = tracevault_hooks();
1527 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1528 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1529
1530 for event in [
1531 "PreToolUse",
1532 "PostToolUse",
1533 "Notification",
1534 "Stop",
1535 "SubagentStop",
1536 "SessionStart",
1537 "UserPromptSubmit",
1538 ] {
1539 let arr = settings["hooks"][event].as_array().unwrap();
1540 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1541 }
1542 }
1543
1544 #[test]
1545 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1546 let mut settings = serde_json::json!({
1550 "hooks": {
1551 "PreToolUse": [{
1552 "matcher": "Write|Edit|Bash",
1553 "hooks": [
1554 { "type": "command", "command": "other", "timeout": 3 },
1555 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1556 ]
1557 }]
1558 }
1559 });
1560 merge_hooks(
1561 &mut settings,
1562 &tracevault_hooks(),
1563 Path::new("settings.json"),
1564 )
1565 .unwrap();
1566
1567 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1568 assert_eq!(
1569 pre_tool_use[0],
1570 serde_json::json!({
1571 "matcher": "Write|Edit|Bash",
1572 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1573 })
1574 );
1575 assert_eq!(
1576 &pre_tool_use[1..],
1577 tracevault_hooks()["PreToolUse"].as_array().unwrap()
1578 );
1579 }
1580
1581 fn stale_tracevault_hooks() -> serde_json::Value {
1584 let entry = |matcher: &str, event: &str| {
1585 serde_json::json!([{
1586 "matcher": matcher,
1587 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1588 }])
1589 };
1590 serde_json::json!({
1591 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1592 "PostToolUse": entry("", "post-tool-use"),
1593 "Notification": entry("", "notification"),
1594 "Stop": entry("", "stop"),
1595 })
1596 }
1597
1598 #[test]
1599 fn merge_hooks_upgrades_stale_tracevault_entries() {
1600 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1601 merge_hooks(
1602 &mut settings,
1603 &tracevault_hooks(),
1604 Path::new("settings.json"),
1605 )
1606 .unwrap();
1607 assert_eq!(settings["hooks"], tracevault_hooks());
1608 }
1609
1610 #[test]
1611 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1612 let mut settings = serde_json::json!({
1615 "hooks": {
1616 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1617 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1618 "Custom": "left alone"
1619 }
1620 });
1621 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1622
1623 let hooks = settings["hooks"].as_object().unwrap();
1624 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
1625 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
1626 assert_eq!(hooks["Custom"], "left alone");
1627 for (event, entries) in codex_hooks().as_object().unwrap() {
1628 assert_eq!(&hooks[event], entries, "{event}");
1629 }
1630 }
1631
1632 #[test]
1633 fn merge_hooks_rerun_keeps_our_entry_in_place() {
1634 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
1637 settings["hooks"]["Stop"]
1638 .as_array_mut()
1639 .unwrap()
1640 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
1641 let before = settings.clone();
1642 merge_hooks(
1643 &mut settings,
1644 &tracevault_hooks(),
1645 Path::new("settings.json"),
1646 )
1647 .unwrap();
1648 assert_eq!(settings.to_string(), before.to_string());
1649 }
1650
1651 #[test]
1652 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
1653 let foreign = serde_json::json!({
1654 "matcher": "",
1655 "hooks": [
1656 { "type": "command", "command": "tracevault-wrapper stream" },
1657 { "type": "command", "command": "echo tracevault stream" },
1658 { "type": "command", "command": " tracevault check" }
1659 ]
1660 });
1661 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
1662 merge_hooks(
1663 &mut settings,
1664 &tracevault_hooks(),
1665 Path::new("settings.json"),
1666 )
1667 .unwrap();
1668 assert_eq!(settings["hooks"]["Stop"][0], foreign);
1669 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
1670 }
1671
1672 #[test]
1673 fn merge_hooks_errors_on_non_object_top_level() {
1674 let mut settings = serde_json::json!([1, 2, 3]);
1675 let ours = tracevault_hooks();
1676 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1677 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1678 assert!(err.to_string().contains("settings.json"));
1679 }
1680
1681 #[test]
1682 fn merge_hooks_errors_on_non_object_top_level_number() {
1683 let mut settings = serde_json::json!(42);
1684 let ours = tracevault_hooks();
1685 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1686 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1687 }
1688
1689 #[test]
1690 fn merge_hooks_errors_on_non_object_hooks() {
1691 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1692 let ours = tracevault_hooks();
1693 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1694 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1695 assert!(err.to_string().contains("hooks"));
1696 }
1697
1698 #[test]
1699 fn merge_hooks_errors_on_non_array_event_value() {
1700 let mut settings = serde_json::json!({
1701 "hooks": {
1702 "PreToolUse": "not-an-array"
1703 }
1704 });
1705 let ours = tracevault_hooks();
1706 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1707 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1708 assert!(err.to_string().contains("PreToolUse"));
1709 }
1710
1711 #[test]
1712 fn install_global_hooks_writes_settings_and_claude_md() {
1713 let tmp = tempfile::tempdir().unwrap();
1714 let claude_dir = tmp.path().join(".claude");
1715
1716 install_global_hooks(&claude_dir).unwrap();
1717
1718 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1719 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1720 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1721 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1722 }
1723
1724 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1725 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1726 }
1727
1728 #[test]
1729 fn install_global_hooks_is_idempotent() {
1730 let tmp = tempfile::tempdir().unwrap();
1731 let claude_dir = tmp.path().join(".claude");
1732
1733 install_global_hooks(&claude_dir).unwrap();
1734 install_global_hooks(&claude_dir).unwrap();
1735
1736 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1737 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1738 for event in [
1739 "PreToolUse",
1740 "PostToolUse",
1741 "Notification",
1742 "Stop",
1743 "SubagentStop",
1744 "SessionStart",
1745 "UserPromptSubmit",
1746 ] {
1747 let arr = settings["hooks"][event].as_array().unwrap();
1748 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1749 }
1750
1751 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1752 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1753 assert_eq!(
1754 marker_count, 1,
1755 "CLAUDE.md marker should appear exactly once"
1756 );
1757 }
1758
1759 #[test]
1760 fn install_global_hooks_preserves_existing_claude_md_content() {
1761 let tmp = tempfile::tempdir().unwrap();
1762 let claude_dir = tmp.path().join(".claude");
1763 fs::create_dir_all(&claude_dir).unwrap();
1764 fs::write(
1765 claude_dir.join("CLAUDE.md"),
1766 "# My existing notes\nSome content.\n",
1767 )
1768 .unwrap();
1769
1770 install_global_hooks(&claude_dir).unwrap();
1771
1772 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1773 assert!(claude_md.contains("# My existing notes"));
1774 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1775 }
1776
1777 #[test]
1778 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1779 let tmp = tempfile::tempdir().unwrap();
1780 let claude_dir = tmp.path().join(".claude");
1781
1782 install_global_hooks(&claude_dir).unwrap();
1783
1784 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1785 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1786 assert!(settings["hooks"].get("SessionStart").is_some());
1787
1788 let leftover = fs::read_dir(&claude_dir)
1789 .unwrap()
1790 .filter_map(|e| e.ok())
1791 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1792 assert!(
1793 !leftover,
1794 "no settings.json.tmp should remain after install"
1795 );
1796 }
1797
1798 #[test]
1799 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1800 let tmp = tempfile::tempdir().unwrap();
1801 let claude_dir = tmp.path().join(".claude");
1802 fs::create_dir_all(&claude_dir).unwrap();
1803 let settings_path = claude_dir.join("settings.json");
1804 let original = "[1, 2, 3]";
1805 fs::write(&settings_path, original).unwrap();
1806
1807 let err = install_global_hooks(&claude_dir).unwrap_err();
1808 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1809
1810 let after = fs::read_to_string(&settings_path).unwrap();
1813 assert_eq!(after, original);
1814 let leftover = fs::read_dir(&claude_dir)
1815 .unwrap()
1816 .filter_map(|e| e.ok())
1817 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1818 assert!(!leftover, "no tmp file should be left behind on error");
1819 }
1820
1821 #[test]
1822 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1823 let tmp = tempfile::tempdir().unwrap();
1824 let claude_dir = tmp.path().join(".claude");
1825 fs::create_dir_all(&claude_dir).unwrap();
1826 let settings_path = claude_dir.join("settings.json");
1827 let original = r#"{"hooks": "oops"}"#;
1828 fs::write(&settings_path, original).unwrap();
1829
1830 let err = install_global_hooks(&claude_dir).unwrap_err();
1831 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1832
1833 let after = fs::read_to_string(&settings_path).unwrap();
1834 assert_eq!(after, original);
1835 }
1836
1837 #[test]
1838 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1839 let tmp = tempfile::tempdir().unwrap();
1840 let claude_dir = tmp.path().join(".claude");
1841 fs::create_dir_all(&claude_dir).unwrap();
1842 let settings_path = claude_dir.join("settings.json");
1843 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1844 fs::write(&settings_path, original).unwrap();
1845
1846 let err = install_global_hooks(&claude_dir).unwrap_err();
1847 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1848
1849 let after = fs::read_to_string(&settings_path).unwrap();
1850 assert_eq!(after, original);
1851 }
1852
1853 #[test]
1854 fn safe_join_allows_direct_child_file() {
1855 let tmp = tempfile::tempdir().unwrap();
1856 let base = tmp.path();
1857 let result = safe_join(base, "settings.json").unwrap();
1858 assert_eq!(result.parent(), Some(base));
1859 assert_eq!(result.file_name().unwrap(), "settings.json");
1860 }
1861
1862 #[test]
1863 fn safe_join_rejects_path_traversal() {
1864 let tmp = tempfile::tempdir().unwrap();
1865 let base = tmp.path();
1866 let result = safe_join(base, "../evil");
1867 assert!(result.is_err());
1868 let err = result.unwrap_err();
1869 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1870 assert!(err.to_string().contains("refusing to access path outside"));
1871 }
1872
1873 #[test]
1874 fn safe_join_rejects_absolute_path() {
1875 let tmp = tempfile::tempdir().unwrap();
1876 let base = tmp.path();
1877 let result = safe_join(base, "/etc/passwd");
1878 assert!(result.is_err());
1881 }
1882
1883 #[test]
1884 fn write_global_user_config_enables_and_creates_context() {
1885 let root = tempfile::tempdir().unwrap();
1886 let active = write_global_user_config_in(root.path(), None).unwrap();
1887 let cfg = crate::config::try_load_user_config_in(root.path())
1888 .unwrap()
1889 .unwrap();
1890 assert_eq!(
1893 cfg.user_context.unwrap().resolve_in(root.path()),
1894 Some(crate::config::default_user_context_path_in(root.path()))
1895 );
1896 let ctx = crate::config::default_user_context_path_in(root.path());
1897 assert_eq!(active, Some(ctx.clone()));
1898 assert!(ctx.exists());
1899 }
1900
1901 #[test]
1902 fn write_global_user_config_can_disable() {
1903 let root = tempfile::tempdir().unwrap();
1904 let active = write_global_user_config_in(
1905 root.path(),
1906 Some(crate::config::UserContext::Toggle(false)),
1907 )
1908 .unwrap();
1909 let cfg = crate::config::try_load_user_config_in(root.path())
1910 .unwrap()
1911 .unwrap();
1912 assert!(matches!(
1913 cfg.user_context,
1914 Some(crate::config::UserContext::Toggle(false))
1915 ));
1916 assert_eq!(active, None, "disabled → no active context path");
1917 assert!(
1919 !crate::config::default_user_context_path_in(root.path()).exists(),
1920 "disabled user context must not create a context.json"
1921 );
1922 }
1923
1924 #[test]
1925 fn write_global_user_config_custom_path_seeds_that_file_only() {
1926 let root = tempfile::tempdir().unwrap();
1927 let custom = root.path().join("custom-ctx.json");
1928 let active = write_global_user_config_in(
1929 root.path(),
1930 Some(crate::config::UserContext::Path(
1931 custom.to_string_lossy().into_owned(),
1932 )),
1933 )
1934 .unwrap();
1935 assert_eq!(active, Some(custom.clone()));
1936 assert!(custom.exists(), "the configured custom path must be seeded");
1937 assert!(
1938 !crate::config::default_user_context_path_in(root.path()).exists(),
1939 "the default context.json must NOT be created when a custom path is configured"
1940 );
1941 }
1942
1943 #[test]
1944 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1945 let root = tempfile::tempdir().unwrap();
1946 let custom = root.path().join("custom-ctx.json");
1947 write_global_user_config_in(
1949 root.path(),
1950 Some(crate::config::UserContext::Path(
1951 custom.to_string_lossy().into_owned(),
1952 )),
1953 )
1954 .unwrap();
1955 let active = write_global_user_config_in(root.path(), None).unwrap();
1957 assert_eq!(
1958 active,
1959 Some(custom.clone()),
1960 "re-run without flags must preserve the custom path"
1961 );
1962 let cfg = crate::config::try_load_user_config_in(root.path())
1963 .unwrap()
1964 .unwrap();
1965 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1966 }
1967
1968 #[test]
1969 fn install_global_codex_hooks_writes_and_is_idempotent() {
1970 let tmp = tempfile::tempdir().unwrap();
1971 let codex_dir = tmp.path().join(".codex");
1972
1973 install_global_codex_hooks(&codex_dir).unwrap();
1974 install_global_codex_hooks(&codex_dir).unwrap();
1975
1976 let v: serde_json::Value =
1977 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1978 .unwrap();
1979 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1980 let arr = v["hooks"][event].as_array().unwrap();
1981 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1982 }
1983 assert!(v["hooks"].get("PreToolUse").is_none());
1984 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1986 assert_eq!(
1987 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1988 1,
1989 "AGENTS.md workspace-mode block must appear exactly once"
1990 );
1991 let leftover = fs::read_dir(&codex_dir)
1993 .unwrap()
1994 .filter_map(|e| e.ok())
1995 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1996 assert!(!leftover);
1997 }
1998
1999 #[test]
2000 fn codex_hooks_has_expected_events_and_commands() {
2001 let h = codex_hooks();
2002 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2003 assert!(h.get(event).is_some(), "missing codex event {event}");
2004 }
2005 assert!(h.get("PreToolUse").is_none());
2009 assert!(h.get("Notification").is_none());
2010 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2012 assert_eq!(
2013 cmd("PostToolUse"),
2014 "tracevault stream --event post-tool-use --agent codex"
2015 );
2016 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2017 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2018 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2019 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2021 }
2022
2023 #[test]
2024 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2025 let tmp = tempfile::tempdir().unwrap();
2026 install_codex_hooks(tmp.path()).unwrap();
2027 install_codex_hooks(tmp.path()).unwrap();
2028
2029 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2030 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2031 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2032 let arr = v["hooks"][event].as_array().unwrap();
2033 assert_eq!(
2034 arr.len(),
2035 1,
2036 "event {event} must not be duplicated on re-run"
2037 );
2038 }
2039 assert!(v["hooks"].get("PreToolUse").is_none());
2040 }
2041
2042 #[test]
2043 fn install_codex_hooks_preserves_existing_user_hook() {
2044 let tmp = tempfile::tempdir().unwrap();
2045 let codex_dir = tmp.path().join(".codex");
2046 fs::create_dir_all(&codex_dir).unwrap();
2047 fs::write(
2050 codex_dir.join("hooks.json"),
2051 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2052 )
2053 .unwrap();
2054
2055 install_codex_hooks(tmp.path()).unwrap();
2056
2057 let v: serde_json::Value =
2058 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2059 .unwrap();
2060 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2062 .as_array()
2063 .unwrap()
2064 .iter()
2065 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2066 .collect();
2067 assert!(
2068 post_cmds.contains(&"my-own"),
2069 "user PostToolUse hook preserved"
2070 );
2071 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2072 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2074 .as_array()
2075 .unwrap()
2076 .iter()
2077 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2078 .collect();
2079 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2080 }
2081
2082 const FOREIGN_SETTINGS: &str = r#"{
2086 "permissions": { "allow": ["Bash(ls)"] },
2087 "hooks": {
2088 "PreToolUse": [
2089 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2090 { "matcher": "Write|Edit", "hooks": [
2091 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2092 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2093 ] }
2094 ],
2095 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2096 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2097 },
2098 "model": "opus"
2099}"#;
2100
2101 fn expected_foreign_entries() -> Vec<String> {
2105 [
2106 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2107 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2108 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2109 ]
2110 .map(String::from)
2111 .to_vec()
2112 }
2113
2114 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2115 entry["hooks"]
2116 .as_array()
2117 .unwrap()
2118 .iter()
2119 .any(is_tracevault_hook)
2120 }
2121
2122 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2123 let v: serde_json::Value =
2124 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2125 assert_eq!(
2126 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2127 ["permissions", "hooks", "model"],
2128 "top-level keys kept, in their order"
2129 );
2130 assert_eq!(
2131 v["permissions"],
2132 serde_json::json!({ "allow": ["Bash(ls)"] })
2133 );
2134 let hooks = v["hooks"].as_object().unwrap();
2135 let foreign: Vec<String> = hooks
2136 .values()
2137 .flat_map(|entries| entries.as_array().unwrap())
2138 .filter(|e| !holds_tracevault_hook(e))
2139 .map(|e| e.to_string())
2140 .collect();
2141 assert_eq!(foreign, expected_foreign_entries());
2142 let ours = ours.as_object().unwrap();
2143 for (event, entries) in hooks {
2144 let mine: Vec<&serde_json::Value> = entries
2145 .as_array()
2146 .unwrap()
2147 .iter()
2148 .filter(|e| holds_tracevault_hook(e))
2149 .collect();
2150 let want: Vec<&serde_json::Value> = ours
2151 .get(event)
2152 .map(|o| o.as_array().unwrap().iter().collect())
2153 .unwrap_or_default();
2154 assert_eq!(mine, want, "TraceVault entries under {event}");
2155 }
2156 for event in ours.keys() {
2157 assert!(hooks.contains_key(event), "missing {event}");
2158 }
2159 }
2160
2161 #[test]
2162 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2163 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2164 let tmp = tempfile::tempdir().unwrap();
2165 let path = tmp.path().join(".claude").join(target.filename());
2166 fs::create_dir_all(path.parent().unwrap()).unwrap();
2167 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2168
2169 install_claude_hooks(tmp.path(), target).unwrap();
2170 assert_installed_over_foreign(&path, &tracevault_hooks());
2171
2172 let after_first = fs::read(&path).unwrap();
2174 install_claude_hooks(tmp.path(), target).unwrap();
2175 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2176 }
2177 }
2178
2179 #[test]
2180 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2181 let tmp = tempfile::tempdir().unwrap();
2182 let claude_dir = tmp.path().join(".claude");
2183 fs::create_dir_all(&claude_dir).unwrap();
2184 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2185
2186 install_global_hooks(&claude_dir).unwrap();
2187 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2188 }
2189
2190 #[test]
2191 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2192 for global in [false, true] {
2193 let tmp = tempfile::tempdir().unwrap();
2194 let codex_dir = tmp.path().join(".codex");
2195 fs::create_dir_all(&codex_dir).unwrap();
2196 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2197
2198 if global {
2199 install_global_codex_hooks(&codex_dir).unwrap();
2200 } else {
2201 install_codex_hooks(tmp.path()).unwrap();
2202 }
2203 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2204 }
2205 }
2206
2207 #[test]
2208 fn up_to_date_hook_file_is_not_rewritten() {
2209 let tmp = tempfile::tempdir().unwrap();
2211 let path = tmp.path().join(".claude/settings.json");
2212 fs::create_dir_all(path.parent().unwrap()).unwrap();
2213 let mut body = Vec::new();
2214 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
2215 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2216 serde::Serialize::serialize(
2217 &serde_json::json!({ "hooks": tracevault_hooks() }),
2218 &mut ser,
2219 )
2220 .unwrap();
2221 fs::write(&path, &body).unwrap();
2222
2223 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2224 assert_eq!(fs::read(&path).unwrap(), body);
2225 }
2226
2227 #[test]
2228 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2229 for (target, body) in [
2230 (ClaudeSettingsTarget::Shared, "{ not json"),
2231 (ClaudeSettingsTarget::Local, "[1, 2]"),
2232 (ClaudeSettingsTarget::Shared, "null"),
2233 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2234 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2235 ] {
2236 let tmp = tempfile::tempdir().unwrap();
2237 let path = tmp.path().join(".claude").join(target.filename());
2238 fs::create_dir_all(path.parent().unwrap()).unwrap();
2239 fs::write(&path, body).unwrap();
2240
2241 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2242 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2243 assert_eq!(
2244 fs::read_to_string(&path).unwrap(),
2245 body,
2246 "file must be untouched"
2247 );
2248 assert_eq!(
2249 fs::read_dir(path.parent().unwrap()).unwrap().count(),
2250 1,
2251 "no temp file left behind"
2252 );
2253 }
2254 }
2255
2256 #[test]
2257 fn concurrent_installs_never_publish_a_partial_file() {
2258 let tmp = tempfile::tempdir().unwrap();
2264 let path = tmp.path().join("settings.json");
2265 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2266 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2267 let reader = {
2268 let (path, done) = (path.clone(), done.clone());
2269 std::thread::spawn(move || {
2270 while !done.load(std::sync::atomic::Ordering::Relaxed) {
2271 let body = fs::read_to_string(&path).unwrap();
2272 serde_json::from_str::<serde_json::Value>(&body).unwrap();
2273 }
2274 })
2275 };
2276 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2277 .into_iter()
2278 .map(|ours| {
2279 let path = path.clone();
2280 std::thread::spawn(move || {
2281 for _ in 0..200 {
2282 if let Err(e) = merge_hooks_into_file(&path, &ours) {
2283 assert!(e.to_string().contains("kept changing"), "{e}");
2284 }
2285 }
2286 })
2287 })
2288 .collect();
2289 for writer in writers {
2290 writer.join().unwrap();
2291 }
2292 done.store(true, std::sync::atomic::Ordering::Relaxed);
2293 reader.join().unwrap();
2294 let v: serde_json::Value =
2295 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2296 assert_eq!(v["model"], "opus");
2297 assert_eq!(
2298 fs::read_dir(tmp.path()).unwrap().count(),
2299 1,
2300 "no temp file left"
2301 );
2302 }
2303
2304 #[cfg(unix)]
2305 #[test]
2306 fn install_claude_hooks_keeps_file_permissions() {
2307 use std::os::unix::fs::PermissionsExt;
2308 let tmp = tempfile::tempdir().unwrap();
2309 let path = tmp.path().join(".claude/settings.local.json");
2310 fs::create_dir_all(path.parent().unwrap()).unwrap();
2311 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2312 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2313
2314 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2315
2316 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2317 assert_eq!(mode, 0o600);
2318 assert_installed_over_foreign(&path, &tracevault_hooks());
2319 }
2320
2321 #[cfg(unix)]
2322 #[test]
2323 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2324 let tmp = tempfile::tempdir().unwrap();
2325 let central = tmp.path().join("central/claude-settings.json");
2326 fs::create_dir_all(central.parent().unwrap()).unwrap();
2327 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
2328 let link = tmp.path().join("repo/.claude/settings.json");
2329 fs::create_dir_all(link.parent().unwrap()).unwrap();
2330 std::os::unix::fs::symlink(¢ral, &link).unwrap();
2331
2332 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2333
2334 assert!(fs::symlink_metadata(&link)
2335 .unwrap()
2336 .file_type()
2337 .is_symlink());
2338 assert_installed_over_foreign(¢ral, &tracevault_hooks());
2339 }
2340
2341 #[cfg(unix)]
2342 #[test]
2343 fn install_claude_hooks_refuses_dangling_symlink() {
2344 let tmp = tempfile::tempdir().unwrap();
2345 let link = tmp.path().join(".claude/settings.json");
2346 fs::create_dir_all(link.parent().unwrap()).unwrap();
2347 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2348
2349 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2350 assert!(fs::symlink_metadata(&link)
2351 .unwrap()
2352 .file_type()
2353 .is_symlink());
2354 assert!(!tmp.path().join("gone.json").exists());
2355 }
2356
2357 #[test]
2358 fn validate_init_flags_rejects_claude_settings_with_codex() {
2359 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2360 }
2361
2362 #[test]
2363 fn validate_init_flags_allows_codex_without_claude_settings() {
2364 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2365 }
2366
2367 #[test]
2368 fn validate_init_flags_allows_claude_with_claude_settings() {
2369 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2370 }
2371
2372 #[test]
2373 fn merge_hooks_into_file_rejects_parent_dir() {
2374 let tmp = tempfile::tempdir().unwrap();
2375 let bad = tmp.path().join("..").join("hooks.json");
2376 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2377 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2378 }
2379
2380 #[test]
2381 fn append_workspace_md_rejects_parent_dir() {
2382 let tmp = tempfile::tempdir().unwrap();
2383 let bad = tmp.path().join("..").join("AGENTS.md");
2384 let err = append_workspace_md(&bad).unwrap_err();
2385 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2386 }
2387
2388 #[tokio::test]
2389 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2390 let tmp = tempfile::tempdir().unwrap();
2391 let root = tmp.path();
2392 crate::test_helpers::init_git_repo(root);
2393 fs::create_dir_all(root.join(".tracevault")).unwrap();
2396 fs::write(
2397 root.join(".tracevault/config.toml"),
2398 "api_key = \"tvk_test\"\n",
2399 )
2400 .unwrap();
2401
2402 let entry = init_in_directory(
2403 root,
2404 None,
2405 None,
2406 false,
2407 Some(crate::config::UserContext::Toggle(false)),
2408 crate::agent::Agent::Codex,
2409 )
2410 .await
2411 .unwrap();
2412
2413 assert!(root.join(".codex").join("hooks.json").exists());
2415 assert!(!root.join(".claude").join("settings.json").exists());
2416 assert_eq!(entry, ".codex/hooks.json");
2417
2418 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2420 assert!(gi.contains(".codex/hooks.json"));
2421 assert!(gi.contains(".tracevault/"));
2422 }
2423
2424 #[tokio::test]
2436 async fn init_in_directory_registers_repo_and_persists_repo_id() {
2437 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2438 let tmp = tempfile::tempdir().unwrap();
2439 let root = tmp.path();
2440 crate::test_helpers::init_git_repo(root);
2441 add_origin_remote(root, "git@github.com:org/repo.git");
2442
2443 let repo_id = "11111111-1111-4111-8111-111111111111";
2444 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2445 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2448 http_response("404 Not Found", NO_REMOTE),
2449 http_response("200 OK", &body),
2450 ]);
2451
2452 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2453 _guard.set("XDG_CONFIG_HOME", tmp.path());
2454 _guard.set("TRACEVAULT_API_KEY", "tok");
2455 _guard.remove("TRACEVAULT_SERVER_URL");
2456
2457 init_in_directory(
2458 root,
2459 Some(&base),
2460 None,
2461 true,
2462 Some(crate::config::UserContext::Toggle(false)),
2463 crate::agent::Agent::Codex,
2464 )
2465 .await
2466 .unwrap();
2467
2468 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2469 assert_eq!(
2470 cfg.repo_id,
2471 Some(repo_id.to_string()),
2472 "successful registration must persist repo_id to config.toml"
2473 );
2474 }
2475
2476 #[tokio::test]
2482 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2483 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2484 let tmp = tempfile::tempdir().unwrap();
2485 let root = tmp.path();
2486 crate::test_helpers::init_git_repo(root);
2487 add_origin_remote(root, "git@github.com:org/repo.git");
2488
2489 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2490 http_response("404 Not Found", NO_REMOTE),
2491 http_response("403 Forbidden", ""),
2492 ]);
2493
2494 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2495 _guard.set("XDG_CONFIG_HOME", tmp.path());
2496 _guard.set("TRACEVAULT_API_KEY", "tok");
2497 _guard.remove("TRACEVAULT_SERVER_URL");
2498
2499 let entry = init_in_directory(
2500 root,
2501 Some(&base),
2502 None,
2503 true,
2504 Some(crate::config::UserContext::Toggle(false)),
2505 crate::agent::Agent::Codex,
2506 )
2507 .await
2508 .expect("a registration failure (403) must not abort init itself");
2509 assert_eq!(entry, ".codex/hooks.json");
2510
2511 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2512 assert!(
2513 cfg.repo_id.is_none(),
2514 "a 403 registration failure must not persist a repo_id"
2515 );
2516 }
2517
2518 #[tokio::test]
2523 async fn registration_failure_message_flags_403_as_not_authorized() {
2524 let base = spawn_once(http_response("403 Forbidden", ""));
2525 let client = ApiClient::new(&base, Some("tok"));
2526 let err = client
2527 .register_repo(crate::api_client::RegisterRepoRequest {
2528 repo_name: "repo".into(),
2529 github_url: Some("git@github.com:org/repo.git".into()),
2530 })
2531 .await
2532 .unwrap_err();
2533 let msg = registration_failure_message(err.as_ref());
2534 assert!(
2535 msg.contains("not authorized"),
2536 "403 registration failure must surface a not-authorized message; got: {msg}"
2537 );
2538 }
2539
2540 #[tokio::test]
2543 async fn registration_failure_message_generic_for_non_403() {
2544 let base = spawn_once(http_response("500 Internal Server Error", ""));
2545 let client = ApiClient::new(&base, Some("tok"));
2546 let err = client
2547 .register_repo(crate::api_client::RegisterRepoRequest {
2548 repo_name: "repo".into(),
2549 github_url: Some("git@github.com:org/repo.git".into()),
2550 })
2551 .await
2552 .unwrap_err();
2553 let msg = registration_failure_message(err.as_ref());
2554 assert!(
2555 msg.contains("could not register repo on server"),
2556 "got: {msg}"
2557 );
2558 assert!(!msg.contains("not authorized"), "got: {msg}");
2559 }
2560
2561 #[tokio::test]
2566 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2567 let base = spawn_once(http_response(
2568 "500 Internal Server Error",
2569 "upstream error 403 from proxy",
2570 ));
2571 let client = ApiClient::new(&base, Some("tok"));
2572 let err = client
2573 .register_repo(crate::api_client::RegisterRepoRequest {
2574 repo_name: "repo".into(),
2575 github_url: Some("git@github.com:org/repo.git".into()),
2576 })
2577 .await
2578 .unwrap_err();
2579 let msg = registration_failure_message(err.as_ref());
2580 assert!(
2581 !msg.contains("not authorized"),
2582 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2583 );
2584 assert!(
2585 msg.contains("could not register repo on server"),
2586 "got: {msg}"
2587 );
2588 }
2589
2590 #[tokio::test]
2594 async fn registration_failure_message_flags_404_as_version_mismatch() {
2595 let base = spawn_once(http_response("404 Not Found", ""));
2596 let client = ApiClient::new(&base, Some("tok"));
2597 let err = client
2598 .register_repo(crate::api_client::RegisterRepoRequest {
2599 repo_name: "repo".into(),
2600 github_url: Some("git@github.com:org/repo.git".into()),
2601 })
2602 .await
2603 .unwrap_err();
2604 let msg = registration_failure_message(err.as_ref());
2605 assert!(
2606 msg.to_lowercase().contains("version mismatch"),
2607 "a 404 registration failure should hint at a version mismatch; got: {msg}"
2608 );
2609 }
2610
2611 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2615 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2616 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2617 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2618
2619 fn resolve_remote_ok() -> String {
2620 http_response(
2621 "200 OK",
2622 &format!(
2623 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2624 ),
2625 )
2626 }
2627
2628 fn remote_detail(repos: &[(&str, &str)]) -> String {
2629 let repos: Vec<String> = repos
2630 .iter()
2631 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2632 .collect();
2633 http_response(
2634 "200 OK",
2635 &format!(
2636 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2637 repos.join(",")
2638 ),
2639 )
2640 }
2641
2642 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2645 let (base, rx) = crate::test_helpers::spawn_seq(responses);
2646 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2647 _guard.set("XDG_CONFIG_HOME", root);
2648 _guard.set("TRACEVAULT_API_KEY", "tok");
2649 _guard.remove("TRACEVAULT_SERVER_URL");
2650
2651 init_in_directory(
2652 root,
2653 Some(&base),
2654 None,
2655 true,
2656 Some(crate::config::UserContext::Toggle(false)),
2657 crate::agent::Agent::Codex,
2658 )
2659 .await
2660 .expect("init succeeds");
2661
2662 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2663 (cfg.repo_id, rx.try_iter().collect())
2664 }
2665
2666 fn registered(requests: &[String]) -> bool {
2667 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2668 }
2669
2670 #[tokio::test]
2673 async fn init_binds_the_existing_repo_of_a_known_remote() {
2674 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2675 let tmp = tempfile::tempdir().unwrap();
2676 crate::test_helpers::init_git_repo(tmp.path());
2677 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2678
2679 let (repo_id, requests) = init_against(
2680 tmp.path(),
2681 vec![
2682 resolve_remote_ok(),
2683 remote_detail(&[(CANONICAL, "tracevault")]),
2684 ],
2685 )
2686 .await;
2687
2688 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2689 assert!(!registered(&requests), "requests: {requests:?}");
2690 }
2691
2692 #[tokio::test]
2695 async fn init_binds_the_record_named_like_the_checkout() {
2696 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2697 let tmp = tempfile::tempdir().unwrap();
2698 crate::test_helpers::init_git_repo(tmp.path());
2699 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2700 let dir_name = crate::resolution::git_repo_name(tmp.path());
2701
2702 let (repo_id, requests) = init_against(
2703 tmp.path(),
2704 vec![
2705 resolve_remote_ok(),
2706 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2707 ],
2708 )
2709 .await;
2710
2711 assert_eq!(repo_id.as_deref(), Some(STRAY));
2712 assert!(!registered(&requests));
2713 }
2714
2715 #[tokio::test]
2717 async fn init_rerun_keeps_the_previously_bound_repo() {
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 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2723 fs::write(
2724 tmp.path().join(".tracevault/config.toml"),
2725 format!("repo_id = \"{STRAY}\"\n"),
2726 )
2727 .unwrap();
2728
2729 let (repo_id, requests) = init_against(
2730 tmp.path(),
2731 vec![
2732 resolve_remote_ok(),
2733 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2734 ],
2735 )
2736 .await;
2737
2738 assert_eq!(repo_id.as_deref(), Some(STRAY));
2739 assert!(!registered(&requests));
2740 }
2741
2742 #[tokio::test]
2745 async fn init_binding_keeps_the_rest_of_the_config() {
2746 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2747 let tmp = tempfile::tempdir().unwrap();
2748 crate::test_helpers::init_git_repo(tmp.path());
2749 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2750 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2751 fs::write(
2752 tmp.path().join(".tracevault/config.toml"),
2753 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
2754 )
2755 .unwrap();
2756
2757 let (repo_id, _) = init_against(
2758 tmp.path(),
2759 vec![
2760 resolve_remote_ok(),
2761 remote_detail(&[(CANONICAL, "tracevault")]),
2762 ],
2763 )
2764 .await;
2765
2766 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2767 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
2768 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
2769 assert_eq!(cfg.default_project.as_deref(), Some("payments"));
2770 }
2771
2772 #[tokio::test]
2775 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
2776 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2777 let tmp = tempfile::tempdir().unwrap();
2778 crate::test_helpers::init_git_repo(tmp.path());
2779 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2780 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2781 fs::write(
2782 tmp.path().join(".tracevault/config.toml"),
2783 format!("repo_id = \"{STRAY}\"\n"),
2784 )
2785 .unwrap();
2786
2787 let (repo_id, requests) = init_against(
2788 tmp.path(),
2789 vec![http_response("500 Internal Server Error", "{}")],
2790 )
2791 .await;
2792
2793 assert_eq!(repo_id.as_deref(), Some(STRAY));
2794 assert!(!registered(&requests));
2795 }
2796
2797 #[tokio::test]
2799 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2800 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2801 let tmp = tempfile::tempdir().unwrap();
2802 crate::test_helpers::init_git_repo(tmp.path());
2803 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2804
2805 let (repo_id, requests) = init_against(
2806 tmp.path(),
2807 vec![
2808 resolve_remote_ok(),
2809 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2810 ],
2811 )
2812 .await;
2813
2814 assert_eq!(repo_id, None);
2815 assert!(!registered(&requests));
2816 }
2817
2818 #[tokio::test]
2821 async fn init_registers_for_a_codebase_without_live_repos() {
2822 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2823 let tmp = tempfile::tempdir().unwrap();
2824 crate::test_helpers::init_git_repo(tmp.path());
2825 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2826
2827 let (repo_id, requests) = init_against(
2828 tmp.path(),
2829 vec![
2830 resolve_remote_ok(),
2831 remote_detail(&[]),
2832 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2833 ],
2834 )
2835 .await;
2836
2837 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2838 assert!(registered(&requests));
2839 }
2840
2841 #[tokio::test]
2843 async fn init_does_not_register_when_the_remote_check_fails() {
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![http_response("500 Internal Server Error", "{}")],
2852 )
2853 .await;
2854
2855 assert_eq!(repo_id, None);
2856 assert!(!registered(&requests));
2857 }
2858}