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};
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(
117 project_root: &Path,
118 server_url: Option<&str>,
119 claude_settings: Option<ClaudeSettingsTarget>,
120 no_gitignore: bool,
121 user_context: UserContext,
122 agent: crate::agent::Agent,
123) -> Result<String, io::Error> {
124 if !project_root.join(".git").exists() {
126 return Err(io::Error::new(
127 io::ErrorKind::NotFound,
128 "Not a git repository. Run 'git init' first.",
129 ));
130 }
131
132 if let Some(primary) = linked_worktree_primary(project_root) {
138 return Err(io::Error::new(
139 io::ErrorKind::Unsupported,
140 format!(
141 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
142 cd there and run it again — all worktrees share the primary's .tracevault/.",
143 primary.display()
144 ),
145 ));
146 }
147
148 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
151 {
152 crate::agent::Agent::ClaudeCode => {
153 let target = resolve_claude_target(claude_settings)?;
154 (Some(target), target.gitignore_entry().to_string())
155 }
156 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
157 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
163 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
168 };
169
170 let config_dir = TracevaultConfig::config_dir(project_root);
172 fs::create_dir_all(&config_dir)?;
173 fs::create_dir_all(config_dir.join("sessions"))?;
174 fs::create_dir_all(config_dir.join("cache"))?;
175 TracevaultConfig::ensure_gitignore(&config_dir)?;
178
179 if !no_gitignore {
181 update_root_gitignore(project_root, &hook_gitignore_entry)?;
182 }
183
184 let remote_url = git_remote_url(project_root);
186 if remote_url.is_none() {
187 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
188 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
189 }
190
191 let mut config = TracevaultConfig::default();
193 if let Some(url) = server_url {
194 config.server_url = Some(url.to_string());
195 }
196 config.user_context = Some(user_context);
197 fs::write(
198 TracevaultConfig::config_path(project_root),
199 config.to_toml(),
200 )?;
201
202 match agent {
204 crate::agent::Agent::ClaudeCode => {
205 let target =
207 claude_target.expect("claude settings target is resolved for the Claude agent");
208 install_claude_hooks(project_root, target)?;
209 }
210 crate::agent::Agent::Codex => {
211 install_codex_hooks(project_root)?;
212 println!("{}", codex_hook_trust_notice());
213 }
214 crate::agent::Agent::Gsd => {
215 install_gsd_extension(Some(project_root))?;
223 }
224 crate::agent::Agent::OpenCode => {
225 install_opencode_plugin(Some(project_root))?;
226 }
227 }
228
229 install_git_hook(project_root)?;
231 install_post_commit_hook(project_root)?;
232
233 let detected = crate::hooks::detect_tools(project_root);
235 for tool in &detected {
236 println!(" Detected: {}", tool.name());
237 }
238
239 let (resolved_url, resolved_credential) =
244 crate::credentials::resolve_credentials_quiet(project_root)
245 .map_err(|e| io::Error::other(e.to_string()))?;
246 let effective_url = server_url.map(String::from).or(resolved_url);
247
248 if resolved_credential.is_none() {
249 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
250 } else if let (Some(url), Some(remote)) = (effective_url, remote_url) {
251 let client = ApiClient::with_credential(&url, resolved_credential);
252 let repo_name = git_repo_name(project_root);
253 let origin_url = remote.clone();
256
257 match client
258 .register_repo(crate::api_client::RegisterRepoRequest {
259 repo_name,
260 github_url: Some(remote),
261 })
262 .await
263 {
264 Ok(resp) => {
265 println!("Repo registered on server (id: {})", resp.repo_id);
266 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
268 cfg.repo_id = Some(resp.repo_id.to_string());
269 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
275 println!(
276 "{}",
277 crate::resolution::codebase_line(
278 remote.name.as_deref(),
279 &remote.normalized_url,
280 &remote.clone_status
281 )
282 );
283 cfg.remote_id = Some(remote.remote_id.to_string());
284 cfg.codebase_name = remote.name.clone();
285 }
286 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
287 }
288 }
289 Err(e) => {
290 eprintln!("{}", registration_failure_message(e.as_ref()));
291 }
292 }
293 }
294
295 Ok(hook_gitignore_entry)
296}
297
298fn registration_failure_message(err: &dyn std::error::Error) -> String {
313 let msg = err.to_string();
314 if msg.starts_with("Server returned 403 ") {
315 "Warning: you are not authorized to register this repo.".to_string()
316 } else if msg.starts_with("Server returned 404 ") {
317 "Warning: could not register repo on server (404) — this endpoint may not exist on \
318 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
319 once the server is upgraded."
320 .to_string()
321 } else {
322 format!("Warning: could not register repo on server: {err}")
323 }
324}
325
326fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
327 let path = project_root.join(".gitignore");
328 let existing = if path.exists() {
329 fs::read_to_string(&path)?
330 } else {
331 String::new()
332 };
333
334 let needed: Vec<&str> = [".tracevault/", settings_entry]
340 .iter()
341 .copied()
342 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
343 .collect();
344
345 if needed.is_empty() {
346 return Ok(());
347 }
348
349 let mut content = existing;
350 if !content.is_empty() && !content.ends_with('\n') {
351 content.push('\n');
352 }
353 content.push_str("\n# TraceVault — local only, do not commit\n");
354 for entry in needed {
355 content.push_str(entry);
356 content.push('\n');
357 }
358
359 fs::write(path, content)
360}
361
362const HOOK_MARKER: &str = "# tracevault:enforce";
363const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
364
365fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
366 let hooks_dir = project_root.join(".git/hooks");
367 fs::create_dir_all(&hooks_dir)?;
368
369 let hook_path = hooks_dir.join("pre-push");
370 let tracevault_block = format!(
377 "{HOOK_MARKER}\n\
378 # Capture git's pre-push ref list once; `check` uses it to determine\n\
379 # which files are being pushed.\n\
380 tracevault_prepush_stdin=$(cat)\n\
381 tracevault sync 2>/dev/null || true\n\
382 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
383 );
384
385 if hook_path.exists() {
386 let existing = fs::read_to_string(&hook_path)?;
387
388 if existing.contains(HOOK_MARKER) {
390 return Ok(());
391 }
392
393 if existing.contains(OLD_HOOK_MARKER) {
395 let mut new_content = String::new();
396 let mut skip = false;
397 for line in existing.lines() {
398 if line.contains(OLD_HOOK_MARKER) {
399 skip = true;
400 continue;
401 }
402 if skip {
403 if line.starts_with("tracevault ") {
405 continue;
406 }
407 skip = false;
408 }
409 new_content.push_str(line);
410 new_content.push('\n');
411 }
412 if !new_content.ends_with('\n') {
413 new_content.push('\n');
414 }
415 new_content.push_str(&tracevault_block);
416 fs::write(&hook_path, new_content)?;
417 } else {
418 let mut content = existing;
420 if !content.ends_with('\n') {
421 content.push('\n');
422 }
423 content.push_str(&tracevault_block);
424 fs::write(&hook_path, content)?;
425 }
426 } else {
427 let content = format!("#!/bin/sh\n{tracevault_block}");
428 fs::write(&hook_path, content)?;
429 }
430
431 #[cfg(unix)]
433 {
434 use std::os::unix::fs::PermissionsExt;
435 let mut perms = fs::metadata(&hook_path)?.permissions();
436 perms.set_mode(0o755);
437 fs::set_permissions(&hook_path, perms)?;
438 }
439
440 Ok(())
441}
442
443const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
444
445fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
446 let hooks_dir = project_root.join(".git/hooks");
447 fs::create_dir_all(&hooks_dir)?;
448
449 let hook_path = hooks_dir.join("post-commit");
450 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
451
452 if hook_path.exists() {
453 let existing = fs::read_to_string(&hook_path)?;
454
455 if existing.contains(POST_COMMIT_MARKER) {
456 return Ok(());
457 }
458
459 let mut content = existing;
460 if !content.ends_with('\n') {
461 content.push('\n');
462 }
463 content.push_str(&tracevault_block);
464 fs::write(&hook_path, content)?;
465 } else {
466 let content = format!("#!/bin/sh\n{tracevault_block}");
467 fs::write(&hook_path, content)?;
468 }
469
470 #[cfg(unix)]
471 {
472 use std::os::unix::fs::PermissionsExt;
473 let mut perms = fs::metadata(&hook_path)?.permissions();
474 perms.set_mode(0o755);
475 fs::set_permissions(&hook_path, perms)?;
476 }
477
478 Ok(())
479}
480
481fn install_claude_hooks(
482 project_root: &Path,
483 target: ClaudeSettingsTarget,
484) -> Result<(), io::Error> {
485 let claude_dir = project_root.join(".claude");
486 fs::create_dir_all(&claude_dir)?;
487
488 let filename = target.filename();
489 let settings_path = claude_dir.join(filename);
490 let mut settings: serde_json::Value = if settings_path.exists() {
491 let content = fs::read_to_string(&settings_path)?;
492 serde_json::from_str(&content).map_err(|e| {
493 io::Error::new(
494 io::ErrorKind::InvalidData,
495 format!("Failed to parse .claude/{filename}: {e}"),
496 )
497 })?
498 } else {
499 serde_json::json!({})
500 };
501
502 let hooks = tracevault_hooks();
503
504 let settings_obj = settings.as_object_mut().ok_or_else(|| {
506 io::Error::new(
507 io::ErrorKind::InvalidData,
508 format!(".claude/{filename} is not a JSON object"),
509 )
510 })?;
511
512 settings_obj.insert("hooks".to_string(), hooks);
513
514 let formatted = serde_json::to_string_pretty(&settings)
515 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
516 fs::write(&settings_path, formatted)?;
517
518 Ok(())
519}
520
521pub fn tracevault_hooks() -> serde_json::Value {
522 serde_json::json!({
523 "PreToolUse": [{
524 "matcher": "Write|Edit|Bash",
525 "hooks": [{
526 "type": "command",
527 "command": "tracevault stream --event pre-tool-use",
528 "timeout": 10,
529 "statusMessage": "TraceVault: streaming pre-tool event"
530 }]
531 }],
532 "PostToolUse": [{
533 "matcher": "",
534 "hooks": [{
535 "type": "command",
536 "command": "tracevault stream --event post-tool-use",
537 "timeout": 10,
538 "statusMessage": "TraceVault: streaming post-tool event"
539 }]
540 }],
541 "Notification": [{
542 "matcher": "",
543 "hooks": [{
544 "type": "command",
545 "command": "tracevault stream --event notification",
546 "timeout": 10,
547 "statusMessage": "TraceVault: streaming notification"
548 }]
549 }],
550 "Stop": [{
551 "matcher": "",
552 "hooks": [{
553 "type": "command",
554 "command": "tracevault stream --event stop",
555 "timeout": 10,
556 "statusMessage": "TraceVault: finalizing session"
557 }]
558 }],
559 "SessionStart": [{
560 "matcher": "",
561 "hooks": [{
562 "type": "command",
563 "command": "tracevault session-start",
564 "timeout": 10,
565 "statusMessage": "TraceVault: session start"
566 }]
567 }],
568 "UserPromptSubmit": [{
569 "matcher": "",
570 "hooks": [{
571 "type": "command",
572 "command": "tracevault user-prompt",
573 "timeout": 10,
574 "statusMessage": "TraceVault: policy reinforcement"
575 }]
576 }]
577 })
578}
579
580pub fn codex_hook_trust_notice() -> &'static str {
590 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
591 silently and no session is captured. Run `codex` once interactively in a repo and \
592 approve the hook-trust prompt; unattended runs (CI) can pass \
593 `--dangerously-bypass-hook-trust` instead."
594}
595
596pub fn codex_hooks() -> serde_json::Value {
606 serde_json::json!({
607 "SessionStart": [{
608 "matcher": "",
609 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
610 }],
611 "UserPromptSubmit": [{
612 "matcher": "",
613 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
614 }],
615 "PostToolUse": [{
616 "matcher": "",
617 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
618 }],
619 "Stop": [{
620 "matcher": "",
621 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
622 }]
623 })
624}
625
626const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
630const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
631const GSD_EXT_MANIFEST_JSON: &str =
632 include_str!("../../assets/gsd-extension/extension-manifest.json");
633
634fn gsd_extension_source_dir() -> io::Result<PathBuf> {
638 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
639 let config_dir = config_dir
640 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
641 Ok(config_dir.join("tracevault").join("gsd-extension"))
642}
643
644pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
668 let home =
669 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
670 let gsd_home = home.join(".gsd");
671
672 let source_dir = gsd_extension_source_dir()?;
673 fs::create_dir_all(&source_dir)?;
674 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
675 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
676 fs::write(
677 source_dir.join("extension-manifest.json"),
678 GSD_EXT_MANIFEST_JSON,
679 )?;
680
681 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
685 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
686 }
687
688 let local_flag = project_root.is_some();
692 let mut cmd = std::process::Command::new("gsd");
693 cmd.arg("install").arg(&source_dir);
694 if let Some(root) = project_root {
695 cmd.arg("-l");
696 cmd.current_dir(root);
697 }
698
699 let retry_hint = format!(
700 "gsd install {}{}",
701 source_dir.display(),
702 if local_flag { " -l" } else { "" }
703 );
704
705 match cmd.output() {
706 Ok(output) if output.status.success() => {
707 println!(
708 "TraceVault: installed and registered the GSD extension ({}).",
709 source_dir.display()
710 );
711 }
712 Ok(output) => {
713 eprintln!(
714 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
715 source_dir.display(),
716 String::from_utf8_lossy(&output.stderr),
717 );
718 }
719 Err(e) => {
720 eprintln!(
721 "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.",
722 source_dir.display(),
723 );
724 }
725 }
726
727 Ok(())
728}
729
730const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
733
734pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
750 let plugins_dir = match project_root {
751 Some(root) => root.join(".opencode").join("plugins"),
752 None => {
753 let config_dir =
754 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
755 config_dir
756 .ok_or_else(|| {
757 io::Error::new(
758 io::ErrorKind::NotFound,
759 "could not determine the config directory for the OpenCode plugin install",
760 )
761 })?
762 .join("opencode")
763 .join("plugins")
764 }
765 };
766
767 write_opencode_plugin_files(&plugins_dir)
768}
769
770fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
771 fs::create_dir_all(plugins_dir)?;
772 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
773 Ok(())
774}
775
776pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
788 let ext_root = gsd_home.join("extensions");
789 let reg_path = ext_root.join("registry.json");
790
791 let reg: Option<serde_json::Value> = if reg_path.exists() {
796 let content = fs::read_to_string(®_path)?;
797 let parsed: serde_json::Value = match serde_json::from_str(&content) {
798 Ok(v) => v,
799 Err(_) => return Ok(()), };
801 let corrupt = match parsed.as_object() {
802 None => true,
803 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
804 };
805 if corrupt {
806 return Ok(()); }
808 Some(parsed)
809 } else {
810 None
811 };
812
813 let stale = ext_root.join("tracevault-tracker");
815 if stale.exists() {
816 fs::remove_dir_all(&stale)?;
817 }
818
819 if let Some(mut reg) = reg {
821 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
822 let removed_tracker = entries.remove("tracevault-tracker").is_some();
823 let removed_inert = entries.remove("tracevault").is_some();
824 if removed_tracker || removed_inert {
825 let tmp = reg_path.with_extension("json.tmp");
827 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
828 fs::rename(&tmp, ®_path)?;
829 }
830 }
831 }
832 Ok(())
833}
834
835fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
845 if hooks_path
850 .components()
851 .any(|c| c == std::path::Component::ParentDir)
852 {
853 return Err(io::Error::new(
854 io::ErrorKind::InvalidInput,
855 format!("refusing to use path with '..': {}", hooks_path.display()),
856 ));
857 }
858 let mut root: serde_json::Value = if hooks_path.exists() {
859 let content = fs::read_to_string(hooks_path)?;
860 serde_json::from_str(&content).map_err(|e| {
861 io::Error::new(
862 io::ErrorKind::InvalidData,
863 format!("Failed to parse {}: {e}", hooks_path.display()),
864 )
865 })?
866 } else {
867 serde_json::json!({})
868 };
869
870 merge_hooks(&mut root, ours, hooks_path)?;
871
872 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
873 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
874 })?;
875 let tmp = hooks_path.with_extension("json.tmp");
876 fs::write(&tmp, formatted)?;
877 fs::rename(&tmp, hooks_path)?;
878 Ok(())
879}
880
881pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
885 let codex_dir = project_root.join(".codex");
886 fs::create_dir_all(&codex_dir)?;
887 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
888}
889
890pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
897 fs::create_dir_all(codex_dir)?;
898 let base = codex_dir.canonicalize()?;
900 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
901 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
902}
903
904const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
908
909const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
910<!-- tracevault:workspace-mode -->
911## TraceVault (workspace mode)
912You may be running detached from any single repository. Before working on a repo, run
913`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
914output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
915already be registered with TraceVault.
916";
917
918fn append_workspace_md(md_path: &Path) -> io::Result<()> {
924 if md_path
926 .components()
927 .any(|c| c == std::path::Component::ParentDir)
928 {
929 return Err(io::Error::new(
930 io::ErrorKind::InvalidInput,
931 format!("refusing to use path with '..': {}", md_path.display()),
932 ));
933 }
934 let existing = if md_path.exists() {
935 fs::read_to_string(md_path)?
936 } else {
937 String::new()
938 };
939 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
940 return Ok(());
941 }
942 let mut content = existing;
943 if !content.is_empty() && !content.ends_with('\n') {
944 content.push('\n');
945 }
946 if !content.is_empty() {
947 content.push('\n');
948 }
949 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
950 fs::write(md_path, content)
951}
952
953fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
957 let joined = base.join(name);
958 if joined.parent() != Some(base) {
959 return Err(io::Error::new(
960 io::ErrorKind::InvalidInput,
961 format!(
962 "refusing to access path outside {}: {}",
963 base.display(),
964 joined.display()
965 ),
966 ));
967 }
968 Ok(joined)
969}
970
971fn merge_hooks(
984 settings: &mut serde_json::Value,
985 ours: &serde_json::Value,
986 path: &Path,
987) -> io::Result<()> {
988 if settings.is_null() {
989 *settings = serde_json::json!({});
990 }
991 let settings_obj = settings.as_object_mut().ok_or_else(|| {
992 io::Error::new(
993 io::ErrorKind::InvalidData,
994 format!("{} is not a JSON object", path.display()),
995 )
996 })?;
997
998 let hooks_value = settings_obj
999 .entry("hooks")
1000 .or_insert_with(|| serde_json::json!({}));
1001 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1002 io::Error::new(
1003 io::ErrorKind::InvalidData,
1004 format!("{} \"hooks\" key is not a JSON object", path.display()),
1005 )
1006 })?;
1007
1008 let Some(ours_obj) = ours.as_object() else {
1009 return Ok(());
1010 };
1011
1012 for (event, our_array) in ours_obj {
1013 let Some(our_entries) = our_array.as_array() else {
1014 continue;
1015 };
1016
1017 let existing_value = hooks_obj
1018 .entry(event.clone())
1019 .or_insert_with(|| serde_json::json!([]));
1020 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1021 io::Error::new(
1022 io::ErrorKind::InvalidData,
1023 format!(
1024 "{} \"hooks\".\"{event}\" is not a JSON array",
1025 path.display()
1026 ),
1027 )
1028 })?;
1029
1030 for our_entry in our_entries {
1031 let our_command = entry_command(our_entry);
1032 let already_present = existing_array
1033 .iter()
1034 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1035 if !already_present {
1036 existing_array.push(our_entry.clone());
1037 }
1038 }
1039 }
1040
1041 Ok(())
1042}
1043
1044fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1047 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1048}
1049
1050fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1055 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1056 return false;
1057 };
1058 hooks
1059 .iter()
1060 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1061}
1062
1063pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1069 fs::create_dir_all(claude_dir)?;
1070
1071 let base = claude_dir.canonicalize()?;
1074
1075 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1077
1078 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1080}
1081
1082pub fn write_global_user_config_in(
1092 config_root: &Path,
1093 requested: Option<UserContext>,
1094) -> io::Result<Option<PathBuf>> {
1095 fs::create_dir_all(config_root)?;
1096 let mut config = crate::config::try_load_user_config_in(config_root)
1098 .ok()
1099 .flatten()
1100 .unwrap_or_default();
1101 let user_context = requested
1103 .or_else(|| config.user_context.clone())
1104 .unwrap_or(UserContext::Toggle(true));
1105 let active = user_context
1106 .resolve()
1107 .map(|_| user_context.path_in(config_root));
1108 config.user_context = Some(user_context);
1109 fs::write(user_config_path_in(config_root), config.to_toml())?;
1110 if let Some(ref ctx_path) = active {
1111 if !ctx_path.exists() {
1112 Context::default().save_to(ctx_path)?;
1113 }
1114 }
1115 Ok(active)
1116}
1117
1118#[cfg(test)]
1119mod tests {
1120 use super::*;
1121 use std::io::{BufRead, BufReader, Write};
1122 use std::net::TcpListener;
1123 use std::thread;
1124
1125 #[test]
1131 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1132 let notice = codex_hook_trust_notice();
1133 assert!(
1134 notice.contains("hook trust"),
1135 "notice must name what is missing: {notice}"
1136 );
1137 assert!(
1138 notice.contains("codex") && notice.contains("approve"),
1139 "notice must tell the user to run codex and approve the prompt: {notice}"
1140 );
1141 assert!(
1142 notice.contains("--dangerously-bypass-hook-trust"),
1143 "notice must name the flag for unattended/CI runs: {notice}"
1144 );
1145 assert!(
1146 notice.contains("silently"),
1147 "notice must say the failure is silent, which is why it needs saying: {notice}"
1148 );
1149 }
1150
1151 fn spawn_once(response: String) -> String {
1154 let response: &'static str = Box::leak(response.into_boxed_str());
1155 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1156 let addr = listener.local_addr().unwrap();
1157 thread::spawn(move || {
1158 if let Ok((stream, _)) = listener.accept() {
1159 let mut reader = BufReader::new(stream);
1160 let mut request_line = String::new();
1161 let _ = reader.read_line(&mut request_line);
1162 let mut stream = reader.into_inner();
1163 let _ = stream.write_all(response.as_bytes());
1164 let _ = stream.flush();
1165 }
1166 });
1167 format!("http://{addr}")
1168 }
1169
1170 fn http_response(status: &str, body: &str) -> String {
1173 format!(
1174 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1175 status,
1176 body.len(),
1177 body
1178 )
1179 }
1180
1181 fn add_origin_remote(dir: &Path, url: &str) {
1182 let ok = std::process::Command::new("git")
1183 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1184 .status()
1185 .expect("git remote add failed")
1186 .success();
1187 assert!(ok, "git remote add must succeed");
1188 }
1189
1190 #[test]
1191 fn linked_worktree_primary_detects_linked_and_primary() {
1192 let tmp = tempfile::tempdir().unwrap();
1193 let repo = tmp.path().join("repo");
1194 let wt = tmp.path().join("linked-wt");
1195 std::fs::create_dir_all(&repo).unwrap();
1196 crate::test_helpers::init_git_repo(&repo);
1197 crate::test_helpers::add_worktree(&repo, &wt);
1198
1199 assert!(
1201 linked_worktree_primary(&repo).is_none(),
1202 "primary checkout must not be flagged as a linked worktree"
1203 );
1204 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1206 assert_eq!(
1207 primary.canonicalize().unwrap(),
1208 repo.canonicalize().unwrap(),
1209 "must resolve to the primary repo root"
1210 );
1211 }
1212
1213 #[test]
1214 fn linked_worktree_primary_none_for_non_git() {
1215 let tmp = tempfile::tempdir().unwrap();
1216 assert!(
1217 linked_worktree_primary(tmp.path()).is_none(),
1218 "a non-git directory is not a linked worktree"
1219 );
1220 }
1221
1222 #[test]
1223 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1224 let mut settings = serde_json::json!({});
1225 let ours = tracevault_hooks();
1226 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1227
1228 let hooks = settings.get("hooks").unwrap();
1229 for event in [
1230 "PreToolUse",
1231 "PostToolUse",
1232 "Notification",
1233 "Stop",
1234 "SessionStart",
1235 "UserPromptSubmit",
1236 ] {
1237 assert!(hooks.get(event).is_some(), "missing event {event}");
1238 }
1239 }
1240
1241 #[test]
1242 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1243 let mut settings = serde_json::json!({
1244 "model": "opus",
1245 "hooks": {
1246 "PreToolUse": [{
1247 "matcher": "",
1248 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1249 }]
1250 }
1251 });
1252 let ours = tracevault_hooks();
1253 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1254
1255 assert_eq!(settings.get("model").unwrap(), "opus");
1257
1258 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1259 assert_eq!(pre_tool_use.len(), 2);
1261 let commands: Vec<&str> = pre_tool_use
1262 .iter()
1263 .map(|e| entry_command(e).unwrap())
1264 .collect();
1265 assert!(commands.contains(&"my-own-hook"));
1266 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1267
1268 assert!(settings["hooks"]["SessionStart"].is_array());
1270 }
1271
1272 #[test]
1273 fn merge_hooks_is_idempotent() {
1274 let mut settings = serde_json::json!({});
1275 let ours = tracevault_hooks();
1276 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1277 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1278
1279 for event in [
1280 "PreToolUse",
1281 "PostToolUse",
1282 "Notification",
1283 "Stop",
1284 "SessionStart",
1285 "UserPromptSubmit",
1286 ] {
1287 let arr = settings["hooks"][event].as_array().unwrap();
1288 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1289 }
1290 }
1291
1292 #[test]
1293 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1294 let mut settings = serde_json::json!({
1298 "hooks": {
1299 "PreToolUse": [{
1300 "matcher": "Write|Edit|Bash",
1301 "hooks": [
1302 { "type": "command", "command": "other" },
1303 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1304 ]
1305 }]
1306 }
1307 });
1308 let ours = tracevault_hooks();
1309 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1310
1311 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1312 assert_eq!(
1313 pre_tool_use.len(),
1314 1,
1315 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1316 );
1317 }
1318
1319 #[test]
1320 fn merge_hooks_errors_on_non_object_top_level() {
1321 let mut settings = serde_json::json!([1, 2, 3]);
1322 let ours = tracevault_hooks();
1323 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1324 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1325 assert!(err.to_string().contains("settings.json"));
1326 }
1327
1328 #[test]
1329 fn merge_hooks_errors_on_non_object_top_level_number() {
1330 let mut settings = serde_json::json!(42);
1331 let ours = tracevault_hooks();
1332 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1333 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1334 }
1335
1336 #[test]
1337 fn merge_hooks_errors_on_non_object_hooks() {
1338 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1339 let ours = tracevault_hooks();
1340 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1341 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1342 assert!(err.to_string().contains("hooks"));
1343 }
1344
1345 #[test]
1346 fn merge_hooks_errors_on_non_array_event_value() {
1347 let mut settings = serde_json::json!({
1348 "hooks": {
1349 "PreToolUse": "not-an-array"
1350 }
1351 });
1352 let ours = tracevault_hooks();
1353 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1354 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1355 assert!(err.to_string().contains("PreToolUse"));
1356 }
1357
1358 #[test]
1359 fn install_global_hooks_writes_settings_and_claude_md() {
1360 let tmp = tempfile::tempdir().unwrap();
1361 let claude_dir = tmp.path().join(".claude");
1362
1363 install_global_hooks(&claude_dir).unwrap();
1364
1365 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1366 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1367 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1368 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1369 }
1370
1371 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1372 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1373 }
1374
1375 #[test]
1376 fn install_global_hooks_is_idempotent() {
1377 let tmp = tempfile::tempdir().unwrap();
1378 let claude_dir = tmp.path().join(".claude");
1379
1380 install_global_hooks(&claude_dir).unwrap();
1381 install_global_hooks(&claude_dir).unwrap();
1382
1383 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1384 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1385 for event in [
1386 "PreToolUse",
1387 "PostToolUse",
1388 "Notification",
1389 "Stop",
1390 "SessionStart",
1391 "UserPromptSubmit",
1392 ] {
1393 let arr = settings["hooks"][event].as_array().unwrap();
1394 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1395 }
1396
1397 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1398 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1399 assert_eq!(
1400 marker_count, 1,
1401 "CLAUDE.md marker should appear exactly once"
1402 );
1403 }
1404
1405 #[test]
1406 fn install_global_hooks_preserves_existing_claude_md_content() {
1407 let tmp = tempfile::tempdir().unwrap();
1408 let claude_dir = tmp.path().join(".claude");
1409 fs::create_dir_all(&claude_dir).unwrap();
1410 fs::write(
1411 claude_dir.join("CLAUDE.md"),
1412 "# My existing notes\nSome content.\n",
1413 )
1414 .unwrap();
1415
1416 install_global_hooks(&claude_dir).unwrap();
1417
1418 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1419 assert!(claude_md.contains("# My existing notes"));
1420 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1421 }
1422
1423 #[test]
1424 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1425 let tmp = tempfile::tempdir().unwrap();
1426 let claude_dir = tmp.path().join(".claude");
1427
1428 install_global_hooks(&claude_dir).unwrap();
1429
1430 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1431 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1432 assert!(settings["hooks"].get("SessionStart").is_some());
1433
1434 let leftover = fs::read_dir(&claude_dir)
1435 .unwrap()
1436 .filter_map(|e| e.ok())
1437 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1438 assert!(
1439 !leftover,
1440 "no settings.json.tmp should remain after install"
1441 );
1442 }
1443
1444 #[test]
1445 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1446 let tmp = tempfile::tempdir().unwrap();
1447 let claude_dir = tmp.path().join(".claude");
1448 fs::create_dir_all(&claude_dir).unwrap();
1449 let settings_path = claude_dir.join("settings.json");
1450 let original = "[1, 2, 3]";
1451 fs::write(&settings_path, original).unwrap();
1452
1453 let err = install_global_hooks(&claude_dir).unwrap_err();
1454 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1455
1456 let after = fs::read_to_string(&settings_path).unwrap();
1459 assert_eq!(after, original);
1460 let leftover = fs::read_dir(&claude_dir)
1461 .unwrap()
1462 .filter_map(|e| e.ok())
1463 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1464 assert!(!leftover, "no tmp file should be left behind on error");
1465 }
1466
1467 #[test]
1468 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1469 let tmp = tempfile::tempdir().unwrap();
1470 let claude_dir = tmp.path().join(".claude");
1471 fs::create_dir_all(&claude_dir).unwrap();
1472 let settings_path = claude_dir.join("settings.json");
1473 let original = r#"{"hooks": "oops"}"#;
1474 fs::write(&settings_path, original).unwrap();
1475
1476 let err = install_global_hooks(&claude_dir).unwrap_err();
1477 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1478
1479 let after = fs::read_to_string(&settings_path).unwrap();
1480 assert_eq!(after, original);
1481 }
1482
1483 #[test]
1484 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1485 let tmp = tempfile::tempdir().unwrap();
1486 let claude_dir = tmp.path().join(".claude");
1487 fs::create_dir_all(&claude_dir).unwrap();
1488 let settings_path = claude_dir.join("settings.json");
1489 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1490 fs::write(&settings_path, original).unwrap();
1491
1492 let err = install_global_hooks(&claude_dir).unwrap_err();
1493 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1494
1495 let after = fs::read_to_string(&settings_path).unwrap();
1496 assert_eq!(after, original);
1497 }
1498
1499 #[test]
1500 fn safe_join_allows_direct_child_file() {
1501 let tmp = tempfile::tempdir().unwrap();
1502 let base = tmp.path();
1503 let result = safe_join(base, "settings.json").unwrap();
1504 assert_eq!(result.parent(), Some(base));
1505 assert_eq!(result.file_name().unwrap(), "settings.json");
1506 }
1507
1508 #[test]
1509 fn safe_join_rejects_path_traversal() {
1510 let tmp = tempfile::tempdir().unwrap();
1511 let base = tmp.path();
1512 let result = safe_join(base, "../evil");
1513 assert!(result.is_err());
1514 let err = result.unwrap_err();
1515 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1516 assert!(err.to_string().contains("refusing to access path outside"));
1517 }
1518
1519 #[test]
1520 fn safe_join_rejects_absolute_path() {
1521 let tmp = tempfile::tempdir().unwrap();
1522 let base = tmp.path();
1523 let result = safe_join(base, "/etc/passwd");
1524 assert!(result.is_err());
1527 }
1528
1529 #[test]
1530 fn write_global_user_config_enables_and_creates_context() {
1531 let root = tempfile::tempdir().unwrap();
1532 let active = write_global_user_config_in(root.path(), None).unwrap();
1533 let cfg = crate::config::try_load_user_config_in(root.path())
1534 .unwrap()
1535 .unwrap();
1536 assert_eq!(
1539 cfg.user_context.unwrap().resolve_in(root.path()),
1540 Some(crate::config::default_user_context_path_in(root.path()))
1541 );
1542 let ctx = crate::config::default_user_context_path_in(root.path());
1543 assert_eq!(active, Some(ctx.clone()));
1544 assert!(ctx.exists());
1545 }
1546
1547 #[test]
1548 fn write_global_user_config_can_disable() {
1549 let root = tempfile::tempdir().unwrap();
1550 let active = write_global_user_config_in(
1551 root.path(),
1552 Some(crate::config::UserContext::Toggle(false)),
1553 )
1554 .unwrap();
1555 let cfg = crate::config::try_load_user_config_in(root.path())
1556 .unwrap()
1557 .unwrap();
1558 assert!(matches!(
1559 cfg.user_context,
1560 Some(crate::config::UserContext::Toggle(false))
1561 ));
1562 assert_eq!(active, None, "disabled → no active context path");
1563 assert!(
1565 !crate::config::default_user_context_path_in(root.path()).exists(),
1566 "disabled user context must not create a context.json"
1567 );
1568 }
1569
1570 #[test]
1571 fn write_global_user_config_custom_path_seeds_that_file_only() {
1572 let root = tempfile::tempdir().unwrap();
1573 let custom = root.path().join("custom-ctx.json");
1574 let active = write_global_user_config_in(
1575 root.path(),
1576 Some(crate::config::UserContext::Path(
1577 custom.to_string_lossy().into_owned(),
1578 )),
1579 )
1580 .unwrap();
1581 assert_eq!(active, Some(custom.clone()));
1582 assert!(custom.exists(), "the configured custom path must be seeded");
1583 assert!(
1584 !crate::config::default_user_context_path_in(root.path()).exists(),
1585 "the default context.json must NOT be created when a custom path is configured"
1586 );
1587 }
1588
1589 #[test]
1590 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1591 let root = tempfile::tempdir().unwrap();
1592 let custom = root.path().join("custom-ctx.json");
1593 write_global_user_config_in(
1595 root.path(),
1596 Some(crate::config::UserContext::Path(
1597 custom.to_string_lossy().into_owned(),
1598 )),
1599 )
1600 .unwrap();
1601 let active = write_global_user_config_in(root.path(), None).unwrap();
1603 assert_eq!(
1604 active,
1605 Some(custom.clone()),
1606 "re-run without flags must preserve the custom path"
1607 );
1608 let cfg = crate::config::try_load_user_config_in(root.path())
1609 .unwrap()
1610 .unwrap();
1611 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1612 }
1613
1614 #[test]
1615 fn install_global_codex_hooks_writes_and_is_idempotent() {
1616 let tmp = tempfile::tempdir().unwrap();
1617 let codex_dir = tmp.path().join(".codex");
1618
1619 install_global_codex_hooks(&codex_dir).unwrap();
1620 install_global_codex_hooks(&codex_dir).unwrap();
1621
1622 let v: serde_json::Value =
1623 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1624 .unwrap();
1625 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1626 let arr = v["hooks"][event].as_array().unwrap();
1627 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1628 }
1629 assert!(v["hooks"].get("PreToolUse").is_none());
1630 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1632 assert_eq!(
1633 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1634 1,
1635 "AGENTS.md workspace-mode block must appear exactly once"
1636 );
1637 let leftover = fs::read_dir(&codex_dir)
1639 .unwrap()
1640 .filter_map(|e| e.ok())
1641 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1642 assert!(!leftover);
1643 }
1644
1645 #[test]
1646 fn codex_hooks_has_expected_events_and_commands() {
1647 let h = codex_hooks();
1648 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1649 assert!(h.get(event).is_some(), "missing codex event {event}");
1650 }
1651 assert!(h.get("PreToolUse").is_none());
1655 assert!(h.get("Notification").is_none());
1656 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1658 assert_eq!(
1659 cmd("PostToolUse"),
1660 "tracevault stream --event post-tool-use --agent codex"
1661 );
1662 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1663 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1664 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1665 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1667 }
1668
1669 #[test]
1670 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1671 let tmp = tempfile::tempdir().unwrap();
1672 install_codex_hooks(tmp.path()).unwrap();
1673 install_codex_hooks(tmp.path()).unwrap();
1674
1675 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1676 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1677 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1678 let arr = v["hooks"][event].as_array().unwrap();
1679 assert_eq!(
1680 arr.len(),
1681 1,
1682 "event {event} must not be duplicated on re-run"
1683 );
1684 }
1685 assert!(v["hooks"].get("PreToolUse").is_none());
1686 }
1687
1688 #[test]
1689 fn install_codex_hooks_preserves_existing_user_hook() {
1690 let tmp = tempfile::tempdir().unwrap();
1691 let codex_dir = tmp.path().join(".codex");
1692 fs::create_dir_all(&codex_dir).unwrap();
1693 fs::write(
1696 codex_dir.join("hooks.json"),
1697 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1698 )
1699 .unwrap();
1700
1701 install_codex_hooks(tmp.path()).unwrap();
1702
1703 let v: serde_json::Value =
1704 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1705 .unwrap();
1706 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1708 .as_array()
1709 .unwrap()
1710 .iter()
1711 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1712 .collect();
1713 assert!(
1714 post_cmds.contains(&"my-own"),
1715 "user PostToolUse hook preserved"
1716 );
1717 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1718 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1720 .as_array()
1721 .unwrap()
1722 .iter()
1723 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1724 .collect();
1725 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1726 }
1727
1728 #[test]
1729 fn validate_init_flags_rejects_claude_settings_with_codex() {
1730 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1731 }
1732
1733 #[test]
1734 fn validate_init_flags_allows_codex_without_claude_settings() {
1735 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1736 }
1737
1738 #[test]
1739 fn validate_init_flags_allows_claude_with_claude_settings() {
1740 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1741 }
1742
1743 #[test]
1744 fn merge_hooks_into_file_rejects_parent_dir() {
1745 let tmp = tempfile::tempdir().unwrap();
1746 let bad = tmp.path().join("..").join("hooks.json");
1747 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1748 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1749 }
1750
1751 #[test]
1752 fn append_workspace_md_rejects_parent_dir() {
1753 let tmp = tempfile::tempdir().unwrap();
1754 let bad = tmp.path().join("..").join("AGENTS.md");
1755 let err = append_workspace_md(&bad).unwrap_err();
1756 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1757 }
1758
1759 #[tokio::test]
1760 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1761 let tmp = tempfile::tempdir().unwrap();
1762 let root = tmp.path();
1763 crate::test_helpers::init_git_repo(root);
1764
1765 let entry = init_in_directory(
1766 root,
1767 None,
1768 None,
1769 false,
1770 crate::config::UserContext::Toggle(false),
1771 crate::agent::Agent::Codex,
1772 )
1773 .await
1774 .unwrap();
1775
1776 assert!(root.join(".codex").join("hooks.json").exists());
1778 assert!(!root.join(".claude").join("settings.json").exists());
1779 assert_eq!(entry, ".codex/hooks.json");
1780
1781 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1783 assert!(gi.contains(".codex/hooks.json"));
1784 assert!(gi.contains(".tracevault/"));
1785 }
1786
1787 #[tokio::test]
1799 async fn init_in_directory_registers_repo_and_persists_repo_id() {
1800 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1801 let tmp = tempfile::tempdir().unwrap();
1802 let root = tmp.path();
1803 crate::test_helpers::init_git_repo(root);
1804 add_origin_remote(root, "git@github.com:org/repo.git");
1805
1806 let repo_id = "11111111-1111-4111-8111-111111111111";
1807 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
1808 let base = spawn_once(http_response("200 OK", &body));
1809
1810 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1811 _guard.set("XDG_CONFIG_HOME", tmp.path());
1812 _guard.set("TRACEVAULT_API_KEY", "tok");
1813 _guard.remove("TRACEVAULT_SERVER_URL");
1814
1815 init_in_directory(
1816 root,
1817 Some(&base),
1818 None,
1819 true,
1820 crate::config::UserContext::Toggle(false),
1821 crate::agent::Agent::Codex,
1822 )
1823 .await
1824 .unwrap();
1825
1826 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1827 assert_eq!(
1828 cfg.repo_id,
1829 Some(repo_id.to_string()),
1830 "successful registration must persist repo_id to config.toml"
1831 );
1832 }
1833
1834 #[tokio::test]
1840 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
1841 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1842 let tmp = tempfile::tempdir().unwrap();
1843 let root = tmp.path();
1844 crate::test_helpers::init_git_repo(root);
1845 add_origin_remote(root, "git@github.com:org/repo.git");
1846
1847 let base = spawn_once(http_response("403 Forbidden", ""));
1848
1849 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1850 _guard.set("XDG_CONFIG_HOME", tmp.path());
1851 _guard.set("TRACEVAULT_API_KEY", "tok");
1852 _guard.remove("TRACEVAULT_SERVER_URL");
1853
1854 let entry = init_in_directory(
1855 root,
1856 Some(&base),
1857 None,
1858 true,
1859 crate::config::UserContext::Toggle(false),
1860 crate::agent::Agent::Codex,
1861 )
1862 .await
1863 .expect("a registration failure (403) must not abort init itself");
1864 assert_eq!(entry, ".codex/hooks.json");
1865
1866 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1867 assert!(
1868 cfg.repo_id.is_none(),
1869 "a 403 registration failure must not persist a repo_id"
1870 );
1871 }
1872
1873 #[tokio::test]
1878 async fn registration_failure_message_flags_403_as_not_authorized() {
1879 let base = spawn_once(http_response("403 Forbidden", ""));
1880 let client = ApiClient::new(&base, Some("tok"));
1881 let err = client
1882 .register_repo(crate::api_client::RegisterRepoRequest {
1883 repo_name: "repo".into(),
1884 github_url: Some("git@github.com:org/repo.git".into()),
1885 })
1886 .await
1887 .unwrap_err();
1888 let msg = registration_failure_message(err.as_ref());
1889 assert!(
1890 msg.contains("not authorized"),
1891 "403 registration failure must surface a not-authorized message; got: {msg}"
1892 );
1893 }
1894
1895 #[tokio::test]
1898 async fn registration_failure_message_generic_for_non_403() {
1899 let base = spawn_once(http_response("500 Internal Server Error", ""));
1900 let client = ApiClient::new(&base, Some("tok"));
1901 let err = client
1902 .register_repo(crate::api_client::RegisterRepoRequest {
1903 repo_name: "repo".into(),
1904 github_url: Some("git@github.com:org/repo.git".into()),
1905 })
1906 .await
1907 .unwrap_err();
1908 let msg = registration_failure_message(err.as_ref());
1909 assert!(
1910 msg.contains("could not register repo on server"),
1911 "got: {msg}"
1912 );
1913 assert!(!msg.contains("not authorized"), "got: {msg}");
1914 }
1915
1916 #[tokio::test]
1921 async fn registration_failure_message_does_not_misclassify_403_in_body() {
1922 let base = spawn_once(http_response(
1923 "500 Internal Server Error",
1924 "upstream error 403 from proxy",
1925 ));
1926 let client = ApiClient::new(&base, Some("tok"));
1927 let err = client
1928 .register_repo(crate::api_client::RegisterRepoRequest {
1929 repo_name: "repo".into(),
1930 github_url: Some("git@github.com:org/repo.git".into()),
1931 })
1932 .await
1933 .unwrap_err();
1934 let msg = registration_failure_message(err.as_ref());
1935 assert!(
1936 !msg.contains("not authorized"),
1937 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
1938 );
1939 assert!(
1940 msg.contains("could not register repo on server"),
1941 "got: {msg}"
1942 );
1943 }
1944
1945 #[tokio::test]
1949 async fn registration_failure_message_flags_404_as_version_mismatch() {
1950 let base = spawn_once(http_response("404 Not Found", ""));
1951 let client = ApiClient::new(&base, Some("tok"));
1952 let err = client
1953 .register_repo(crate::api_client::RegisterRepoRequest {
1954 repo_name: "repo".into(),
1955 github_url: Some("git@github.com:org/repo.git".into()),
1956 })
1957 .await
1958 .unwrap_err();
1959 let msg = registration_failure_message(err.as_ref());
1960 assert!(
1961 msg.to_lowercase().contains("version mismatch"),
1962 "a 404 registration failure should hint at a version mismatch; got: {msg}"
1963 );
1964 }
1965}