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
109 | crate::agent::Agent::Gsd
110 | crate::agent::Agent::OpenCode
111 | crate::agent::Agent::Amp
112 ) && claude_settings_set
113 {
114 return Err("--claude-settings only applies to --agent claude-code".to_string());
115 }
116 Ok(())
117}
118
119pub async fn init_in_directory(
124 project_root: &Path,
125 server_url: Option<&str>,
126 claude_settings: Option<ClaudeSettingsTarget>,
127 no_gitignore: bool,
128 user_context: Option<UserContext>,
129 agent: crate::agent::Agent,
130) -> Result<String, io::Error> {
131 if !project_root.join(".git").exists() {
133 return Err(io::Error::new(
134 io::ErrorKind::NotFound,
135 "Not a git repository. Run 'git init' first.",
136 ));
137 }
138
139 if let Some(primary) = linked_worktree_primary(project_root) {
145 return Err(io::Error::new(
146 io::ErrorKind::Unsupported,
147 format!(
148 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
149 cd there and run it again — all worktrees share the primary's .tracevault/.",
150 primary.display()
151 ),
152 ));
153 }
154
155 let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
159 io::Error::new(
160 io::ErrorKind::InvalidData,
161 format!(
162 "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
163 then run `tracevault init` again."
164 ),
165 )
166 })?;
167
168 let (resolved_url, resolved_credential) =
177 crate::credentials::resolve_credentials_quiet(project_root)
178 .map_err(|e| io::Error::other(e.to_string()))?;
179 let effective_url = server_url.map(String::from).or(resolved_url);
180 if resolved_credential.is_none() {
181 return Err(io::Error::new(
182 io::ErrorKind::PermissionDenied,
183 not_logged_in_message(effective_url.as_deref()),
184 ));
185 }
186
187 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
190 {
191 crate::agent::Agent::ClaudeCode => {
192 let target = resolve_claude_target(claude_settings)?;
193 (Some(target), target.gitignore_entry().to_string())
194 }
195 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
196 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
202 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
207 crate::agent::Agent::Amp => (None, AMP_PLUGIN_GITIGNORE_ENTRY.to_string()),
210 };
211
212 let config_dir = TracevaultConfig::config_dir(project_root);
214 fs::create_dir_all(&config_dir)?;
215 fs::create_dir_all(config_dir.join("sessions"))?;
216 fs::create_dir_all(config_dir.join("cache"))?;
217 TracevaultConfig::ensure_gitignore(&config_dir)?;
220
221 if !no_gitignore {
223 update_root_gitignore(project_root, &hook_gitignore_entry)?;
224 }
225
226 let remote_url = git_remote_url(project_root);
228 if remote_url.is_none() {
229 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
230 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
231 }
232
233 let mut config = existing_config.unwrap_or_default();
238 if let Some(url) = server_url {
239 config.server_url = Some(url.to_string());
240 }
241 config.user_context = user_context
242 .or(config.user_context)
243 .or(Some(UserContext::Toggle(true)));
244 config.save(project_root)?;
245
246 let previous_repo_id = config
249 .repo_id
250 .as_deref()
251 .and_then(|id| id.parse::<uuid::Uuid>().ok());
252
253 match agent {
255 crate::agent::Agent::ClaudeCode => {
256 let target =
258 claude_target.expect("claude settings target is resolved for the Claude agent");
259 install_claude_hooks(project_root, target)?;
260 }
261 crate::agent::Agent::Codex => {
262 install_codex_hooks(project_root)?;
263 println!("{}", codex_hook_trust_notice());
264 }
265 crate::agent::Agent::Gsd => {
266 install_gsd_extension(Some(project_root))?;
274 }
275 crate::agent::Agent::OpenCode => {
276 install_opencode_plugin(Some(project_root))?;
277 }
278 crate::agent::Agent::Amp => {
279 let path = install_amp_plugin(Some(project_root))?;
280 println!("Installed the TraceVault Amp plugin in {}", path.display());
281 println!("{}", amp_headless_notice());
282 }
283 }
284
285 install_git_hook(project_root)?;
287 install_post_commit_hook(project_root)?;
288
289 let detected = crate::hooks::detect_tools(project_root);
291 for tool in &detected {
292 println!(" Detected: {}", tool.name());
293 }
294
295 if let (Some(url), Some(remote)) = (effective_url, remote_url) {
296 let client = ApiClient::with_credential(&url, resolved_credential);
297 let repo_name = git_repo_name(project_root);
298 let origin_url = remote.clone();
301
302 match crate::resolution::plan_registration(
306 &client,
307 &origin_url,
308 &repo_name,
309 previous_repo_id,
310 )
311 .await
312 {
313 Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
314 println!(
315 "Bound to existing repo {} (id: {repo_id}); not registering another record \
316 for this codebase",
317 codebase
318 .repos
319 .iter()
320 .find(|r| r.id == repo_id)
321 .map_or("", |r| r.name.as_str())
322 );
323 println!(
324 "{}",
325 crate::resolution::codebase_line(
326 codebase.remote.name.as_deref(),
327 &codebase.remote.normalized_url,
328 &codebase.remote.clone_status
329 )
330 );
331 persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
332 }
333 Ok(RegistrationPlan::Ambiguous(codebase)) => {
334 eprintln!(
335 "Warning: codebase {} already has {} repo records ({}) and none is named \
336 '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
337 .tracevault/config.toml to the one this checkout belongs to.",
338 codebase.display_name(),
339 codebase.repos.len(),
340 codebase.repo_list()
341 );
342 }
343 Ok(RegistrationPlan::Register) => {
344 register_new_repo(&client, project_root, repo_name, origin_url).await;
345 }
346 Err(e) => {
349 eprintln!(
350 "Warning: could not check the server for an existing repo of this remote \
351 ({e}); not registering. Run `tracevault init` again once the server is \
352 reachable."
353 );
354 }
355 }
356 }
357
358 Ok(hook_gitignore_entry)
359}
360
361pub fn not_logged_in_message(url: Option<&str>) -> String {
366 let url = url.unwrap_or("<URL>");
367 format!(
368 "Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
369 would record nothing, so nothing was installed.\n\
370 Log in, then run init again:\n\
371 \n tracevault login --server-url {url}\n tracevault init\n\n\
372 (In CI, set TRACEVAULT_API_KEY instead of logging in.)"
373 )
374}
375
376pub(crate) fn persist_repo_binding(
383 project_root: &Path,
384 repo_id: uuid::Uuid,
385 codebase: Option<&crate::api_client::ResolveRemoteResponse>,
386) -> bool {
387 let Some(mut cfg) = TracevaultConfig::load(project_root) else {
388 return false;
389 };
390 cfg.repo_id = Some(repo_id.to_string());
391 if let Some(remote) = codebase {
392 cfg.remote_id = Some(remote.remote_id.to_string());
393 cfg.codebase_name = remote.name.clone();
394 }
395 cfg.save(project_root).is_ok()
396}
397
398async fn register_new_repo(
402 client: &ApiClient,
403 project_root: &Path,
404 repo_name: String,
405 origin_url: String,
406) {
407 match client
408 .register_repo(crate::api_client::RegisterRepoRequest {
409 repo_name,
410 github_url: Some(origin_url.clone()),
411 })
412 .await
413 {
414 Ok(resp) => {
415 println!("Repo registered on server (id: {})", resp.repo_id);
416 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
418 cfg.repo_id = Some(resp.repo_id.to_string());
419 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
425 println!(
426 "{}",
427 crate::resolution::codebase_line(
428 remote.name.as_deref(),
429 &remote.normalized_url,
430 &remote.clone_status
431 )
432 );
433 cfg.remote_id = Some(remote.remote_id.to_string());
434 cfg.codebase_name = remote.name.clone();
435 }
436 let _ = cfg.save(project_root);
437 }
438 }
439 Err(e) => {
440 eprintln!("{}", registration_failure_message(e.as_ref()));
441 }
442 }
443}
444
445fn registration_failure_message(err: &dyn std::error::Error) -> String {
460 let msg = err.to_string();
461 if msg.starts_with("Server returned 403 ") {
462 "Warning: you are not authorized to register this repo.".to_string()
463 } else if msg.starts_with("Server returned 404 ") {
464 "Warning: could not register repo on server (404) — this endpoint may not exist on \
465 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
466 once the server is upgraded."
467 .to_string()
468 } else {
469 format!("Warning: could not register repo on server: {err}")
470 }
471}
472
473fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
474 let path = project_root.join(".gitignore");
475 let existing = if path.exists() {
476 fs::read_to_string(&path)?
477 } else {
478 String::new()
479 };
480
481 let needed: Vec<&str> = [".tracevault/", settings_entry]
487 .iter()
488 .copied()
489 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
490 .collect();
491
492 if needed.is_empty() {
493 return Ok(());
494 }
495
496 let mut content = existing;
497 if !content.is_empty() && !content.ends_with('\n') {
498 content.push('\n');
499 }
500 content.push_str("\n# TraceVault — local only, do not commit\n");
501 for entry in needed {
502 content.push_str(entry);
503 content.push('\n');
504 }
505
506 fs::write(path, content)
507}
508
509const HOOK_MARKER: &str = "# tracevault:enforce";
510const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
511
512fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
513 let hooks_dir = project_root.join(".git/hooks");
514 fs::create_dir_all(&hooks_dir)?;
515
516 let hook_path = hooks_dir.join("pre-push");
517 let tracevault_block = format!(
524 "{HOOK_MARKER}\n\
525 # Capture git's pre-push ref list once; `check` uses it to determine\n\
526 # which files are being pushed.\n\
527 tracevault_prepush_stdin=$(cat)\n\
528 tracevault sync 2>/dev/null || true\n\
529 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
530 );
531
532 if hook_path.exists() {
533 let existing = fs::read_to_string(&hook_path)?;
534
535 if existing.contains(HOOK_MARKER) {
537 return Ok(());
538 }
539
540 if existing.contains(OLD_HOOK_MARKER) {
542 let mut new_content = String::new();
543 let mut skip = false;
544 for line in existing.lines() {
545 if line.contains(OLD_HOOK_MARKER) {
546 skip = true;
547 continue;
548 }
549 if skip {
550 if line.starts_with("tracevault ") {
552 continue;
553 }
554 skip = false;
555 }
556 new_content.push_str(line);
557 new_content.push('\n');
558 }
559 if !new_content.ends_with('\n') {
560 new_content.push('\n');
561 }
562 new_content.push_str(&tracevault_block);
563 fs::write(&hook_path, new_content)?;
564 } else {
565 let mut content = existing;
567 if !content.ends_with('\n') {
568 content.push('\n');
569 }
570 content.push_str(&tracevault_block);
571 fs::write(&hook_path, content)?;
572 }
573 } else {
574 let content = format!("#!/bin/sh\n{tracevault_block}");
575 fs::write(&hook_path, content)?;
576 }
577
578 #[cfg(unix)]
580 {
581 use std::os::unix::fs::PermissionsExt;
582 let mut perms = fs::metadata(&hook_path)?.permissions();
583 perms.set_mode(0o755);
584 fs::set_permissions(&hook_path, perms)?;
585 }
586
587 Ok(())
588}
589
590const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
591
592fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
593 let hooks_dir = project_root.join(".git/hooks");
594 fs::create_dir_all(&hooks_dir)?;
595
596 let hook_path = hooks_dir.join("post-commit");
597 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
598
599 if hook_path.exists() {
600 let existing = fs::read_to_string(&hook_path)?;
601
602 if existing.contains(POST_COMMIT_MARKER) {
603 return Ok(());
604 }
605
606 let mut content = existing;
607 if !content.ends_with('\n') {
608 content.push('\n');
609 }
610 content.push_str(&tracevault_block);
611 fs::write(&hook_path, content)?;
612 } else {
613 let content = format!("#!/bin/sh\n{tracevault_block}");
614 fs::write(&hook_path, content)?;
615 }
616
617 #[cfg(unix)]
618 {
619 use std::os::unix::fs::PermissionsExt;
620 let mut perms = fs::metadata(&hook_path)?.permissions();
621 perms.set_mode(0o755);
622 fs::set_permissions(&hook_path, perms)?;
623 }
624
625 Ok(())
626}
627
628fn install_claude_hooks(
629 project_root: &Path,
630 target: ClaudeSettingsTarget,
631) -> Result<(), io::Error> {
632 let claude_dir = project_root.join(".claude");
633 fs::create_dir_all(&claude_dir)?;
634 merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
635}
636
637pub fn tracevault_hooks() -> serde_json::Value {
638 serde_json::json!({
639 "PreToolUse": [{
640 "matcher": "Write|Edit|Bash",
641 "hooks": [{
642 "type": "command",
643 "command": "tracevault stream --event pre-tool-use",
644 "timeout": 10,
645 "statusMessage": "TraceVault: streaming pre-tool event"
646 }]
647 }],
648 "PostToolUse": [{
649 "matcher": "",
650 "hooks": [{
651 "type": "command",
652 "command": "tracevault stream --event post-tool-use",
653 "timeout": 10,
654 "statusMessage": "TraceVault: streaming post-tool event"
655 }]
656 }],
657 "Notification": [{
658 "matcher": "",
659 "hooks": [{
660 "type": "command",
661 "command": "tracevault stream --event notification",
662 "timeout": 10,
663 "statusMessage": "TraceVault: streaming notification"
664 }]
665 }],
666 "Stop": [{
667 "matcher": "",
668 "hooks": [{
669 "type": "command",
670 "command": "tracevault stream --event stop",
671 "timeout": 10,
672 "statusMessage": "TraceVault: finalizing session"
673 }]
674 }],
675 "SessionEnd": [{
678 "matcher": "",
679 "hooks": [{
680 "type": "command",
681 "command": "tracevault stream --event session-end",
682 "timeout": 10,
683 "statusMessage": "TraceVault: sending session cost"
684 }]
685 }],
686 "SubagentStop": [{
689 "matcher": "",
690 "hooks": [{
691 "type": "command",
692 "command": "tracevault stream --event subagent-stop",
693 "timeout": 10,
694 "statusMessage": "TraceVault: streaming subagent transcript"
695 }]
696 }],
697 "SessionStart": [{
698 "matcher": "",
699 "hooks": [{
700 "type": "command",
701 "command": "tracevault session-start",
702 "timeout": 10,
703 "statusMessage": "TraceVault: session start"
704 }]
705 }],
706 "UserPromptSubmit": [{
707 "matcher": "",
708 "hooks": [{
709 "type": "command",
710 "command": "tracevault user-prompt",
711 "timeout": 10,
712 "statusMessage": "TraceVault: policy reinforcement"
713 }]
714 }]
715 })
716}
717
718pub fn codex_hook_trust_notice() -> &'static str {
728 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
729 silently and no session is captured. Run `codex` once interactively in a repo and \
730 approve the hook-trust prompt; unattended runs (CI) can pass \
731 `--dangerously-bypass-hook-trust` instead."
732}
733
734pub fn codex_hooks() -> serde_json::Value {
744 serde_json::json!({
745 "SessionStart": [{
746 "matcher": "",
747 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
748 }],
749 "UserPromptSubmit": [{
750 "matcher": "",
751 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
752 }],
753 "PostToolUse": [{
754 "matcher": "",
755 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
756 }],
757 "Stop": [{
758 "matcher": "",
759 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
760 }]
761 })
762}
763
764const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
768const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
769const GSD_EXT_MANIFEST_JSON: &str =
770 include_str!("../../assets/gsd-extension/extension-manifest.json");
771
772fn gsd_extension_source_dir() -> io::Result<PathBuf> {
776 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
777 let config_dir = config_dir
778 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
779 Ok(config_dir.join("tracevault").join("gsd-extension"))
780}
781
782pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
806 let home =
807 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
808 let gsd_home = home.join(".gsd");
809
810 let source_dir = gsd_extension_source_dir()?;
811 fs::create_dir_all(&source_dir)?;
812 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
813 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
814 fs::write(
815 source_dir.join("extension-manifest.json"),
816 GSD_EXT_MANIFEST_JSON,
817 )?;
818
819 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
823 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
824 }
825
826 let local_flag = project_root.is_some();
830 let mut cmd = std::process::Command::new("gsd");
831 cmd.arg("install").arg(&source_dir);
832 if let Some(root) = project_root {
833 cmd.arg("-l");
834 cmd.current_dir(root);
835 }
836
837 let retry_hint = format!(
838 "gsd install {}{}",
839 source_dir.display(),
840 if local_flag { " -l" } else { "" }
841 );
842
843 match cmd.output() {
844 Ok(output) if output.status.success() => {
845 println!(
846 "TraceVault: installed and registered the GSD extension ({}).",
847 source_dir.display()
848 );
849 }
850 Ok(output) => {
851 eprintln!(
852 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
853 source_dir.display(),
854 String::from_utf8_lossy(&output.stderr),
855 );
856 }
857 Err(e) => {
858 eprintln!(
859 "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.",
860 source_dir.display(),
861 );
862 }
863 }
864
865 Ok(())
866}
867
868const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
871
872pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
888 let plugins_dir = match project_root {
889 Some(root) => root.join(".opencode").join("plugins"),
890 None => {
891 let config_dir =
892 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
893 config_dir
894 .ok_or_else(|| {
895 io::Error::new(
896 io::ErrorKind::NotFound,
897 "could not determine the config directory for the OpenCode plugin install",
898 )
899 })?
900 .join("opencode")
901 .join("plugins")
902 }
903 };
904
905 write_opencode_plugin_files(&plugins_dir)
906}
907
908fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
909 fs::create_dir_all(plugins_dir)?;
910 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
911 Ok(())
912}
913
914pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");
917
918const AMP_PLUGIN_GITIGNORE_ENTRY: &str = ".amp/plugins/tracevault/";
920
921pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
930 let plugins_dir = match project_root {
931 Some(root) => root.join(".amp").join("plugins"),
932 None => amp_user_config_dir()
933 .ok_or_else(|| {
934 io::Error::new(
935 io::ErrorKind::NotFound,
936 "could not determine the config directory for the Amp plugin install",
937 )
938 })?
939 .join("plugins"),
940 };
941 let plugin_dir = plugins_dir.join("tracevault");
942 fs::create_dir_all(&plugin_dir)?;
943 let path = plugin_dir.join("index.ts");
944 fs::write(&path, AMP_PLUGIN_INDEX)?;
945 Ok(path)
946}
947
948fn amp_user_config_dir() -> Option<PathBuf> {
952 let xdg = std::env::var_os("XDG_CONFIG_HOME")
953 .map(PathBuf::from)
954 .filter(|p| p.is_absolute());
955 xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
956 .map(|c| c.join("amp"))
957}
958
959pub fn amp_headless_notice() -> &'static str {
964 "Amp loads the plugin in interactive sessions. For headless runs use \
965`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
966starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
967path), so allow what it needs up front.\n\
968The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
969unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
970ampcode.com, or exports it, can read them."
971}
972
973pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
985 let ext_root = gsd_home.join("extensions");
986 let reg_path = ext_root.join("registry.json");
987
988 let reg: Option<serde_json::Value> = if reg_path.exists() {
993 let content = fs::read_to_string(®_path)?;
994 let parsed: serde_json::Value = match serde_json::from_str(&content) {
995 Ok(v) => v,
996 Err(_) => return Ok(()), };
998 let corrupt = match parsed.as_object() {
999 None => true,
1000 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
1001 };
1002 if corrupt {
1003 return Ok(()); }
1005 Some(parsed)
1006 } else {
1007 None
1008 };
1009
1010 let stale = ext_root.join("tracevault-tracker");
1012 if stale.exists() {
1013 fs::remove_dir_all(&stale)?;
1014 }
1015
1016 if let Some(mut reg) = reg {
1018 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
1019 let removed_tracker = entries.remove("tracevault-tracker").is_some();
1020 let removed_inert = entries.remove("tracevault").is_some();
1021 if removed_tracker || removed_inert {
1022 let tmp = reg_path.with_extension("json.tmp");
1024 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
1025 fs::rename(&tmp, ®_path)?;
1026 }
1027 }
1028 }
1029 Ok(())
1030}
1031
1032fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
1042 update_json_file(hooks_path, "its hooks", |root| {
1043 merge_hooks(root, ours, hooks_path)
1044 })
1045}
1046
1047pub(crate) fn update_json_file(
1055 path: &Path,
1056 what: &str,
1057 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
1058) -> io::Result<()> {
1059 if path
1064 .components()
1065 .any(|c| c == std::path::Component::ParentDir)
1066 {
1067 return Err(io::Error::new(
1068 io::ErrorKind::InvalidInput,
1069 format!("refusing to use path with '..': {}", path.display()),
1070 ));
1071 }
1072 let target = match fs::symlink_metadata(path) {
1076 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
1077 _ => path.to_path_buf(),
1078 };
1079 for _ in 0..3 {
1085 let existing = read_existing(&target)?;
1086 let mut root: serde_json::Value = match &existing {
1087 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1088 io::Error::new(
1089 io::ErrorKind::InvalidData,
1090 format!("Failed to parse {}: {e}", path.display()),
1091 )
1092 })?,
1093 None => serde_json::json!({}),
1094 };
1095
1096 let before = existing.is_some().then(|| root.to_string());
1097 mutate(&mut root)?;
1098 if before.as_deref() == Some(root.to_string().as_str())
1099 || (existing.is_none() && root == serde_json::json!({}))
1100 {
1101 return Ok(());
1102 }
1103
1104 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1105 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1106 })?;
1107 let tmp = unique_temp_sibling(&target);
1108 let published = write_owner_only(&tmp, formatted.as_bytes())
1109 .and_then(|()| {
1110 match &existing {
1113 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1114 None => Ok(()),
1115 }
1116 })
1117 .and_then(|()| {
1118 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1119 == existing.as_ref().map(|(_, c)| c.clone());
1120 if unchanged {
1121 fs::rename(&tmp, &target).map(|()| true)
1122 } else {
1123 Ok(false)
1124 }
1125 });
1126 match published {
1127 Ok(true) => return Ok(()),
1128 Ok(false) => {
1129 let _ = fs::remove_file(&tmp);
1130 }
1131 Err(e) => {
1132 let _ = fs::remove_file(&tmp);
1133 return Err(e);
1134 }
1135 }
1136 }
1137 Err(io::Error::other(format!(
1138 "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1139 path.display()
1140 )))
1141}
1142
1143fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1145 let permissions = match fs::metadata(path) {
1146 Ok(meta) => meta.permissions(),
1147 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1148 Err(e) => return Err(e),
1149 };
1150 Ok(Some((permissions, fs::read_to_string(path)?)))
1151}
1152
1153fn unique_temp_sibling(target: &Path) -> PathBuf {
1157 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1158 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1159 let nanos = std::time::SystemTime::now()
1160 .duration_since(std::time::UNIX_EPOCH)
1161 .map(|d| d.subsec_nanos())
1162 .unwrap_or_default();
1163 let mut name = target.file_name().unwrap_or_default().to_os_string();
1164 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1165 target.with_file_name(name)
1166}
1167
1168fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1172 let mut options = fs::OpenOptions::new();
1173 options.write(true).create_new(true);
1174 #[cfg(unix)]
1175 {
1176 use std::os::unix::fs::OpenOptionsExt;
1177 options.mode(0o600);
1178 }
1179 options.open(path)?.write_all(contents)
1180}
1181
1182pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1186 let codex_dir = project_root.join(".codex");
1187 fs::create_dir_all(&codex_dir)?;
1188 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1189}
1190
1191pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1198 fs::create_dir_all(codex_dir)?;
1199 let base = codex_dir.canonicalize()?;
1201 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1202 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1203}
1204
1205const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1209
1210const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1211<!-- tracevault:workspace-mode -->
1212## TraceVault (workspace mode)
1213A session started in a registered repo's checkout is bound to that repo automatically. To work
1214on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1215policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1216one-off. Repos must already be registered with TraceVault.
1217";
1218
1219fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1225 if md_path
1227 .components()
1228 .any(|c| c == std::path::Component::ParentDir)
1229 {
1230 return Err(io::Error::new(
1231 io::ErrorKind::InvalidInput,
1232 format!("refusing to use path with '..': {}", md_path.display()),
1233 ));
1234 }
1235 let existing = if md_path.exists() {
1236 fs::read_to_string(md_path)?
1237 } else {
1238 String::new()
1239 };
1240 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1241 return Ok(());
1242 }
1243 let mut content = existing;
1244 if !content.is_empty() && !content.ends_with('\n') {
1245 content.push('\n');
1246 }
1247 if !content.is_empty() {
1248 content.push('\n');
1249 }
1250 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1251 fs::write(md_path, content)
1252}
1253
1254pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1258 let joined = base.join(name);
1259 if joined.parent() != Some(base) {
1260 return Err(io::Error::new(
1261 io::ErrorKind::InvalidInput,
1262 format!(
1263 "refusing to access path outside {}: {}",
1264 base.display(),
1265 joined.display()
1266 ),
1267 ));
1268 }
1269 Ok(joined)
1270}
1271
1272const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1278
1279fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1280 hook.get("command")
1281 .and_then(|c| c.as_str())
1282 .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1283}
1284
1285fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1292 let mut slot = None;
1293 let mut kept = Vec::with_capacity(entries.len());
1294 for mut entry in entries.drain(..) {
1295 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1296 let before = inner.len();
1297 inner.retain(|hook| !is_tracevault_hook(hook));
1298 if inner.is_empty() && before > 0 {
1299 slot.get_or_insert(kept.len());
1300 continue;
1301 }
1302 }
1303 kept.push(entry);
1304 }
1305 *entries = kept;
1306 slot
1307}
1308
1309fn merge_hooks(
1323 settings: &mut serde_json::Value,
1324 ours: &serde_json::Value,
1325 path: &Path,
1326) -> io::Result<()> {
1327 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1328 io::Error::new(
1329 io::ErrorKind::InvalidData,
1330 format!("{} is not a JSON object", path.display()),
1331 )
1332 })?;
1333
1334 let hooks_value = settings_obj
1335 .entry("hooks")
1336 .or_insert_with(|| serde_json::json!({}));
1337 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1338 io::Error::new(
1339 io::ErrorKind::InvalidData,
1340 format!("{} \"hooks\" key is not a JSON object", path.display()),
1341 )
1342 })?;
1343
1344 let empty = serde_json::Map::new();
1345 let ours_obj = ours.as_object().unwrap_or(&empty);
1346
1347 for event in ours_obj.keys() {
1349 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1350 return Err(io::Error::new(
1351 io::ErrorKind::InvalidData,
1352 format!(
1353 "{} \"hooks\".\"{event}\" is not a JSON array",
1354 path.display()
1355 ),
1356 ));
1357 }
1358 }
1359
1360 let mut emptied = Vec::new();
1361 for (event, value) in hooks_obj.iter_mut() {
1362 let Some(existing) = value.as_array_mut() else {
1363 continue;
1364 };
1365 let had_entries = !existing.is_empty();
1366 let slot = strip_tracevault_hooks(existing);
1367 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1368 match our_entries {
1369 Some(our_entries) => {
1370 let at = slot.unwrap_or(existing.len());
1371 existing.splice(at..at, our_entries.iter().cloned());
1372 }
1373 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1374 None => {}
1375 }
1376 }
1377 hooks_obj.retain(|event, _| !emptied.contains(event));
1379
1380 for (event, our_array) in ours_obj {
1381 if !hooks_obj.contains_key(event) {
1382 hooks_obj.insert(event.clone(), our_array.clone());
1383 }
1384 }
1385
1386 Ok(())
1387}
1388
1389pub(crate) fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
1393 let text = match fs::read_to_string(path) {
1394 Ok(text) => text,
1395 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
1396 Err(e) => return Err(e),
1397 };
1398 let settings: serde_json::Value =
1399 serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1400 Ok(settings
1401 .get("hooks")
1402 .and_then(|h| h.as_object())
1403 .into_iter()
1404 .flat_map(|events| events.values())
1405 .filter_map(|groups| groups.as_array())
1406 .flatten()
1407 .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
1408 .flatten()
1409 .any(is_tracevault_hook))
1410}
1411
1412pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
1416 merge_hooks_into_file(path, &tracevault_hooks())
1417}
1418
1419pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1425 fs::create_dir_all(claude_dir)?;
1426
1427 let base = claude_dir.canonicalize()?;
1430
1431 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1433
1434 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1436}
1437
1438pub fn write_global_user_config_in(
1448 config_root: &Path,
1449 requested: Option<UserContext>,
1450) -> io::Result<Option<PathBuf>> {
1451 fs::create_dir_all(config_root)?;
1452 let mut config = crate::config::try_load_user_config_in(config_root)
1454 .ok()
1455 .flatten()
1456 .unwrap_or_default();
1457 let user_context = requested
1459 .or_else(|| config.user_context.clone())
1460 .unwrap_or(UserContext::Toggle(true));
1461 let active = user_context
1462 .resolve()
1463 .map(|_| user_context.path_in(config_root));
1464 config.user_context = Some(user_context);
1465 fs::write(user_config_path_in(config_root), config.to_toml())?;
1466 if let Some(ref ctx_path) = active {
1467 if !ctx_path.exists() {
1468 Context::default().save_to(ctx_path)?;
1469 }
1470 }
1471 Ok(active)
1472}
1473
1474#[cfg(test)]
1475mod tests {
1476 use super::*;
1477 use std::io::{BufRead, BufReader, Write};
1478 use std::net::TcpListener;
1479 use std::thread;
1480
1481 #[test]
1487 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1488 let notice = codex_hook_trust_notice();
1489 assert!(
1490 notice.contains("hook trust"),
1491 "notice must name what is missing: {notice}"
1492 );
1493 assert!(
1494 notice.contains("codex") && notice.contains("approve"),
1495 "notice must tell the user to run codex and approve the prompt: {notice}"
1496 );
1497 assert!(
1498 notice.contains("--dangerously-bypass-hook-trust"),
1499 "notice must name the flag for unattended/CI runs: {notice}"
1500 );
1501 assert!(
1502 notice.contains("silently"),
1503 "notice must say the failure is silent, which is why it needs saying: {notice}"
1504 );
1505 }
1506
1507 fn spawn_once(response: String) -> String {
1510 let response: &'static str = Box::leak(response.into_boxed_str());
1511 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1512 let addr = listener.local_addr().unwrap();
1513 thread::spawn(move || {
1514 if let Ok((stream, _)) = listener.accept() {
1515 let mut reader = BufReader::new(stream);
1516 let mut request_line = String::new();
1517 let _ = reader.read_line(&mut request_line);
1518 let mut stream = reader.into_inner();
1519 let _ = stream.write_all(response.as_bytes());
1520 let _ = stream.flush();
1521 }
1522 });
1523 format!("http://{addr}")
1524 }
1525
1526 fn http_response(status: &str, body: &str) -> String {
1529 format!(
1530 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1531 status,
1532 body.len(),
1533 body
1534 )
1535 }
1536
1537 fn add_origin_remote(dir: &Path, url: &str) {
1538 let ok = std::process::Command::new("git")
1539 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1540 .status()
1541 .expect("git remote add failed")
1542 .success();
1543 assert!(ok, "git remote add must succeed");
1544 }
1545
1546 #[test]
1547 fn linked_worktree_primary_detects_linked_and_primary() {
1548 let tmp = tempfile::tempdir().unwrap();
1549 let repo = tmp.path().join("repo");
1550 let wt = tmp.path().join("linked-wt");
1551 std::fs::create_dir_all(&repo).unwrap();
1552 crate::test_helpers::init_git_repo(&repo);
1553 crate::test_helpers::add_worktree(&repo, &wt);
1554
1555 assert!(
1557 linked_worktree_primary(&repo).is_none(),
1558 "primary checkout must not be flagged as a linked worktree"
1559 );
1560 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1562 assert_eq!(
1563 primary.canonicalize().unwrap(),
1564 repo.canonicalize().unwrap(),
1565 "must resolve to the primary repo root"
1566 );
1567 }
1568
1569 #[test]
1570 fn linked_worktree_primary_none_for_non_git() {
1571 let tmp = tempfile::tempdir().unwrap();
1572 assert!(
1573 linked_worktree_primary(tmp.path()).is_none(),
1574 "a non-git directory is not a linked worktree"
1575 );
1576 }
1577
1578 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1580 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1581 }
1582
1583 #[test]
1584 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1585 let mut settings = serde_json::json!({});
1586 let ours = tracevault_hooks();
1587 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1588
1589 let hooks = settings.get("hooks").unwrap();
1590 for event in [
1591 "PreToolUse",
1592 "PostToolUse",
1593 "Notification",
1594 "Stop",
1595 "SessionEnd",
1596 "SubagentStop",
1597 "SessionStart",
1598 "UserPromptSubmit",
1599 ] {
1600 assert!(hooks.get(event).is_some(), "missing event {event}");
1601 }
1602 }
1603
1604 #[test]
1605 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1606 let mut settings = serde_json::json!({
1607 "model": "opus",
1608 "hooks": {
1609 "PreToolUse": [{
1610 "matcher": "",
1611 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1612 }]
1613 }
1614 });
1615 let ours = tracevault_hooks();
1616 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1617
1618 assert_eq!(settings.get("model").unwrap(), "opus");
1620
1621 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1622 assert_eq!(pre_tool_use.len(), 2);
1624 let commands: Vec<&str> = pre_tool_use
1625 .iter()
1626 .map(|e| entry_command(e).unwrap())
1627 .collect();
1628 assert!(commands.contains(&"my-own-hook"));
1629 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1630
1631 assert!(settings["hooks"]["SessionStart"].is_array());
1633 }
1634
1635 #[test]
1636 fn merge_hooks_is_idempotent() {
1637 let mut settings = serde_json::json!({});
1638 let ours = tracevault_hooks();
1639 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1640 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1641
1642 for event in [
1643 "PreToolUse",
1644 "PostToolUse",
1645 "Notification",
1646 "Stop",
1647 "SessionEnd",
1648 "SubagentStop",
1649 "SessionStart",
1650 "UserPromptSubmit",
1651 ] {
1652 let arr = settings["hooks"][event].as_array().unwrap();
1653 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1654 }
1655 }
1656
1657 #[test]
1658 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1659 let mut settings = serde_json::json!({
1663 "hooks": {
1664 "PreToolUse": [{
1665 "matcher": "Write|Edit|Bash",
1666 "hooks": [
1667 { "type": "command", "command": "other", "timeout": 3 },
1668 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1669 ]
1670 }]
1671 }
1672 });
1673 merge_hooks(
1674 &mut settings,
1675 &tracevault_hooks(),
1676 Path::new("settings.json"),
1677 )
1678 .unwrap();
1679
1680 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1681 assert_eq!(
1682 pre_tool_use[0],
1683 serde_json::json!({
1684 "matcher": "Write|Edit|Bash",
1685 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1686 })
1687 );
1688 assert_eq!(
1689 &pre_tool_use[1..],
1690 tracevault_hooks()["PreToolUse"].as_array().unwrap()
1691 );
1692 }
1693
1694 fn stale_tracevault_hooks() -> serde_json::Value {
1697 let entry = |matcher: &str, event: &str| {
1698 serde_json::json!([{
1699 "matcher": matcher,
1700 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1701 }])
1702 };
1703 serde_json::json!({
1704 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1705 "PostToolUse": entry("", "post-tool-use"),
1706 "Notification": entry("", "notification"),
1707 "Stop": entry("", "stop"),
1708 })
1709 }
1710
1711 #[test]
1712 fn merge_hooks_upgrades_stale_tracevault_entries() {
1713 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1714 merge_hooks(
1715 &mut settings,
1716 &tracevault_hooks(),
1717 Path::new("settings.json"),
1718 )
1719 .unwrap();
1720 assert_eq!(settings["hooks"], tracevault_hooks());
1721 }
1722
1723 #[test]
1724 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1725 let mut settings = serde_json::json!({
1728 "hooks": {
1729 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1730 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1731 "Custom": "left alone"
1732 }
1733 });
1734 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1735
1736 let hooks = settings["hooks"].as_object().unwrap();
1737 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
1738 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
1739 assert_eq!(hooks["Custom"], "left alone");
1740 for (event, entries) in codex_hooks().as_object().unwrap() {
1741 assert_eq!(&hooks[event], entries, "{event}");
1742 }
1743 }
1744
1745 #[test]
1746 fn merge_hooks_rerun_keeps_our_entry_in_place() {
1747 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
1750 settings["hooks"]["Stop"]
1751 .as_array_mut()
1752 .unwrap()
1753 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
1754 let before = settings.clone();
1755 merge_hooks(
1756 &mut settings,
1757 &tracevault_hooks(),
1758 Path::new("settings.json"),
1759 )
1760 .unwrap();
1761 assert_eq!(settings.to_string(), before.to_string());
1762 }
1763
1764 #[test]
1765 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
1766 let foreign = serde_json::json!({
1767 "matcher": "",
1768 "hooks": [
1769 { "type": "command", "command": "tracevault-wrapper stream" },
1770 { "type": "command", "command": "echo tracevault stream" },
1771 { "type": "command", "command": " tracevault check" }
1772 ]
1773 });
1774 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
1775 merge_hooks(
1776 &mut settings,
1777 &tracevault_hooks(),
1778 Path::new("settings.json"),
1779 )
1780 .unwrap();
1781 assert_eq!(settings["hooks"]["Stop"][0], foreign);
1782 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
1783 }
1784
1785 #[test]
1786 fn merge_hooks_errors_on_non_object_top_level() {
1787 let mut settings = serde_json::json!([1, 2, 3]);
1788 let ours = tracevault_hooks();
1789 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1790 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1791 assert!(err.to_string().contains("settings.json"));
1792 }
1793
1794 #[test]
1795 fn merge_hooks_errors_on_non_object_top_level_number() {
1796 let mut settings = serde_json::json!(42);
1797 let ours = tracevault_hooks();
1798 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1799 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1800 }
1801
1802 #[test]
1803 fn merge_hooks_errors_on_non_object_hooks() {
1804 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1805 let ours = tracevault_hooks();
1806 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1807 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1808 assert!(err.to_string().contains("hooks"));
1809 }
1810
1811 #[test]
1812 fn merge_hooks_errors_on_non_array_event_value() {
1813 let mut settings = serde_json::json!({
1814 "hooks": {
1815 "PreToolUse": "not-an-array"
1816 }
1817 });
1818 let ours = tracevault_hooks();
1819 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1820 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1821 assert!(err.to_string().contains("PreToolUse"));
1822 }
1823
1824 #[test]
1825 fn install_global_hooks_writes_settings_and_claude_md() {
1826 let tmp = tempfile::tempdir().unwrap();
1827 let claude_dir = tmp.path().join(".claude");
1828
1829 install_global_hooks(&claude_dir).unwrap();
1830
1831 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1832 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1833 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1834 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1835 }
1836
1837 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1838 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1839 }
1840
1841 #[test]
1842 fn install_global_hooks_is_idempotent() {
1843 let tmp = tempfile::tempdir().unwrap();
1844 let claude_dir = tmp.path().join(".claude");
1845
1846 install_global_hooks(&claude_dir).unwrap();
1847 install_global_hooks(&claude_dir).unwrap();
1848
1849 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1850 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1851 for event in [
1852 "PreToolUse",
1853 "PostToolUse",
1854 "Notification",
1855 "Stop",
1856 "SessionEnd",
1857 "SubagentStop",
1858 "SessionStart",
1859 "UserPromptSubmit",
1860 ] {
1861 let arr = settings["hooks"][event].as_array().unwrap();
1862 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1863 }
1864
1865 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1866 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1867 assert_eq!(
1868 marker_count, 1,
1869 "CLAUDE.md marker should appear exactly once"
1870 );
1871 }
1872
1873 #[test]
1874 fn install_global_hooks_preserves_existing_claude_md_content() {
1875 let tmp = tempfile::tempdir().unwrap();
1876 let claude_dir = tmp.path().join(".claude");
1877 fs::create_dir_all(&claude_dir).unwrap();
1878 fs::write(
1879 claude_dir.join("CLAUDE.md"),
1880 "# My existing notes\nSome content.\n",
1881 )
1882 .unwrap();
1883
1884 install_global_hooks(&claude_dir).unwrap();
1885
1886 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1887 assert!(claude_md.contains("# My existing notes"));
1888 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1889 }
1890
1891 #[test]
1892 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1893 let tmp = tempfile::tempdir().unwrap();
1894 let claude_dir = tmp.path().join(".claude");
1895
1896 install_global_hooks(&claude_dir).unwrap();
1897
1898 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1899 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1900 assert!(settings["hooks"].get("SessionStart").is_some());
1901
1902 let leftover = fs::read_dir(&claude_dir)
1903 .unwrap()
1904 .filter_map(|e| e.ok())
1905 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1906 assert!(
1907 !leftover,
1908 "no settings.json.tmp should remain after install"
1909 );
1910 }
1911
1912 #[test]
1913 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1914 let tmp = tempfile::tempdir().unwrap();
1915 let claude_dir = tmp.path().join(".claude");
1916 fs::create_dir_all(&claude_dir).unwrap();
1917 let settings_path = claude_dir.join("settings.json");
1918 let original = "[1, 2, 3]";
1919 fs::write(&settings_path, original).unwrap();
1920
1921 let err = install_global_hooks(&claude_dir).unwrap_err();
1922 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1923
1924 let after = fs::read_to_string(&settings_path).unwrap();
1927 assert_eq!(after, original);
1928 let leftover = fs::read_dir(&claude_dir)
1929 .unwrap()
1930 .filter_map(|e| e.ok())
1931 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1932 assert!(!leftover, "no tmp file should be left behind on error");
1933 }
1934
1935 #[test]
1936 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1937 let tmp = tempfile::tempdir().unwrap();
1938 let claude_dir = tmp.path().join(".claude");
1939 fs::create_dir_all(&claude_dir).unwrap();
1940 let settings_path = claude_dir.join("settings.json");
1941 let original = r#"{"hooks": "oops"}"#;
1942 fs::write(&settings_path, original).unwrap();
1943
1944 let err = install_global_hooks(&claude_dir).unwrap_err();
1945 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1946
1947 let after = fs::read_to_string(&settings_path).unwrap();
1948 assert_eq!(after, original);
1949 }
1950
1951 #[test]
1952 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1953 let tmp = tempfile::tempdir().unwrap();
1954 let claude_dir = tmp.path().join(".claude");
1955 fs::create_dir_all(&claude_dir).unwrap();
1956 let settings_path = claude_dir.join("settings.json");
1957 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1958 fs::write(&settings_path, original).unwrap();
1959
1960 let err = install_global_hooks(&claude_dir).unwrap_err();
1961 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1962
1963 let after = fs::read_to_string(&settings_path).unwrap();
1964 assert_eq!(after, original);
1965 }
1966
1967 #[test]
1968 fn safe_join_allows_direct_child_file() {
1969 let tmp = tempfile::tempdir().unwrap();
1970 let base = tmp.path();
1971 let result = safe_join(base, "settings.json").unwrap();
1972 assert_eq!(result.parent(), Some(base));
1973 assert_eq!(result.file_name().unwrap(), "settings.json");
1974 }
1975
1976 #[test]
1977 fn safe_join_rejects_path_traversal() {
1978 let tmp = tempfile::tempdir().unwrap();
1979 let base = tmp.path();
1980 let result = safe_join(base, "../evil");
1981 assert!(result.is_err());
1982 let err = result.unwrap_err();
1983 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1984 assert!(err.to_string().contains("refusing to access path outside"));
1985 }
1986
1987 #[test]
1988 fn safe_join_rejects_absolute_path() {
1989 let tmp = tempfile::tempdir().unwrap();
1990 let base = tmp.path();
1991 let result = safe_join(base, "/etc/passwd");
1992 assert!(result.is_err());
1995 }
1996
1997 #[test]
1998 fn write_global_user_config_enables_and_creates_context() {
1999 let root = tempfile::tempdir().unwrap();
2000 let active = write_global_user_config_in(root.path(), None).unwrap();
2001 let cfg = crate::config::try_load_user_config_in(root.path())
2002 .unwrap()
2003 .unwrap();
2004 assert_eq!(
2007 cfg.user_context.unwrap().resolve_in(root.path()),
2008 Some(crate::config::default_user_context_path_in(root.path()))
2009 );
2010 let ctx = crate::config::default_user_context_path_in(root.path());
2011 assert_eq!(active, Some(ctx.clone()));
2012 assert!(ctx.exists());
2013 }
2014
2015 #[test]
2016 fn write_global_user_config_can_disable() {
2017 let root = tempfile::tempdir().unwrap();
2018 let active = write_global_user_config_in(
2019 root.path(),
2020 Some(crate::config::UserContext::Toggle(false)),
2021 )
2022 .unwrap();
2023 let cfg = crate::config::try_load_user_config_in(root.path())
2024 .unwrap()
2025 .unwrap();
2026 assert!(matches!(
2027 cfg.user_context,
2028 Some(crate::config::UserContext::Toggle(false))
2029 ));
2030 assert_eq!(active, None, "disabled → no active context path");
2031 assert!(
2033 !crate::config::default_user_context_path_in(root.path()).exists(),
2034 "disabled user context must not create a context.json"
2035 );
2036 }
2037
2038 #[test]
2039 fn write_global_user_config_custom_path_seeds_that_file_only() {
2040 let root = tempfile::tempdir().unwrap();
2041 let custom = root.path().join("custom-ctx.json");
2042 let active = write_global_user_config_in(
2043 root.path(),
2044 Some(crate::config::UserContext::Path(
2045 custom.to_string_lossy().into_owned(),
2046 )),
2047 )
2048 .unwrap();
2049 assert_eq!(active, Some(custom.clone()));
2050 assert!(custom.exists(), "the configured custom path must be seeded");
2051 assert!(
2052 !crate::config::default_user_context_path_in(root.path()).exists(),
2053 "the default context.json must NOT be created when a custom path is configured"
2054 );
2055 }
2056
2057 #[test]
2058 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
2059 let root = tempfile::tempdir().unwrap();
2060 let custom = root.path().join("custom-ctx.json");
2061 write_global_user_config_in(
2063 root.path(),
2064 Some(crate::config::UserContext::Path(
2065 custom.to_string_lossy().into_owned(),
2066 )),
2067 )
2068 .unwrap();
2069 let active = write_global_user_config_in(root.path(), None).unwrap();
2071 assert_eq!(
2072 active,
2073 Some(custom.clone()),
2074 "re-run without flags must preserve the custom path"
2075 );
2076 let cfg = crate::config::try_load_user_config_in(root.path())
2077 .unwrap()
2078 .unwrap();
2079 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
2080 }
2081
2082 #[test]
2083 fn install_global_codex_hooks_writes_and_is_idempotent() {
2084 let tmp = tempfile::tempdir().unwrap();
2085 let codex_dir = tmp.path().join(".codex");
2086
2087 install_global_codex_hooks(&codex_dir).unwrap();
2088 install_global_codex_hooks(&codex_dir).unwrap();
2089
2090 let v: serde_json::Value =
2091 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2092 .unwrap();
2093 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2094 let arr = v["hooks"][event].as_array().unwrap();
2095 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
2096 }
2097 assert!(v["hooks"].get("PreToolUse").is_none());
2098 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
2100 assert_eq!(
2101 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
2102 1,
2103 "AGENTS.md workspace-mode block must appear exactly once"
2104 );
2105 let leftover = fs::read_dir(&codex_dir)
2107 .unwrap()
2108 .filter_map(|e| e.ok())
2109 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2110 assert!(!leftover);
2111 }
2112
2113 #[test]
2114 fn codex_hooks_has_expected_events_and_commands() {
2115 let h = codex_hooks();
2116 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2117 assert!(h.get(event).is_some(), "missing codex event {event}");
2118 }
2119 assert!(h.get("PreToolUse").is_none());
2123 assert!(h.get("Notification").is_none());
2124 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2126 assert_eq!(
2127 cmd("PostToolUse"),
2128 "tracevault stream --event post-tool-use --agent codex"
2129 );
2130 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2131 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2132 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2133 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2135 }
2136
2137 #[test]
2138 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2139 let tmp = tempfile::tempdir().unwrap();
2140 install_codex_hooks(tmp.path()).unwrap();
2141 install_codex_hooks(tmp.path()).unwrap();
2142
2143 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2144 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2145 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2146 let arr = v["hooks"][event].as_array().unwrap();
2147 assert_eq!(
2148 arr.len(),
2149 1,
2150 "event {event} must not be duplicated on re-run"
2151 );
2152 }
2153 assert!(v["hooks"].get("PreToolUse").is_none());
2154 }
2155
2156 #[test]
2157 fn install_codex_hooks_preserves_existing_user_hook() {
2158 let tmp = tempfile::tempdir().unwrap();
2159 let codex_dir = tmp.path().join(".codex");
2160 fs::create_dir_all(&codex_dir).unwrap();
2161 fs::write(
2164 codex_dir.join("hooks.json"),
2165 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2166 )
2167 .unwrap();
2168
2169 install_codex_hooks(tmp.path()).unwrap();
2170
2171 let v: serde_json::Value =
2172 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2173 .unwrap();
2174 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2176 .as_array()
2177 .unwrap()
2178 .iter()
2179 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2180 .collect();
2181 assert!(
2182 post_cmds.contains(&"my-own"),
2183 "user PostToolUse hook preserved"
2184 );
2185 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2186 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2188 .as_array()
2189 .unwrap()
2190 .iter()
2191 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2192 .collect();
2193 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2194 }
2195
2196 const FOREIGN_SETTINGS: &str = r#"{
2200 "permissions": { "allow": ["Bash(ls)"] },
2201 "hooks": {
2202 "PreToolUse": [
2203 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2204 { "matcher": "Write|Edit", "hooks": [
2205 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2206 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2207 ] }
2208 ],
2209 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2210 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2211 },
2212 "model": "opus"
2213}"#;
2214
2215 fn expected_foreign_entries() -> Vec<String> {
2219 [
2220 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2221 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2222 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2223 ]
2224 .map(String::from)
2225 .to_vec()
2226 }
2227
2228 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2229 entry["hooks"]
2230 .as_array()
2231 .unwrap()
2232 .iter()
2233 .any(is_tracevault_hook)
2234 }
2235
2236 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2237 let v: serde_json::Value =
2238 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2239 assert_eq!(
2240 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2241 ["permissions", "hooks", "model"],
2242 "top-level keys kept, in their order"
2243 );
2244 assert_eq!(
2245 v["permissions"],
2246 serde_json::json!({ "allow": ["Bash(ls)"] })
2247 );
2248 let hooks = v["hooks"].as_object().unwrap();
2249 let foreign: Vec<String> = hooks
2250 .values()
2251 .flat_map(|entries| entries.as_array().unwrap())
2252 .filter(|e| !holds_tracevault_hook(e))
2253 .map(|e| e.to_string())
2254 .collect();
2255 assert_eq!(foreign, expected_foreign_entries());
2256 let ours = ours.as_object().unwrap();
2257 for (event, entries) in hooks {
2258 let mine: Vec<&serde_json::Value> = entries
2259 .as_array()
2260 .unwrap()
2261 .iter()
2262 .filter(|e| holds_tracevault_hook(e))
2263 .collect();
2264 let want: Vec<&serde_json::Value> = ours
2265 .get(event)
2266 .map(|o| o.as_array().unwrap().iter().collect())
2267 .unwrap_or_default();
2268 assert_eq!(mine, want, "TraceVault entries under {event}");
2269 }
2270 for event in ours.keys() {
2271 assert!(hooks.contains_key(event), "missing {event}");
2272 }
2273 }
2274
2275 #[test]
2276 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2277 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2278 let tmp = tempfile::tempdir().unwrap();
2279 let path = tmp.path().join(".claude").join(target.filename());
2280 fs::create_dir_all(path.parent().unwrap()).unwrap();
2281 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2282
2283 install_claude_hooks(tmp.path(), target).unwrap();
2284 assert_installed_over_foreign(&path, &tracevault_hooks());
2285
2286 let after_first = fs::read(&path).unwrap();
2288 install_claude_hooks(tmp.path(), target).unwrap();
2289 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2290 }
2291 }
2292
2293 #[test]
2294 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2295 let tmp = tempfile::tempdir().unwrap();
2296 let claude_dir = tmp.path().join(".claude");
2297 fs::create_dir_all(&claude_dir).unwrap();
2298 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2299
2300 install_global_hooks(&claude_dir).unwrap();
2301 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2302 }
2303
2304 #[test]
2305 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2306 for global in [false, true] {
2307 let tmp = tempfile::tempdir().unwrap();
2308 let codex_dir = tmp.path().join(".codex");
2309 fs::create_dir_all(&codex_dir).unwrap();
2310 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2311
2312 if global {
2313 install_global_codex_hooks(&codex_dir).unwrap();
2314 } else {
2315 install_codex_hooks(tmp.path()).unwrap();
2316 }
2317 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2318 }
2319 }
2320
2321 #[test]
2322 fn up_to_date_hook_file_is_not_rewritten() {
2323 let tmp = tempfile::tempdir().unwrap();
2325 let path = tmp.path().join(".claude/settings.json");
2326 fs::create_dir_all(path.parent().unwrap()).unwrap();
2327 let mut body = Vec::new();
2328 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
2329 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2330 serde::Serialize::serialize(
2331 &serde_json::json!({ "hooks": tracevault_hooks() }),
2332 &mut ser,
2333 )
2334 .unwrap();
2335 fs::write(&path, &body).unwrap();
2336
2337 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2338 assert_eq!(fs::read(&path).unwrap(), body);
2339 }
2340
2341 #[test]
2342 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2343 for (target, body) in [
2344 (ClaudeSettingsTarget::Shared, "{ not json"),
2345 (ClaudeSettingsTarget::Local, "[1, 2]"),
2346 (ClaudeSettingsTarget::Shared, "null"),
2347 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2348 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2349 ] {
2350 let tmp = tempfile::tempdir().unwrap();
2351 let path = tmp.path().join(".claude").join(target.filename());
2352 fs::create_dir_all(path.parent().unwrap()).unwrap();
2353 fs::write(&path, body).unwrap();
2354
2355 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2356 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2357 assert_eq!(
2358 fs::read_to_string(&path).unwrap(),
2359 body,
2360 "file must be untouched"
2361 );
2362 assert_eq!(
2363 fs::read_dir(path.parent().unwrap()).unwrap().count(),
2364 1,
2365 "no temp file left behind"
2366 );
2367 }
2368 }
2369
2370 #[test]
2371 fn concurrent_installs_never_publish_a_partial_file() {
2372 let tmp = tempfile::tempdir().unwrap();
2378 let path = tmp.path().join("settings.json");
2379 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2380 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2381 let reader = {
2382 let (path, done) = (path.clone(), done.clone());
2383 std::thread::spawn(move || {
2384 while !done.load(std::sync::atomic::Ordering::Relaxed) {
2385 let body = fs::read_to_string(&path).unwrap();
2386 serde_json::from_str::<serde_json::Value>(&body).unwrap();
2387 }
2388 })
2389 };
2390 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2391 .into_iter()
2392 .map(|ours| {
2393 let path = path.clone();
2394 std::thread::spawn(move || {
2395 for _ in 0..200 {
2396 if let Err(e) = merge_hooks_into_file(&path, &ours) {
2397 assert!(e.to_string().contains("kept changing"), "{e}");
2398 }
2399 }
2400 })
2401 })
2402 .collect();
2403 for writer in writers {
2404 writer.join().unwrap();
2405 }
2406 done.store(true, std::sync::atomic::Ordering::Relaxed);
2407 reader.join().unwrap();
2408 let v: serde_json::Value =
2409 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2410 assert_eq!(v["model"], "opus");
2411 assert_eq!(
2412 fs::read_dir(tmp.path()).unwrap().count(),
2413 1,
2414 "no temp file left"
2415 );
2416 }
2417
2418 #[cfg(unix)]
2419 #[test]
2420 fn install_claude_hooks_keeps_file_permissions() {
2421 use std::os::unix::fs::PermissionsExt;
2422 let tmp = tempfile::tempdir().unwrap();
2423 let path = tmp.path().join(".claude/settings.local.json");
2424 fs::create_dir_all(path.parent().unwrap()).unwrap();
2425 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2426 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2427
2428 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2429
2430 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2431 assert_eq!(mode, 0o600);
2432 assert_installed_over_foreign(&path, &tracevault_hooks());
2433 }
2434
2435 #[cfg(unix)]
2436 #[test]
2437 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2438 let tmp = tempfile::tempdir().unwrap();
2439 let central = tmp.path().join("central/claude-settings.json");
2440 fs::create_dir_all(central.parent().unwrap()).unwrap();
2441 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
2442 let link = tmp.path().join("repo/.claude/settings.json");
2443 fs::create_dir_all(link.parent().unwrap()).unwrap();
2444 std::os::unix::fs::symlink(¢ral, &link).unwrap();
2445
2446 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2447
2448 assert!(fs::symlink_metadata(&link)
2449 .unwrap()
2450 .file_type()
2451 .is_symlink());
2452 assert_installed_over_foreign(¢ral, &tracevault_hooks());
2453 }
2454
2455 #[cfg(unix)]
2456 #[test]
2457 fn install_claude_hooks_refuses_dangling_symlink() {
2458 let tmp = tempfile::tempdir().unwrap();
2459 let link = tmp.path().join(".claude/settings.json");
2460 fs::create_dir_all(link.parent().unwrap()).unwrap();
2461 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2462
2463 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2464 assert!(fs::symlink_metadata(&link)
2465 .unwrap()
2466 .file_type()
2467 .is_symlink());
2468 assert!(!tmp.path().join("gone.json").exists());
2469 }
2470
2471 #[test]
2472 fn validate_init_flags_rejects_claude_settings_with_codex() {
2473 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2474 }
2475
2476 #[test]
2477 fn validate_init_flags_allows_codex_without_claude_settings() {
2478 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2479 }
2480
2481 #[test]
2482 fn validate_init_flags_allows_claude_with_claude_settings() {
2483 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2484 }
2485
2486 #[test]
2487 fn merge_hooks_into_file_rejects_parent_dir() {
2488 let tmp = tempfile::tempdir().unwrap();
2489 let bad = tmp.path().join("..").join("hooks.json");
2490 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2491 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2492 }
2493
2494 #[test]
2495 fn append_workspace_md_rejects_parent_dir() {
2496 let tmp = tempfile::tempdir().unwrap();
2497 let bad = tmp.path().join("..").join("AGENTS.md");
2498 let err = append_workspace_md(&bad).unwrap_err();
2499 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2500 }
2501
2502 #[tokio::test]
2503 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2504 let tmp = tempfile::tempdir().unwrap();
2505 let root = tmp.path();
2506 crate::test_helpers::init_git_repo(root);
2507 fs::create_dir_all(root.join(".tracevault")).unwrap();
2510 fs::write(
2511 root.join(".tracevault/config.toml"),
2512 "api_key = \"tvk_test\"\n",
2513 )
2514 .unwrap();
2515
2516 let entry = init_in_directory(
2517 root,
2518 None,
2519 None,
2520 false,
2521 Some(crate::config::UserContext::Toggle(false)),
2522 crate::agent::Agent::Codex,
2523 )
2524 .await
2525 .unwrap();
2526
2527 assert!(root.join(".codex").join("hooks.json").exists());
2529 assert!(!root.join(".claude").join("settings.json").exists());
2530 assert_eq!(entry, ".codex/hooks.json");
2531
2532 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2534 assert!(gi.contains(".codex/hooks.json"));
2535 assert!(gi.contains(".tracevault/"));
2536 }
2537
2538 #[tokio::test]
2550 async fn init_in_directory_registers_repo_and_persists_repo_id() {
2551 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2552 let tmp = tempfile::tempdir().unwrap();
2553 let root = tmp.path();
2554 crate::test_helpers::init_git_repo(root);
2555 add_origin_remote(root, "git@github.com:org/repo.git");
2556
2557 let repo_id = "11111111-1111-4111-8111-111111111111";
2558 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2559 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2562 http_response("404 Not Found", NO_REMOTE),
2563 http_response("200 OK", &body),
2564 ]);
2565
2566 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2567 _guard.set("XDG_CONFIG_HOME", tmp.path());
2568 _guard.set("TRACEVAULT_API_KEY", "tok");
2569 _guard.remove("TRACEVAULT_SERVER_URL");
2570
2571 init_in_directory(
2572 root,
2573 Some(&base),
2574 None,
2575 true,
2576 Some(crate::config::UserContext::Toggle(false)),
2577 crate::agent::Agent::Codex,
2578 )
2579 .await
2580 .unwrap();
2581
2582 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2583 assert_eq!(
2584 cfg.repo_id,
2585 Some(repo_id.to_string()),
2586 "successful registration must persist repo_id to config.toml"
2587 );
2588 }
2589
2590 #[tokio::test]
2596 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2597 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2598 let tmp = tempfile::tempdir().unwrap();
2599 let root = tmp.path();
2600 crate::test_helpers::init_git_repo(root);
2601 add_origin_remote(root, "git@github.com:org/repo.git");
2602
2603 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2604 http_response("404 Not Found", NO_REMOTE),
2605 http_response("403 Forbidden", ""),
2606 ]);
2607
2608 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2609 _guard.set("XDG_CONFIG_HOME", tmp.path());
2610 _guard.set("TRACEVAULT_API_KEY", "tok");
2611 _guard.remove("TRACEVAULT_SERVER_URL");
2612
2613 let entry = init_in_directory(
2614 root,
2615 Some(&base),
2616 None,
2617 true,
2618 Some(crate::config::UserContext::Toggle(false)),
2619 crate::agent::Agent::Codex,
2620 )
2621 .await
2622 .expect("a registration failure (403) must not abort init itself");
2623 assert_eq!(entry, ".codex/hooks.json");
2624
2625 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2626 assert!(
2627 cfg.repo_id.is_none(),
2628 "a 403 registration failure must not persist a repo_id"
2629 );
2630 }
2631
2632 #[tokio::test]
2637 async fn registration_failure_message_flags_403_as_not_authorized() {
2638 let base = spawn_once(http_response("403 Forbidden", ""));
2639 let client = ApiClient::new(&base, Some("tok"));
2640 let err = client
2641 .register_repo(crate::api_client::RegisterRepoRequest {
2642 repo_name: "repo".into(),
2643 github_url: Some("git@github.com:org/repo.git".into()),
2644 })
2645 .await
2646 .unwrap_err();
2647 let msg = registration_failure_message(err.as_ref());
2648 assert!(
2649 msg.contains("not authorized"),
2650 "403 registration failure must surface a not-authorized message; got: {msg}"
2651 );
2652 }
2653
2654 #[tokio::test]
2657 async fn registration_failure_message_generic_for_non_403() {
2658 let base = spawn_once(http_response("500 Internal Server Error", ""));
2659 let client = ApiClient::new(&base, Some("tok"));
2660 let err = client
2661 .register_repo(crate::api_client::RegisterRepoRequest {
2662 repo_name: "repo".into(),
2663 github_url: Some("git@github.com:org/repo.git".into()),
2664 })
2665 .await
2666 .unwrap_err();
2667 let msg = registration_failure_message(err.as_ref());
2668 assert!(
2669 msg.contains("could not register repo on server"),
2670 "got: {msg}"
2671 );
2672 assert!(!msg.contains("not authorized"), "got: {msg}");
2673 }
2674
2675 #[tokio::test]
2680 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2681 let base = spawn_once(http_response(
2682 "500 Internal Server Error",
2683 "upstream error 403 from proxy",
2684 ));
2685 let client = ApiClient::new(&base, Some("tok"));
2686 let err = client
2687 .register_repo(crate::api_client::RegisterRepoRequest {
2688 repo_name: "repo".into(),
2689 github_url: Some("git@github.com:org/repo.git".into()),
2690 })
2691 .await
2692 .unwrap_err();
2693 let msg = registration_failure_message(err.as_ref());
2694 assert!(
2695 !msg.contains("not authorized"),
2696 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2697 );
2698 assert!(
2699 msg.contains("could not register repo on server"),
2700 "got: {msg}"
2701 );
2702 }
2703
2704 #[tokio::test]
2708 async fn registration_failure_message_flags_404_as_version_mismatch() {
2709 let base = spawn_once(http_response("404 Not Found", ""));
2710 let client = ApiClient::new(&base, Some("tok"));
2711 let err = client
2712 .register_repo(crate::api_client::RegisterRepoRequest {
2713 repo_name: "repo".into(),
2714 github_url: Some("git@github.com:org/repo.git".into()),
2715 })
2716 .await
2717 .unwrap_err();
2718 let msg = registration_failure_message(err.as_ref());
2719 assert!(
2720 msg.to_lowercase().contains("version mismatch"),
2721 "a 404 registration failure should hint at a version mismatch; got: {msg}"
2722 );
2723 }
2724
2725 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2729 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2730 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2731 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2732
2733 fn resolve_remote_ok() -> String {
2734 http_response(
2735 "200 OK",
2736 &format!(
2737 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2738 ),
2739 )
2740 }
2741
2742 fn remote_detail(repos: &[(&str, &str)]) -> String {
2743 let repos: Vec<String> = repos
2744 .iter()
2745 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2746 .collect();
2747 http_response(
2748 "200 OK",
2749 &format!(
2750 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2751 repos.join(",")
2752 ),
2753 )
2754 }
2755
2756 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2759 let (base, rx) = crate::test_helpers::spawn_seq(responses);
2760 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2761 _guard.set("XDG_CONFIG_HOME", root);
2762 _guard.set("TRACEVAULT_API_KEY", "tok");
2763 _guard.remove("TRACEVAULT_SERVER_URL");
2764
2765 init_in_directory(
2766 root,
2767 Some(&base),
2768 None,
2769 true,
2770 Some(crate::config::UserContext::Toggle(false)),
2771 crate::agent::Agent::Codex,
2772 )
2773 .await
2774 .expect("init succeeds");
2775
2776 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2777 (cfg.repo_id, rx.try_iter().collect())
2778 }
2779
2780 fn registered(requests: &[String]) -> bool {
2781 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2782 }
2783
2784 #[tokio::test]
2787 async fn init_binds_the_existing_repo_of_a_known_remote() {
2788 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2789 let tmp = tempfile::tempdir().unwrap();
2790 crate::test_helpers::init_git_repo(tmp.path());
2791 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2792
2793 let (repo_id, requests) = init_against(
2794 tmp.path(),
2795 vec![
2796 resolve_remote_ok(),
2797 remote_detail(&[(CANONICAL, "tracevault")]),
2798 ],
2799 )
2800 .await;
2801
2802 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2803 assert!(!registered(&requests), "requests: {requests:?}");
2804 }
2805
2806 #[tokio::test]
2809 async fn init_binds_the_record_named_like_the_checkout() {
2810 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2811 let tmp = tempfile::tempdir().unwrap();
2812 crate::test_helpers::init_git_repo(tmp.path());
2813 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2814 let dir_name = crate::resolution::git_repo_name(tmp.path());
2815
2816 let (repo_id, requests) = init_against(
2817 tmp.path(),
2818 vec![
2819 resolve_remote_ok(),
2820 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2821 ],
2822 )
2823 .await;
2824
2825 assert_eq!(repo_id.as_deref(), Some(STRAY));
2826 assert!(!registered(&requests));
2827 }
2828
2829 #[tokio::test]
2831 async fn init_rerun_keeps_the_previously_bound_repo() {
2832 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2833 let tmp = tempfile::tempdir().unwrap();
2834 crate::test_helpers::init_git_repo(tmp.path());
2835 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2836 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2837 fs::write(
2838 tmp.path().join(".tracevault/config.toml"),
2839 format!("repo_id = \"{STRAY}\"\n"),
2840 )
2841 .unwrap();
2842
2843 let (repo_id, requests) = init_against(
2844 tmp.path(),
2845 vec![
2846 resolve_remote_ok(),
2847 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2848 ],
2849 )
2850 .await;
2851
2852 assert_eq!(repo_id.as_deref(), Some(STRAY));
2853 assert!(!registered(&requests));
2854 }
2855
2856 #[tokio::test]
2859 async fn init_binding_keeps_the_rest_of_the_config() {
2860 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2861 let tmp = tempfile::tempdir().unwrap();
2862 crate::test_helpers::init_git_repo(tmp.path());
2863 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2864 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2865 fs::write(
2866 tmp.path().join(".tracevault/config.toml"),
2867 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
2868 )
2869 .unwrap();
2870
2871 let (repo_id, _) = init_against(
2872 tmp.path(),
2873 vec![
2874 resolve_remote_ok(),
2875 remote_detail(&[(CANONICAL, "tracevault")]),
2876 ],
2877 )
2878 .await;
2879
2880 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2881 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
2882 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
2883 assert_eq!(cfg.default_project.as_deref(), Some("payments"));
2884 }
2885
2886 #[tokio::test]
2889 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
2890 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2891 let tmp = tempfile::tempdir().unwrap();
2892 crate::test_helpers::init_git_repo(tmp.path());
2893 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2894 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2895 fs::write(
2896 tmp.path().join(".tracevault/config.toml"),
2897 format!("repo_id = \"{STRAY}\"\n"),
2898 )
2899 .unwrap();
2900
2901 let (repo_id, requests) = init_against(
2902 tmp.path(),
2903 vec![http_response("500 Internal Server Error", "{}")],
2904 )
2905 .await;
2906
2907 assert_eq!(repo_id.as_deref(), Some(STRAY));
2908 assert!(!registered(&requests));
2909 }
2910
2911 #[tokio::test]
2913 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2914 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2915 let tmp = tempfile::tempdir().unwrap();
2916 crate::test_helpers::init_git_repo(tmp.path());
2917 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2918
2919 let (repo_id, requests) = init_against(
2920 tmp.path(),
2921 vec![
2922 resolve_remote_ok(),
2923 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2924 ],
2925 )
2926 .await;
2927
2928 assert_eq!(repo_id, None);
2929 assert!(!registered(&requests));
2930 }
2931
2932 #[tokio::test]
2935 async fn init_registers_for_a_codebase_without_live_repos() {
2936 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2937 let tmp = tempfile::tempdir().unwrap();
2938 crate::test_helpers::init_git_repo(tmp.path());
2939 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2940
2941 let (repo_id, requests) = init_against(
2942 tmp.path(),
2943 vec![
2944 resolve_remote_ok(),
2945 remote_detail(&[]),
2946 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2947 ],
2948 )
2949 .await;
2950
2951 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2952 assert!(registered(&requests));
2953 }
2954
2955 #[tokio::test]
2957 async fn init_does_not_register_when_the_remote_check_fails() {
2958 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2959 let tmp = tempfile::tempdir().unwrap();
2960 crate::test_helpers::init_git_repo(tmp.path());
2961 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2962
2963 let (repo_id, requests) = init_against(
2964 tmp.path(),
2965 vec![http_response("500 Internal Server Error", "{}")],
2966 )
2967 .await;
2968
2969 assert_eq!(repo_id, None);
2970 assert!(!registered(&requests));
2971 }
2972}