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 => install_codex_hooks(project_root)?,
211 crate::agent::Agent::Gsd => {
212 install_gsd_extension(Some(project_root))?;
220 }
221 crate::agent::Agent::OpenCode => {
222 install_opencode_plugin(Some(project_root))?;
223 }
224 }
225
226 install_git_hook(project_root)?;
228 install_post_commit_hook(project_root)?;
229
230 let detected = crate::hooks::detect_tools(project_root);
232 for tool in &detected {
233 println!(" Detected: {}", tool.name());
234 }
235
236 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
237 let effective_url = server_url.map(String::from).or(resolved_url);
238
239 if resolved_token.is_none() {
240 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
241 } else if let (Some(url), Some(remote)) = (effective_url, remote_url) {
242 let client = ApiClient::new(&url, resolved_token.as_deref());
243 let repo_name = git_repo_name(project_root);
244 let origin_url = remote.clone();
247
248 match client
249 .register_repo(crate::api_client::RegisterRepoRequest {
250 repo_name,
251 github_url: Some(remote),
252 })
253 .await
254 {
255 Ok(resp) => {
256 println!("Repo registered on server (id: {})", resp.repo_id);
257 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
259 cfg.repo_id = Some(resp.repo_id.to_string());
260 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
266 println!(
267 "{}",
268 crate::resolution::codebase_line(
269 remote.name.as_deref(),
270 &remote.normalized_url,
271 &remote.clone_status
272 )
273 );
274 cfg.remote_id = Some(remote.remote_id.to_string());
275 cfg.codebase_name = remote.name.clone();
276 }
277 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
278 }
279 }
280 Err(e) => {
281 eprintln!("{}", registration_failure_message(e.as_ref()));
282 }
283 }
284 }
285
286 Ok(hook_gitignore_entry)
287}
288
289fn registration_failure_message(err: &dyn std::error::Error) -> String {
304 let msg = err.to_string();
305 if msg.starts_with("Server returned 403 ") {
306 "Warning: you are not authorized to register this repo.".to_string()
307 } else if msg.starts_with("Server returned 404 ") {
308 "Warning: could not register repo on server (404) — this endpoint may not exist on \
309 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
310 once the server is upgraded."
311 .to_string()
312 } else {
313 format!("Warning: could not register repo on server: {err}")
314 }
315}
316
317fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
318 let path = project_root.join(".gitignore");
319 let existing = if path.exists() {
320 fs::read_to_string(&path)?
321 } else {
322 String::new()
323 };
324
325 let needed: Vec<&str> = [".tracevault/", settings_entry]
331 .iter()
332 .copied()
333 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
334 .collect();
335
336 if needed.is_empty() {
337 return Ok(());
338 }
339
340 let mut content = existing;
341 if !content.is_empty() && !content.ends_with('\n') {
342 content.push('\n');
343 }
344 content.push_str("\n# TraceVault — local only, do not commit\n");
345 for entry in needed {
346 content.push_str(entry);
347 content.push('\n');
348 }
349
350 fs::write(path, content)
351}
352
353const HOOK_MARKER: &str = "# tracevault:enforce";
354const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
355
356fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
357 let hooks_dir = project_root.join(".git/hooks");
358 fs::create_dir_all(&hooks_dir)?;
359
360 let hook_path = hooks_dir.join("pre-push");
361 let tracevault_block = format!(
362 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
363 );
364
365 if hook_path.exists() {
366 let existing = fs::read_to_string(&hook_path)?;
367
368 if existing.contains(HOOK_MARKER) {
370 return Ok(());
371 }
372
373 if existing.contains(OLD_HOOK_MARKER) {
375 let mut new_content = String::new();
376 let mut skip = false;
377 for line in existing.lines() {
378 if line.contains(OLD_HOOK_MARKER) {
379 skip = true;
380 continue;
381 }
382 if skip {
383 if line.starts_with("tracevault ") {
385 continue;
386 }
387 skip = false;
388 }
389 new_content.push_str(line);
390 new_content.push('\n');
391 }
392 if !new_content.ends_with('\n') {
393 new_content.push('\n');
394 }
395 new_content.push_str(&tracevault_block);
396 fs::write(&hook_path, new_content)?;
397 } else {
398 let mut content = existing;
400 if !content.ends_with('\n') {
401 content.push('\n');
402 }
403 content.push_str(&tracevault_block);
404 fs::write(&hook_path, content)?;
405 }
406 } else {
407 let content = format!("#!/bin/sh\n{tracevault_block}");
408 fs::write(&hook_path, content)?;
409 }
410
411 #[cfg(unix)]
413 {
414 use std::os::unix::fs::PermissionsExt;
415 let mut perms = fs::metadata(&hook_path)?.permissions();
416 perms.set_mode(0o755);
417 fs::set_permissions(&hook_path, perms)?;
418 }
419
420 Ok(())
421}
422
423const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
424
425fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
426 let hooks_dir = project_root.join(".git/hooks");
427 fs::create_dir_all(&hooks_dir)?;
428
429 let hook_path = hooks_dir.join("post-commit");
430 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
431
432 if hook_path.exists() {
433 let existing = fs::read_to_string(&hook_path)?;
434
435 if existing.contains(POST_COMMIT_MARKER) {
436 return Ok(());
437 }
438
439 let mut content = existing;
440 if !content.ends_with('\n') {
441 content.push('\n');
442 }
443 content.push_str(&tracevault_block);
444 fs::write(&hook_path, content)?;
445 } else {
446 let content = format!("#!/bin/sh\n{tracevault_block}");
447 fs::write(&hook_path, content)?;
448 }
449
450 #[cfg(unix)]
451 {
452 use std::os::unix::fs::PermissionsExt;
453 let mut perms = fs::metadata(&hook_path)?.permissions();
454 perms.set_mode(0o755);
455 fs::set_permissions(&hook_path, perms)?;
456 }
457
458 Ok(())
459}
460
461fn install_claude_hooks(
462 project_root: &Path,
463 target: ClaudeSettingsTarget,
464) -> Result<(), io::Error> {
465 let claude_dir = project_root.join(".claude");
466 fs::create_dir_all(&claude_dir)?;
467
468 let filename = target.filename();
469 let settings_path = claude_dir.join(filename);
470 let mut settings: serde_json::Value = if settings_path.exists() {
471 let content = fs::read_to_string(&settings_path)?;
472 serde_json::from_str(&content).map_err(|e| {
473 io::Error::new(
474 io::ErrorKind::InvalidData,
475 format!("Failed to parse .claude/{filename}: {e}"),
476 )
477 })?
478 } else {
479 serde_json::json!({})
480 };
481
482 let hooks = tracevault_hooks();
483
484 let settings_obj = settings.as_object_mut().ok_or_else(|| {
486 io::Error::new(
487 io::ErrorKind::InvalidData,
488 format!(".claude/{filename} is not a JSON object"),
489 )
490 })?;
491
492 settings_obj.insert("hooks".to_string(), hooks);
493
494 let formatted = serde_json::to_string_pretty(&settings)
495 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
496 fs::write(&settings_path, formatted)?;
497
498 Ok(())
499}
500
501pub fn tracevault_hooks() -> serde_json::Value {
502 serde_json::json!({
503 "PreToolUse": [{
504 "matcher": "Write|Edit|Bash",
505 "hooks": [{
506 "type": "command",
507 "command": "tracevault stream --event pre-tool-use",
508 "timeout": 10,
509 "statusMessage": "TraceVault: streaming pre-tool event"
510 }]
511 }],
512 "PostToolUse": [{
513 "matcher": "",
514 "hooks": [{
515 "type": "command",
516 "command": "tracevault stream --event post-tool-use",
517 "timeout": 10,
518 "statusMessage": "TraceVault: streaming post-tool event"
519 }]
520 }],
521 "Notification": [{
522 "matcher": "",
523 "hooks": [{
524 "type": "command",
525 "command": "tracevault stream --event notification",
526 "timeout": 10,
527 "statusMessage": "TraceVault: streaming notification"
528 }]
529 }],
530 "Stop": [{
531 "matcher": "",
532 "hooks": [{
533 "type": "command",
534 "command": "tracevault stream --event stop",
535 "timeout": 10,
536 "statusMessage": "TraceVault: finalizing session"
537 }]
538 }],
539 "SessionStart": [{
540 "matcher": "",
541 "hooks": [{
542 "type": "command",
543 "command": "tracevault session-start",
544 "timeout": 10,
545 "statusMessage": "TraceVault: session start"
546 }]
547 }],
548 "UserPromptSubmit": [{
549 "matcher": "",
550 "hooks": [{
551 "type": "command",
552 "command": "tracevault user-prompt",
553 "timeout": 10,
554 "statusMessage": "TraceVault: policy reinforcement"
555 }]
556 }]
557 })
558}
559
560pub fn codex_hooks() -> serde_json::Value {
571 serde_json::json!({
572 "SessionStart": [{
573 "matcher": "",
574 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
575 }],
576 "UserPromptSubmit": [{
577 "matcher": "",
578 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
579 }],
580 "PostToolUse": [{
581 "matcher": "",
582 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
583 }],
584 "Stop": [{
585 "matcher": "",
586 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
587 }]
588 })
589}
590
591const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
595const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
596const GSD_EXT_MANIFEST_JSON: &str =
597 include_str!("../../assets/gsd-extension/extension-manifest.json");
598
599fn gsd_extension_source_dir() -> io::Result<PathBuf> {
603 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
604 let config_dir = config_dir
605 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
606 Ok(config_dir.join("tracevault").join("gsd-extension"))
607}
608
609pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
633 let home =
634 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
635 let gsd_home = home.join(".gsd");
636
637 let source_dir = gsd_extension_source_dir()?;
638 fs::create_dir_all(&source_dir)?;
639 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
640 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
641 fs::write(
642 source_dir.join("extension-manifest.json"),
643 GSD_EXT_MANIFEST_JSON,
644 )?;
645
646 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
650 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
651 }
652
653 let local_flag = project_root.is_some();
657 let mut cmd = std::process::Command::new("gsd");
658 cmd.arg("install").arg(&source_dir);
659 if let Some(root) = project_root {
660 cmd.arg("-l");
661 cmd.current_dir(root);
662 }
663
664 let retry_hint = format!(
665 "gsd install {}{}",
666 source_dir.display(),
667 if local_flag { " -l" } else { "" }
668 );
669
670 match cmd.output() {
671 Ok(output) if output.status.success() => {
672 println!(
673 "TraceVault: installed and registered the GSD extension ({}).",
674 source_dir.display()
675 );
676 }
677 Ok(output) => {
678 eprintln!(
679 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
680 source_dir.display(),
681 String::from_utf8_lossy(&output.stderr),
682 );
683 }
684 Err(e) => {
685 eprintln!(
686 "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.",
687 source_dir.display(),
688 );
689 }
690 }
691
692 Ok(())
693}
694
695const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
698
699pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
715 let plugins_dir = match project_root {
716 Some(root) => root.join(".opencode").join("plugins"),
717 None => {
718 let config_dir =
719 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
720 config_dir
721 .ok_or_else(|| {
722 io::Error::new(
723 io::ErrorKind::NotFound,
724 "could not determine the config directory for the OpenCode plugin install",
725 )
726 })?
727 .join("opencode")
728 .join("plugins")
729 }
730 };
731
732 write_opencode_plugin_files(&plugins_dir)
733}
734
735fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
736 fs::create_dir_all(plugins_dir)?;
737 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
738 Ok(())
739}
740
741pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
753 let ext_root = gsd_home.join("extensions");
754 let reg_path = ext_root.join("registry.json");
755
756 let reg: Option<serde_json::Value> = if reg_path.exists() {
761 let content = fs::read_to_string(®_path)?;
762 let parsed: serde_json::Value = match serde_json::from_str(&content) {
763 Ok(v) => v,
764 Err(_) => return Ok(()), };
766 let corrupt = match parsed.as_object() {
767 None => true,
768 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
769 };
770 if corrupt {
771 return Ok(()); }
773 Some(parsed)
774 } else {
775 None
776 };
777
778 let stale = ext_root.join("tracevault-tracker");
780 if stale.exists() {
781 fs::remove_dir_all(&stale)?;
782 }
783
784 if let Some(mut reg) = reg {
786 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
787 let removed_tracker = entries.remove("tracevault-tracker").is_some();
788 let removed_inert = entries.remove("tracevault").is_some();
789 if removed_tracker || removed_inert {
790 let tmp = reg_path.with_extension("json.tmp");
792 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
793 fs::rename(&tmp, ®_path)?;
794 }
795 }
796 }
797 Ok(())
798}
799
800fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
810 if hooks_path
815 .components()
816 .any(|c| c == std::path::Component::ParentDir)
817 {
818 return Err(io::Error::new(
819 io::ErrorKind::InvalidInput,
820 format!("refusing to use path with '..': {}", hooks_path.display()),
821 ));
822 }
823 let mut root: serde_json::Value = if hooks_path.exists() {
824 let content = fs::read_to_string(hooks_path)?;
825 serde_json::from_str(&content).map_err(|e| {
826 io::Error::new(
827 io::ErrorKind::InvalidData,
828 format!("Failed to parse {}: {e}", hooks_path.display()),
829 )
830 })?
831 } else {
832 serde_json::json!({})
833 };
834
835 merge_hooks(&mut root, ours, hooks_path)?;
836
837 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
838 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
839 })?;
840 let tmp = hooks_path.with_extension("json.tmp");
841 fs::write(&tmp, formatted)?;
842 fs::rename(&tmp, hooks_path)?;
843 Ok(())
844}
845
846pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
850 let codex_dir = project_root.join(".codex");
851 fs::create_dir_all(&codex_dir)?;
852 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
853}
854
855pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
862 fs::create_dir_all(codex_dir)?;
863 let base = codex_dir.canonicalize()?;
865 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
866 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
867}
868
869const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
873
874const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
875<!-- tracevault:workspace-mode -->
876## TraceVault (workspace mode)
877You may be running detached from any single repository. Before working on a repo, run
878`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
879output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
880already be registered with TraceVault.
881";
882
883fn append_workspace_md(md_path: &Path) -> io::Result<()> {
889 if md_path
891 .components()
892 .any(|c| c == std::path::Component::ParentDir)
893 {
894 return Err(io::Error::new(
895 io::ErrorKind::InvalidInput,
896 format!("refusing to use path with '..': {}", md_path.display()),
897 ));
898 }
899 let existing = if md_path.exists() {
900 fs::read_to_string(md_path)?
901 } else {
902 String::new()
903 };
904 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
905 return Ok(());
906 }
907 let mut content = existing;
908 if !content.is_empty() && !content.ends_with('\n') {
909 content.push('\n');
910 }
911 if !content.is_empty() {
912 content.push('\n');
913 }
914 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
915 fs::write(md_path, content)
916}
917
918fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
922 let joined = base.join(name);
923 if joined.parent() != Some(base) {
924 return Err(io::Error::new(
925 io::ErrorKind::InvalidInput,
926 format!(
927 "refusing to access path outside {}: {}",
928 base.display(),
929 joined.display()
930 ),
931 ));
932 }
933 Ok(joined)
934}
935
936fn merge_hooks(
949 settings: &mut serde_json::Value,
950 ours: &serde_json::Value,
951 path: &Path,
952) -> io::Result<()> {
953 if settings.is_null() {
954 *settings = serde_json::json!({});
955 }
956 let settings_obj = settings.as_object_mut().ok_or_else(|| {
957 io::Error::new(
958 io::ErrorKind::InvalidData,
959 format!("{} is not a JSON object", path.display()),
960 )
961 })?;
962
963 let hooks_value = settings_obj
964 .entry("hooks")
965 .or_insert_with(|| serde_json::json!({}));
966 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
967 io::Error::new(
968 io::ErrorKind::InvalidData,
969 format!("{} \"hooks\" key is not a JSON object", path.display()),
970 )
971 })?;
972
973 let Some(ours_obj) = ours.as_object() else {
974 return Ok(());
975 };
976
977 for (event, our_array) in ours_obj {
978 let Some(our_entries) = our_array.as_array() else {
979 continue;
980 };
981
982 let existing_value = hooks_obj
983 .entry(event.clone())
984 .or_insert_with(|| serde_json::json!([]));
985 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
986 io::Error::new(
987 io::ErrorKind::InvalidData,
988 format!(
989 "{} \"hooks\".\"{event}\" is not a JSON array",
990 path.display()
991 ),
992 )
993 })?;
994
995 for our_entry in our_entries {
996 let our_command = entry_command(our_entry);
997 let already_present = existing_array
998 .iter()
999 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1000 if !already_present {
1001 existing_array.push(our_entry.clone());
1002 }
1003 }
1004 }
1005
1006 Ok(())
1007}
1008
1009fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1012 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1013}
1014
1015fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1020 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1021 return false;
1022 };
1023 hooks
1024 .iter()
1025 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1026}
1027
1028pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1034 fs::create_dir_all(claude_dir)?;
1035
1036 let base = claude_dir.canonicalize()?;
1039
1040 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1042
1043 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1045}
1046
1047pub fn write_global_user_config_in(
1057 config_root: &Path,
1058 requested: Option<UserContext>,
1059) -> io::Result<Option<PathBuf>> {
1060 fs::create_dir_all(config_root)?;
1061 let mut config = crate::config::try_load_user_config_in(config_root)
1063 .ok()
1064 .flatten()
1065 .unwrap_or_default();
1066 let user_context = requested
1068 .or_else(|| config.user_context.clone())
1069 .unwrap_or(UserContext::Toggle(true));
1070 let active = user_context
1071 .resolve()
1072 .map(|_| user_context.path_in(config_root));
1073 config.user_context = Some(user_context);
1074 fs::write(user_config_path_in(config_root), config.to_toml())?;
1075 if let Some(ref ctx_path) = active {
1076 if !ctx_path.exists() {
1077 Context::default().save_to(ctx_path)?;
1078 }
1079 }
1080 Ok(active)
1081}
1082
1083#[cfg(test)]
1084mod tests {
1085 use super::*;
1086 use std::io::{BufRead, BufReader, Write};
1087 use std::net::TcpListener;
1088 use std::thread;
1089
1090 fn spawn_once(response: String) -> String {
1093 let response: &'static str = Box::leak(response.into_boxed_str());
1094 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1095 let addr = listener.local_addr().unwrap();
1096 thread::spawn(move || {
1097 if let Ok((stream, _)) = listener.accept() {
1098 let mut reader = BufReader::new(stream);
1099 let mut request_line = String::new();
1100 let _ = reader.read_line(&mut request_line);
1101 let mut stream = reader.into_inner();
1102 let _ = stream.write_all(response.as_bytes());
1103 let _ = stream.flush();
1104 }
1105 });
1106 format!("http://{addr}")
1107 }
1108
1109 fn http_response(status: &str, body: &str) -> String {
1112 format!(
1113 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1114 status,
1115 body.len(),
1116 body
1117 )
1118 }
1119
1120 fn add_origin_remote(dir: &Path, url: &str) {
1121 let ok = std::process::Command::new("git")
1122 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1123 .status()
1124 .expect("git remote add failed")
1125 .success();
1126 assert!(ok, "git remote add must succeed");
1127 }
1128
1129 #[test]
1130 fn linked_worktree_primary_detects_linked_and_primary() {
1131 let tmp = tempfile::tempdir().unwrap();
1132 let repo = tmp.path().join("repo");
1133 let wt = tmp.path().join("linked-wt");
1134 std::fs::create_dir_all(&repo).unwrap();
1135 crate::test_helpers::init_git_repo(&repo);
1136 crate::test_helpers::add_worktree(&repo, &wt);
1137
1138 assert!(
1140 linked_worktree_primary(&repo).is_none(),
1141 "primary checkout must not be flagged as a linked worktree"
1142 );
1143 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1145 assert_eq!(
1146 primary.canonicalize().unwrap(),
1147 repo.canonicalize().unwrap(),
1148 "must resolve to the primary repo root"
1149 );
1150 }
1151
1152 #[test]
1153 fn linked_worktree_primary_none_for_non_git() {
1154 let tmp = tempfile::tempdir().unwrap();
1155 assert!(
1156 linked_worktree_primary(tmp.path()).is_none(),
1157 "a non-git directory is not a linked worktree"
1158 );
1159 }
1160
1161 #[test]
1162 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1163 let mut settings = serde_json::json!({});
1164 let ours = tracevault_hooks();
1165 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1166
1167 let hooks = settings.get("hooks").unwrap();
1168 for event in [
1169 "PreToolUse",
1170 "PostToolUse",
1171 "Notification",
1172 "Stop",
1173 "SessionStart",
1174 "UserPromptSubmit",
1175 ] {
1176 assert!(hooks.get(event).is_some(), "missing event {event}");
1177 }
1178 }
1179
1180 #[test]
1181 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1182 let mut settings = serde_json::json!({
1183 "model": "opus",
1184 "hooks": {
1185 "PreToolUse": [{
1186 "matcher": "",
1187 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1188 }]
1189 }
1190 });
1191 let ours = tracevault_hooks();
1192 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1193
1194 assert_eq!(settings.get("model").unwrap(), "opus");
1196
1197 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1198 assert_eq!(pre_tool_use.len(), 2);
1200 let commands: Vec<&str> = pre_tool_use
1201 .iter()
1202 .map(|e| entry_command(e).unwrap())
1203 .collect();
1204 assert!(commands.contains(&"my-own-hook"));
1205 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1206
1207 assert!(settings["hooks"]["SessionStart"].is_array());
1209 }
1210
1211 #[test]
1212 fn merge_hooks_is_idempotent() {
1213 let mut settings = serde_json::json!({});
1214 let ours = tracevault_hooks();
1215 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1216 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1217
1218 for event in [
1219 "PreToolUse",
1220 "PostToolUse",
1221 "Notification",
1222 "Stop",
1223 "SessionStart",
1224 "UserPromptSubmit",
1225 ] {
1226 let arr = settings["hooks"][event].as_array().unwrap();
1227 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1228 }
1229 }
1230
1231 #[test]
1232 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1233 let mut settings = serde_json::json!({
1237 "hooks": {
1238 "PreToolUse": [{
1239 "matcher": "Write|Edit|Bash",
1240 "hooks": [
1241 { "type": "command", "command": "other" },
1242 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1243 ]
1244 }]
1245 }
1246 });
1247 let ours = tracevault_hooks();
1248 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1249
1250 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1251 assert_eq!(
1252 pre_tool_use.len(),
1253 1,
1254 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1255 );
1256 }
1257
1258 #[test]
1259 fn merge_hooks_errors_on_non_object_top_level() {
1260 let mut settings = serde_json::json!([1, 2, 3]);
1261 let ours = tracevault_hooks();
1262 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1263 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1264 assert!(err.to_string().contains("settings.json"));
1265 }
1266
1267 #[test]
1268 fn merge_hooks_errors_on_non_object_top_level_number() {
1269 let mut settings = serde_json::json!(42);
1270 let ours = tracevault_hooks();
1271 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1272 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1273 }
1274
1275 #[test]
1276 fn merge_hooks_errors_on_non_object_hooks() {
1277 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1278 let ours = tracevault_hooks();
1279 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1280 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1281 assert!(err.to_string().contains("hooks"));
1282 }
1283
1284 #[test]
1285 fn merge_hooks_errors_on_non_array_event_value() {
1286 let mut settings = serde_json::json!({
1287 "hooks": {
1288 "PreToolUse": "not-an-array"
1289 }
1290 });
1291 let ours = tracevault_hooks();
1292 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1293 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1294 assert!(err.to_string().contains("PreToolUse"));
1295 }
1296
1297 #[test]
1298 fn install_global_hooks_writes_settings_and_claude_md() {
1299 let tmp = tempfile::tempdir().unwrap();
1300 let claude_dir = tmp.path().join(".claude");
1301
1302 install_global_hooks(&claude_dir).unwrap();
1303
1304 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1305 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1306 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1307 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1308 }
1309
1310 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1311 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1312 }
1313
1314 #[test]
1315 fn install_global_hooks_is_idempotent() {
1316 let tmp = tempfile::tempdir().unwrap();
1317 let claude_dir = tmp.path().join(".claude");
1318
1319 install_global_hooks(&claude_dir).unwrap();
1320 install_global_hooks(&claude_dir).unwrap();
1321
1322 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1323 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1324 for event in [
1325 "PreToolUse",
1326 "PostToolUse",
1327 "Notification",
1328 "Stop",
1329 "SessionStart",
1330 "UserPromptSubmit",
1331 ] {
1332 let arr = settings["hooks"][event].as_array().unwrap();
1333 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1334 }
1335
1336 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1337 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1338 assert_eq!(
1339 marker_count, 1,
1340 "CLAUDE.md marker should appear exactly once"
1341 );
1342 }
1343
1344 #[test]
1345 fn install_global_hooks_preserves_existing_claude_md_content() {
1346 let tmp = tempfile::tempdir().unwrap();
1347 let claude_dir = tmp.path().join(".claude");
1348 fs::create_dir_all(&claude_dir).unwrap();
1349 fs::write(
1350 claude_dir.join("CLAUDE.md"),
1351 "# My existing notes\nSome content.\n",
1352 )
1353 .unwrap();
1354
1355 install_global_hooks(&claude_dir).unwrap();
1356
1357 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1358 assert!(claude_md.contains("# My existing notes"));
1359 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1360 }
1361
1362 #[test]
1363 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1364 let tmp = tempfile::tempdir().unwrap();
1365 let claude_dir = tmp.path().join(".claude");
1366
1367 install_global_hooks(&claude_dir).unwrap();
1368
1369 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1370 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1371 assert!(settings["hooks"].get("SessionStart").is_some());
1372
1373 let leftover = fs::read_dir(&claude_dir)
1374 .unwrap()
1375 .filter_map(|e| e.ok())
1376 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1377 assert!(
1378 !leftover,
1379 "no settings.json.tmp should remain after install"
1380 );
1381 }
1382
1383 #[test]
1384 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1385 let tmp = tempfile::tempdir().unwrap();
1386 let claude_dir = tmp.path().join(".claude");
1387 fs::create_dir_all(&claude_dir).unwrap();
1388 let settings_path = claude_dir.join("settings.json");
1389 let original = "[1, 2, 3]";
1390 fs::write(&settings_path, original).unwrap();
1391
1392 let err = install_global_hooks(&claude_dir).unwrap_err();
1393 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1394
1395 let after = fs::read_to_string(&settings_path).unwrap();
1398 assert_eq!(after, original);
1399 let leftover = fs::read_dir(&claude_dir)
1400 .unwrap()
1401 .filter_map(|e| e.ok())
1402 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1403 assert!(!leftover, "no tmp file should be left behind on error");
1404 }
1405
1406 #[test]
1407 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1408 let tmp = tempfile::tempdir().unwrap();
1409 let claude_dir = tmp.path().join(".claude");
1410 fs::create_dir_all(&claude_dir).unwrap();
1411 let settings_path = claude_dir.join("settings.json");
1412 let original = r#"{"hooks": "oops"}"#;
1413 fs::write(&settings_path, original).unwrap();
1414
1415 let err = install_global_hooks(&claude_dir).unwrap_err();
1416 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1417
1418 let after = fs::read_to_string(&settings_path).unwrap();
1419 assert_eq!(after, original);
1420 }
1421
1422 #[test]
1423 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1424 let tmp = tempfile::tempdir().unwrap();
1425 let claude_dir = tmp.path().join(".claude");
1426 fs::create_dir_all(&claude_dir).unwrap();
1427 let settings_path = claude_dir.join("settings.json");
1428 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1429 fs::write(&settings_path, original).unwrap();
1430
1431 let err = install_global_hooks(&claude_dir).unwrap_err();
1432 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1433
1434 let after = fs::read_to_string(&settings_path).unwrap();
1435 assert_eq!(after, original);
1436 }
1437
1438 #[test]
1439 fn safe_join_allows_direct_child_file() {
1440 let tmp = tempfile::tempdir().unwrap();
1441 let base = tmp.path();
1442 let result = safe_join(base, "settings.json").unwrap();
1443 assert_eq!(result.parent(), Some(base));
1444 assert_eq!(result.file_name().unwrap(), "settings.json");
1445 }
1446
1447 #[test]
1448 fn safe_join_rejects_path_traversal() {
1449 let tmp = tempfile::tempdir().unwrap();
1450 let base = tmp.path();
1451 let result = safe_join(base, "../evil");
1452 assert!(result.is_err());
1453 let err = result.unwrap_err();
1454 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1455 assert!(err.to_string().contains("refusing to access path outside"));
1456 }
1457
1458 #[test]
1459 fn safe_join_rejects_absolute_path() {
1460 let tmp = tempfile::tempdir().unwrap();
1461 let base = tmp.path();
1462 let result = safe_join(base, "/etc/passwd");
1463 assert!(result.is_err());
1466 }
1467
1468 #[test]
1469 fn write_global_user_config_enables_and_creates_context() {
1470 let root = tempfile::tempdir().unwrap();
1471 let active = write_global_user_config_in(root.path(), None).unwrap();
1472 let cfg = crate::config::try_load_user_config_in(root.path())
1473 .unwrap()
1474 .unwrap();
1475 assert_eq!(
1478 cfg.user_context.unwrap().resolve_in(root.path()),
1479 Some(crate::config::default_user_context_path_in(root.path()))
1480 );
1481 let ctx = crate::config::default_user_context_path_in(root.path());
1482 assert_eq!(active, Some(ctx.clone()));
1483 assert!(ctx.exists());
1484 }
1485
1486 #[test]
1487 fn write_global_user_config_can_disable() {
1488 let root = tempfile::tempdir().unwrap();
1489 let active = write_global_user_config_in(
1490 root.path(),
1491 Some(crate::config::UserContext::Toggle(false)),
1492 )
1493 .unwrap();
1494 let cfg = crate::config::try_load_user_config_in(root.path())
1495 .unwrap()
1496 .unwrap();
1497 assert!(matches!(
1498 cfg.user_context,
1499 Some(crate::config::UserContext::Toggle(false))
1500 ));
1501 assert_eq!(active, None, "disabled → no active context path");
1502 assert!(
1504 !crate::config::default_user_context_path_in(root.path()).exists(),
1505 "disabled user context must not create a context.json"
1506 );
1507 }
1508
1509 #[test]
1510 fn write_global_user_config_custom_path_seeds_that_file_only() {
1511 let root = tempfile::tempdir().unwrap();
1512 let custom = root.path().join("custom-ctx.json");
1513 let active = write_global_user_config_in(
1514 root.path(),
1515 Some(crate::config::UserContext::Path(
1516 custom.to_string_lossy().into_owned(),
1517 )),
1518 )
1519 .unwrap();
1520 assert_eq!(active, Some(custom.clone()));
1521 assert!(custom.exists(), "the configured custom path must be seeded");
1522 assert!(
1523 !crate::config::default_user_context_path_in(root.path()).exists(),
1524 "the default context.json must NOT be created when a custom path is configured"
1525 );
1526 }
1527
1528 #[test]
1529 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1530 let root = tempfile::tempdir().unwrap();
1531 let custom = root.path().join("custom-ctx.json");
1532 write_global_user_config_in(
1534 root.path(),
1535 Some(crate::config::UserContext::Path(
1536 custom.to_string_lossy().into_owned(),
1537 )),
1538 )
1539 .unwrap();
1540 let active = write_global_user_config_in(root.path(), None).unwrap();
1542 assert_eq!(
1543 active,
1544 Some(custom.clone()),
1545 "re-run without flags must preserve the custom path"
1546 );
1547 let cfg = crate::config::try_load_user_config_in(root.path())
1548 .unwrap()
1549 .unwrap();
1550 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1551 }
1552
1553 #[test]
1554 fn install_global_codex_hooks_writes_and_is_idempotent() {
1555 let tmp = tempfile::tempdir().unwrap();
1556 let codex_dir = tmp.path().join(".codex");
1557
1558 install_global_codex_hooks(&codex_dir).unwrap();
1559 install_global_codex_hooks(&codex_dir).unwrap();
1560
1561 let v: serde_json::Value =
1562 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1563 .unwrap();
1564 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1565 let arr = v["hooks"][event].as_array().unwrap();
1566 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1567 }
1568 assert!(v["hooks"].get("PreToolUse").is_none());
1569 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1571 assert_eq!(
1572 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1573 1,
1574 "AGENTS.md workspace-mode block must appear exactly once"
1575 );
1576 let leftover = fs::read_dir(&codex_dir)
1578 .unwrap()
1579 .filter_map(|e| e.ok())
1580 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1581 assert!(!leftover);
1582 }
1583
1584 #[test]
1585 fn codex_hooks_has_expected_events_and_commands() {
1586 let h = codex_hooks();
1587 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1588 assert!(h.get(event).is_some(), "missing codex event {event}");
1589 }
1590 assert!(h.get("PreToolUse").is_none());
1594 assert!(h.get("Notification").is_none());
1595 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1597 assert_eq!(
1598 cmd("PostToolUse"),
1599 "tracevault stream --event post-tool-use --agent codex"
1600 );
1601 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1602 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1603 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1604 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1606 }
1607
1608 #[test]
1609 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1610 let tmp = tempfile::tempdir().unwrap();
1611 install_codex_hooks(tmp.path()).unwrap();
1612 install_codex_hooks(tmp.path()).unwrap();
1613
1614 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1615 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1616 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1617 let arr = v["hooks"][event].as_array().unwrap();
1618 assert_eq!(
1619 arr.len(),
1620 1,
1621 "event {event} must not be duplicated on re-run"
1622 );
1623 }
1624 assert!(v["hooks"].get("PreToolUse").is_none());
1625 }
1626
1627 #[test]
1628 fn install_codex_hooks_preserves_existing_user_hook() {
1629 let tmp = tempfile::tempdir().unwrap();
1630 let codex_dir = tmp.path().join(".codex");
1631 fs::create_dir_all(&codex_dir).unwrap();
1632 fs::write(
1635 codex_dir.join("hooks.json"),
1636 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1637 )
1638 .unwrap();
1639
1640 install_codex_hooks(tmp.path()).unwrap();
1641
1642 let v: serde_json::Value =
1643 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1644 .unwrap();
1645 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1647 .as_array()
1648 .unwrap()
1649 .iter()
1650 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1651 .collect();
1652 assert!(
1653 post_cmds.contains(&"my-own"),
1654 "user PostToolUse hook preserved"
1655 );
1656 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1657 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1659 .as_array()
1660 .unwrap()
1661 .iter()
1662 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1663 .collect();
1664 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1665 }
1666
1667 #[test]
1668 fn validate_init_flags_rejects_claude_settings_with_codex() {
1669 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1670 }
1671
1672 #[test]
1673 fn validate_init_flags_allows_codex_without_claude_settings() {
1674 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1675 }
1676
1677 #[test]
1678 fn validate_init_flags_allows_claude_with_claude_settings() {
1679 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1680 }
1681
1682 #[test]
1683 fn merge_hooks_into_file_rejects_parent_dir() {
1684 let tmp = tempfile::tempdir().unwrap();
1685 let bad = tmp.path().join("..").join("hooks.json");
1686 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1687 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1688 }
1689
1690 #[test]
1691 fn append_workspace_md_rejects_parent_dir() {
1692 let tmp = tempfile::tempdir().unwrap();
1693 let bad = tmp.path().join("..").join("AGENTS.md");
1694 let err = append_workspace_md(&bad).unwrap_err();
1695 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1696 }
1697
1698 #[tokio::test]
1699 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1700 let tmp = tempfile::tempdir().unwrap();
1701 let root = tmp.path();
1702 crate::test_helpers::init_git_repo(root);
1703
1704 let entry = init_in_directory(
1705 root,
1706 None,
1707 None,
1708 false,
1709 crate::config::UserContext::Toggle(false),
1710 crate::agent::Agent::Codex,
1711 )
1712 .await
1713 .unwrap();
1714
1715 assert!(root.join(".codex").join("hooks.json").exists());
1717 assert!(!root.join(".claude").join("settings.json").exists());
1718 assert_eq!(entry, ".codex/hooks.json");
1719
1720 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1722 assert!(gi.contains(".codex/hooks.json"));
1723 assert!(gi.contains(".tracevault/"));
1724 }
1725
1726 #[tokio::test]
1738 async fn init_in_directory_registers_repo_and_persists_repo_id() {
1739 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1740 let tmp = tempfile::tempdir().unwrap();
1741 let root = tmp.path();
1742 crate::test_helpers::init_git_repo(root);
1743 add_origin_remote(root, "git@github.com:org/repo.git");
1744
1745 let repo_id = "11111111-1111-4111-8111-111111111111";
1746 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
1747 let base = spawn_once(http_response("200 OK", &body));
1748
1749 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1750 _guard.set("XDG_CONFIG_HOME", tmp.path());
1751 _guard.set("TRACEVAULT_API_KEY", "tok");
1752 _guard.remove("TRACEVAULT_SERVER_URL");
1753
1754 init_in_directory(
1755 root,
1756 Some(&base),
1757 None,
1758 true,
1759 crate::config::UserContext::Toggle(false),
1760 crate::agent::Agent::Codex,
1761 )
1762 .await
1763 .unwrap();
1764
1765 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1766 assert_eq!(
1767 cfg.repo_id,
1768 Some(repo_id.to_string()),
1769 "successful registration must persist repo_id to config.toml"
1770 );
1771 }
1772
1773 #[tokio::test]
1779 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
1780 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1781 let tmp = tempfile::tempdir().unwrap();
1782 let root = tmp.path();
1783 crate::test_helpers::init_git_repo(root);
1784 add_origin_remote(root, "git@github.com:org/repo.git");
1785
1786 let base = spawn_once(http_response("403 Forbidden", ""));
1787
1788 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1789 _guard.set("XDG_CONFIG_HOME", tmp.path());
1790 _guard.set("TRACEVAULT_API_KEY", "tok");
1791 _guard.remove("TRACEVAULT_SERVER_URL");
1792
1793 let entry = init_in_directory(
1794 root,
1795 Some(&base),
1796 None,
1797 true,
1798 crate::config::UserContext::Toggle(false),
1799 crate::agent::Agent::Codex,
1800 )
1801 .await
1802 .expect("a registration failure (403) must not abort init itself");
1803 assert_eq!(entry, ".codex/hooks.json");
1804
1805 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1806 assert!(
1807 cfg.repo_id.is_none(),
1808 "a 403 registration failure must not persist a repo_id"
1809 );
1810 }
1811
1812 #[tokio::test]
1817 async fn registration_failure_message_flags_403_as_not_authorized() {
1818 let base = spawn_once(http_response("403 Forbidden", ""));
1819 let client = ApiClient::new(&base, Some("tok"));
1820 let err = client
1821 .register_repo(crate::api_client::RegisterRepoRequest {
1822 repo_name: "repo".into(),
1823 github_url: Some("git@github.com:org/repo.git".into()),
1824 })
1825 .await
1826 .unwrap_err();
1827 let msg = registration_failure_message(err.as_ref());
1828 assert!(
1829 msg.contains("not authorized"),
1830 "403 registration failure must surface a not-authorized message; got: {msg}"
1831 );
1832 }
1833
1834 #[tokio::test]
1837 async fn registration_failure_message_generic_for_non_403() {
1838 let base = spawn_once(http_response("500 Internal Server Error", ""));
1839 let client = ApiClient::new(&base, Some("tok"));
1840 let err = client
1841 .register_repo(crate::api_client::RegisterRepoRequest {
1842 repo_name: "repo".into(),
1843 github_url: Some("git@github.com:org/repo.git".into()),
1844 })
1845 .await
1846 .unwrap_err();
1847 let msg = registration_failure_message(err.as_ref());
1848 assert!(
1849 msg.contains("could not register repo on server"),
1850 "got: {msg}"
1851 );
1852 assert!(!msg.contains("not authorized"), "got: {msg}");
1853 }
1854
1855 #[tokio::test]
1860 async fn registration_failure_message_does_not_misclassify_403_in_body() {
1861 let base = spawn_once(http_response(
1862 "500 Internal Server Error",
1863 "upstream error 403 from proxy",
1864 ));
1865 let client = ApiClient::new(&base, Some("tok"));
1866 let err = client
1867 .register_repo(crate::api_client::RegisterRepoRequest {
1868 repo_name: "repo".into(),
1869 github_url: Some("git@github.com:org/repo.git".into()),
1870 })
1871 .await
1872 .unwrap_err();
1873 let msg = registration_failure_message(err.as_ref());
1874 assert!(
1875 !msg.contains("not authorized"),
1876 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
1877 );
1878 assert!(
1879 msg.contains("could not register repo on server"),
1880 "got: {msg}"
1881 );
1882 }
1883
1884 #[tokio::test]
1888 async fn registration_failure_message_flags_404_as_version_mismatch() {
1889 let base = spawn_once(http_response("404 Not Found", ""));
1890 let client = ApiClient::new(&base, Some("tok"));
1891 let err = client
1892 .register_repo(crate::api_client::RegisterRepoRequest {
1893 repo_name: "repo".into(),
1894 github_url: Some("git@github.com:org/repo.git".into()),
1895 })
1896 .await
1897 .unwrap_err();
1898 let msg = registration_failure_message(err.as_ref());
1899 assert!(
1900 msg.to_lowercase().contains("version mismatch"),
1901 "a 404 registration failure should hint at a version mismatch; got: {msg}"
1902 );
1903 }
1904}