1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use crate::resolution::git_remote_url;
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 parse_github_org(remote_url: &str) -> Option<String> {
65 if let Some(path) = remote_url.strip_prefix("git@github.com:") {
67 return path.split('/').next().map(String::from);
68 }
69 if let Some(path) = remote_url
71 .strip_prefix("https://github.com/")
72 .or_else(|| remote_url.strip_prefix("http://github.com/"))
73 {
74 return path.split('/').next().map(String::from);
75 }
76 None
77}
78
79fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
87 let output = std::process::Command::new("git")
88 .args(["rev-parse", "--git-dir", "--git-common-dir"])
89 .current_dir(dir)
90 .output()
91 .ok()?;
92 if !output.status.success() {
93 return None;
94 }
95 let stdout = String::from_utf8(output.stdout).ok()?;
96 let mut lines = stdout.lines();
97 let git_dir = lines.next()?.trim();
98 let git_common_dir = lines.next()?.trim();
99
100 let git_dir = dir.join(git_dir).canonicalize().ok()?;
103 let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
104
105 if git_dir == git_common_dir {
106 None } else {
108 git_common_dir.parent().map(Path::to_path_buf)
109 }
110}
111
112pub fn validate_init_flags(
118 agent: crate::agent::Agent,
119 claude_settings_set: bool,
120) -> Result<(), String> {
121 if matches!(
122 agent,
123 crate::agent::Agent::Codex | crate::agent::Agent::Gsd | crate::agent::Agent::OpenCode
124 ) && claude_settings_set
125 {
126 return Err("--claude-settings only applies to --agent claude-code".to_string());
127 }
128 Ok(())
129}
130
131pub async fn init_in_directory(
132 project_root: &Path,
133 server_url: Option<&str>,
134 claude_settings: Option<ClaudeSettingsTarget>,
135 no_gitignore: bool,
136 user_context: UserContext,
137 agent: crate::agent::Agent,
138) -> Result<String, io::Error> {
139 if !project_root.join(".git").exists() {
141 return Err(io::Error::new(
142 io::ErrorKind::NotFound,
143 "Not a git repository. Run 'git init' first.",
144 ));
145 }
146
147 if let Some(primary) = linked_worktree_primary(project_root) {
153 return Err(io::Error::new(
154 io::ErrorKind::Unsupported,
155 format!(
156 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
157 cd there and run it again — all worktrees share the primary's .tracevault/.",
158 primary.display()
159 ),
160 ));
161 }
162
163 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
166 {
167 crate::agent::Agent::ClaudeCode => {
168 let target = resolve_claude_target(claude_settings)?;
169 (Some(target), target.gitignore_entry().to_string())
170 }
171 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
172 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
178 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
183 };
184
185 let config_dir = TracevaultConfig::config_dir(project_root);
187 fs::create_dir_all(&config_dir)?;
188 fs::create_dir_all(config_dir.join("sessions"))?;
189 fs::create_dir_all(config_dir.join("cache"))?;
190 TracevaultConfig::ensure_gitignore(&config_dir)?;
193
194 if !no_gitignore {
196 update_root_gitignore(project_root, &hook_gitignore_entry)?;
197 }
198
199 let remote_url = git_remote_url(project_root);
201 if remote_url.is_none() {
202 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
203 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
204 }
205
206 let org_slug = remote_url.as_deref().and_then(parse_github_org);
208
209 let mut config = TracevaultConfig::default();
211 if let Some(url) = server_url {
212 config.server_url = Some(url.to_string());
213 }
214 config.org_slug = org_slug.clone();
215 config.user_context = Some(user_context);
216 fs::write(
217 TracevaultConfig::config_path(project_root),
218 config.to_toml(),
219 )?;
220
221 match agent {
223 crate::agent::Agent::ClaudeCode => {
224 let target =
226 claude_target.expect("claude settings target is resolved for the Claude agent");
227 install_claude_hooks(project_root, target)?;
228 }
229 crate::agent::Agent::Codex => install_codex_hooks(project_root)?,
230 crate::agent::Agent::Gsd => {
231 install_gsd_extension(Some(project_root))?;
239 }
240 crate::agent::Agent::OpenCode => {
241 install_opencode_plugin(Some(project_root))?;
242 }
243 }
244
245 install_git_hook(project_root)?;
247 install_post_commit_hook(project_root)?;
248
249 let detected = crate::hooks::detect_tools(project_root);
251 for tool in &detected {
252 println!(" Detected: {}", tool.name());
253 }
254
255 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
256 let effective_url = server_url.map(String::from).or(resolved_url);
257
258 if resolved_token.is_none() {
259 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
260 } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
261 let client = ApiClient::new(&url, resolved_token.as_deref());
262 let repo_name = git_repo_name(project_root);
263 let origin_url = remote.clone();
266
267 match client
268 .register_repo(
269 &slug,
270 crate::api_client::RegisterRepoRequest {
271 repo_name,
272 github_url: Some(remote),
273 },
274 )
275 .await
276 {
277 Ok(resp) => {
278 println!("Repo registered on server (id: {})", resp.repo_id);
279 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
281 cfg.repo_id = Some(resp.repo_id.to_string());
282 if let Ok(Some(remote)) = client.resolve_remote(&slug, &origin_url).await {
288 println!(
289 "{}",
290 crate::resolution::codebase_line(
291 remote.name.as_deref(),
292 &remote.normalized_url,
293 &remote.clone_status
294 )
295 );
296 cfg.remote_id = Some(remote.remote_id.to_string());
297 cfg.codebase_name = remote.name.clone();
298 }
299 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
300 }
301 }
302 Err(e) => {
303 let msg = e.to_string();
304 if msg.contains("404") {
305 eprintln!("Warning: organization '{}' not found on the server.", slug);
306 eprintln!(
307 "Create it first at your TraceVault instance, then run 'tracevault sync'."
308 );
309 } else if msg.contains("403") {
310 eprintln!("Warning: you are not a member of organization '{}'.", slug);
311 } else {
312 eprintln!("Warning: could not register repo on server: {e}");
313 }
314 }
315 }
316 }
317
318 Ok(hook_gitignore_entry)
319}
320
321fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
322 let path = project_root.join(".gitignore");
323 let existing = if path.exists() {
324 fs::read_to_string(&path)?
325 } else {
326 String::new()
327 };
328
329 let needed: Vec<&str> = [".tracevault/", settings_entry]
335 .iter()
336 .copied()
337 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
338 .collect();
339
340 if needed.is_empty() {
341 return Ok(());
342 }
343
344 let mut content = existing;
345 if !content.is_empty() && !content.ends_with('\n') {
346 content.push('\n');
347 }
348 content.push_str("\n# TraceVault — local only, do not commit\n");
349 for entry in needed {
350 content.push_str(entry);
351 content.push('\n');
352 }
353
354 fs::write(path, content)
355}
356
357fn git_repo_name(project_root: &Path) -> String {
358 std::process::Command::new("git")
359 .args(["rev-parse", "--show-toplevel"])
360 .current_dir(project_root)
361 .output()
362 .ok()
363 .filter(|o| o.status.success())
364 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
365 .as_deref()
366 .and_then(|p| p.rsplit('/').next())
367 .map(String::from)
368 .unwrap_or_else(|| "unknown".into())
369}
370
371const HOOK_MARKER: &str = "# tracevault:enforce";
372const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
373
374fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
375 let hooks_dir = project_root.join(".git/hooks");
376 fs::create_dir_all(&hooks_dir)?;
377
378 let hook_path = hooks_dir.join("pre-push");
379 let tracevault_block = format!(
380 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
381 );
382
383 if hook_path.exists() {
384 let existing = fs::read_to_string(&hook_path)?;
385
386 if existing.contains(HOOK_MARKER) {
388 return Ok(());
389 }
390
391 if existing.contains(OLD_HOOK_MARKER) {
393 let mut new_content = String::new();
394 let mut skip = false;
395 for line in existing.lines() {
396 if line.contains(OLD_HOOK_MARKER) {
397 skip = true;
398 continue;
399 }
400 if skip {
401 if line.starts_with("tracevault ") {
403 continue;
404 }
405 skip = false;
406 }
407 new_content.push_str(line);
408 new_content.push('\n');
409 }
410 if !new_content.ends_with('\n') {
411 new_content.push('\n');
412 }
413 new_content.push_str(&tracevault_block);
414 fs::write(&hook_path, new_content)?;
415 } else {
416 let mut content = existing;
418 if !content.ends_with('\n') {
419 content.push('\n');
420 }
421 content.push_str(&tracevault_block);
422 fs::write(&hook_path, content)?;
423 }
424 } else {
425 let content = format!("#!/bin/sh\n{tracevault_block}");
426 fs::write(&hook_path, content)?;
427 }
428
429 #[cfg(unix)]
431 {
432 use std::os::unix::fs::PermissionsExt;
433 let mut perms = fs::metadata(&hook_path)?.permissions();
434 perms.set_mode(0o755);
435 fs::set_permissions(&hook_path, perms)?;
436 }
437
438 Ok(())
439}
440
441const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
442
443fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
444 let hooks_dir = project_root.join(".git/hooks");
445 fs::create_dir_all(&hooks_dir)?;
446
447 let hook_path = hooks_dir.join("post-commit");
448 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
449
450 if hook_path.exists() {
451 let existing = fs::read_to_string(&hook_path)?;
452
453 if existing.contains(POST_COMMIT_MARKER) {
454 return Ok(());
455 }
456
457 let mut content = existing;
458 if !content.ends_with('\n') {
459 content.push('\n');
460 }
461 content.push_str(&tracevault_block);
462 fs::write(&hook_path, content)?;
463 } else {
464 let content = format!("#!/bin/sh\n{tracevault_block}");
465 fs::write(&hook_path, content)?;
466 }
467
468 #[cfg(unix)]
469 {
470 use std::os::unix::fs::PermissionsExt;
471 let mut perms = fs::metadata(&hook_path)?.permissions();
472 perms.set_mode(0o755);
473 fs::set_permissions(&hook_path, perms)?;
474 }
475
476 Ok(())
477}
478
479fn install_claude_hooks(
480 project_root: &Path,
481 target: ClaudeSettingsTarget,
482) -> Result<(), io::Error> {
483 let claude_dir = project_root.join(".claude");
484 fs::create_dir_all(&claude_dir)?;
485
486 let filename = target.filename();
487 let settings_path = claude_dir.join(filename);
488 let mut settings: serde_json::Value = if settings_path.exists() {
489 let content = fs::read_to_string(&settings_path)?;
490 serde_json::from_str(&content).map_err(|e| {
491 io::Error::new(
492 io::ErrorKind::InvalidData,
493 format!("Failed to parse .claude/{filename}: {e}"),
494 )
495 })?
496 } else {
497 serde_json::json!({})
498 };
499
500 let hooks = tracevault_hooks();
501
502 let settings_obj = settings.as_object_mut().ok_or_else(|| {
504 io::Error::new(
505 io::ErrorKind::InvalidData,
506 format!(".claude/{filename} is not a JSON object"),
507 )
508 })?;
509
510 settings_obj.insert("hooks".to_string(), hooks);
511
512 let formatted = serde_json::to_string_pretty(&settings)
513 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
514 fs::write(&settings_path, formatted)?;
515
516 Ok(())
517}
518
519pub fn tracevault_hooks() -> serde_json::Value {
520 serde_json::json!({
521 "PreToolUse": [{
522 "matcher": "Write|Edit|Bash",
523 "hooks": [{
524 "type": "command",
525 "command": "tracevault stream --event pre-tool-use",
526 "timeout": 10,
527 "statusMessage": "TraceVault: streaming pre-tool event"
528 }]
529 }],
530 "PostToolUse": [{
531 "matcher": "",
532 "hooks": [{
533 "type": "command",
534 "command": "tracevault stream --event post-tool-use",
535 "timeout": 10,
536 "statusMessage": "TraceVault: streaming post-tool event"
537 }]
538 }],
539 "Notification": [{
540 "matcher": "",
541 "hooks": [{
542 "type": "command",
543 "command": "tracevault stream --event notification",
544 "timeout": 10,
545 "statusMessage": "TraceVault: streaming notification"
546 }]
547 }],
548 "Stop": [{
549 "matcher": "",
550 "hooks": [{
551 "type": "command",
552 "command": "tracevault stream --event stop",
553 "timeout": 10,
554 "statusMessage": "TraceVault: finalizing session"
555 }]
556 }],
557 "SessionStart": [{
558 "matcher": "",
559 "hooks": [{
560 "type": "command",
561 "command": "tracevault session-start",
562 "timeout": 10,
563 "statusMessage": "TraceVault: session start"
564 }]
565 }],
566 "UserPromptSubmit": [{
567 "matcher": "",
568 "hooks": [{
569 "type": "command",
570 "command": "tracevault user-prompt",
571 "timeout": 10,
572 "statusMessage": "TraceVault: policy reinforcement"
573 }]
574 }]
575 })
576}
577
578pub fn codex_hooks() -> serde_json::Value {
589 serde_json::json!({
590 "SessionStart": [{
591 "matcher": "",
592 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
593 }],
594 "UserPromptSubmit": [{
595 "matcher": "",
596 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
597 }],
598 "PostToolUse": [{
599 "matcher": "",
600 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
601 }],
602 "Stop": [{
603 "matcher": "",
604 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
605 }]
606 })
607}
608
609const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
613const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
614const GSD_EXT_MANIFEST_JSON: &str =
615 include_str!("../../assets/gsd-extension/extension-manifest.json");
616
617fn gsd_extension_source_dir() -> io::Result<PathBuf> {
621 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
622 let config_dir = config_dir
623 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
624 Ok(config_dir.join("tracevault").join("gsd-extension"))
625}
626
627pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
651 let home =
652 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
653 let gsd_home = home.join(".gsd");
654
655 let source_dir = gsd_extension_source_dir()?;
656 fs::create_dir_all(&source_dir)?;
657 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
658 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
659 fs::write(
660 source_dir.join("extension-manifest.json"),
661 GSD_EXT_MANIFEST_JSON,
662 )?;
663
664 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
668 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
669 }
670
671 let local_flag = project_root.is_some();
675 let mut cmd = std::process::Command::new("gsd");
676 cmd.arg("install").arg(&source_dir);
677 if let Some(root) = project_root {
678 cmd.arg("-l");
679 cmd.current_dir(root);
680 }
681
682 let retry_hint = format!(
683 "gsd install {}{}",
684 source_dir.display(),
685 if local_flag { " -l" } else { "" }
686 );
687
688 match cmd.output() {
689 Ok(output) if output.status.success() => {
690 println!(
691 "TraceVault: installed and registered the GSD extension ({}).",
692 source_dir.display()
693 );
694 }
695 Ok(output) => {
696 eprintln!(
697 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
698 source_dir.display(),
699 String::from_utf8_lossy(&output.stderr),
700 );
701 }
702 Err(e) => {
703 eprintln!(
704 "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.",
705 source_dir.display(),
706 );
707 }
708 }
709
710 Ok(())
711}
712
713const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
716
717pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
733 let plugins_dir = match project_root {
734 Some(root) => root.join(".opencode").join("plugins"),
735 None => {
736 let config_dir =
737 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
738 config_dir
739 .ok_or_else(|| {
740 io::Error::new(
741 io::ErrorKind::NotFound,
742 "could not determine the config directory for the OpenCode plugin install",
743 )
744 })?
745 .join("opencode")
746 .join("plugins")
747 }
748 };
749
750 write_opencode_plugin_files(&plugins_dir)
751}
752
753fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
754 fs::create_dir_all(plugins_dir)?;
755 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
756 Ok(())
757}
758
759pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
771 let ext_root = gsd_home.join("extensions");
772 let reg_path = ext_root.join("registry.json");
773
774 let reg: Option<serde_json::Value> = if reg_path.exists() {
779 let content = fs::read_to_string(®_path)?;
780 let parsed: serde_json::Value = match serde_json::from_str(&content) {
781 Ok(v) => v,
782 Err(_) => return Ok(()), };
784 let corrupt = match parsed.as_object() {
785 None => true,
786 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
787 };
788 if corrupt {
789 return Ok(()); }
791 Some(parsed)
792 } else {
793 None
794 };
795
796 let stale = ext_root.join("tracevault-tracker");
798 if stale.exists() {
799 fs::remove_dir_all(&stale)?;
800 }
801
802 if let Some(mut reg) = reg {
804 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
805 let removed_tracker = entries.remove("tracevault-tracker").is_some();
806 let removed_inert = entries.remove("tracevault").is_some();
807 if removed_tracker || removed_inert {
808 let tmp = reg_path.with_extension("json.tmp");
810 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
811 fs::rename(&tmp, ®_path)?;
812 }
813 }
814 }
815 Ok(())
816}
817
818fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
828 if hooks_path
833 .components()
834 .any(|c| c == std::path::Component::ParentDir)
835 {
836 return Err(io::Error::new(
837 io::ErrorKind::InvalidInput,
838 format!("refusing to use path with '..': {}", hooks_path.display()),
839 ));
840 }
841 let mut root: serde_json::Value = if hooks_path.exists() {
842 let content = fs::read_to_string(hooks_path)?;
843 serde_json::from_str(&content).map_err(|e| {
844 io::Error::new(
845 io::ErrorKind::InvalidData,
846 format!("Failed to parse {}: {e}", hooks_path.display()),
847 )
848 })?
849 } else {
850 serde_json::json!({})
851 };
852
853 merge_hooks(&mut root, ours, hooks_path)?;
854
855 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
856 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
857 })?;
858 let tmp = hooks_path.with_extension("json.tmp");
859 fs::write(&tmp, formatted)?;
860 fs::rename(&tmp, hooks_path)?;
861 Ok(())
862}
863
864pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
868 let codex_dir = project_root.join(".codex");
869 fs::create_dir_all(&codex_dir)?;
870 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
871}
872
873pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
880 fs::create_dir_all(codex_dir)?;
881 let base = codex_dir.canonicalize()?;
883 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
884 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
885}
886
887const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
891
892const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
893<!-- tracevault:workspace-mode -->
894## TraceVault (workspace mode)
895You may be running detached from any single repository. Before working on a repo, run
896`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
897output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
898already be registered with TraceVault.
899";
900
901fn append_workspace_md(md_path: &Path) -> io::Result<()> {
907 if md_path
909 .components()
910 .any(|c| c == std::path::Component::ParentDir)
911 {
912 return Err(io::Error::new(
913 io::ErrorKind::InvalidInput,
914 format!("refusing to use path with '..': {}", md_path.display()),
915 ));
916 }
917 let existing = if md_path.exists() {
918 fs::read_to_string(md_path)?
919 } else {
920 String::new()
921 };
922 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
923 return Ok(());
924 }
925 let mut content = existing;
926 if !content.is_empty() && !content.ends_with('\n') {
927 content.push('\n');
928 }
929 if !content.is_empty() {
930 content.push('\n');
931 }
932 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
933 fs::write(md_path, content)
934}
935
936fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
940 let joined = base.join(name);
941 if joined.parent() != Some(base) {
942 return Err(io::Error::new(
943 io::ErrorKind::InvalidInput,
944 format!(
945 "refusing to access path outside {}: {}",
946 base.display(),
947 joined.display()
948 ),
949 ));
950 }
951 Ok(joined)
952}
953
954fn merge_hooks(
967 settings: &mut serde_json::Value,
968 ours: &serde_json::Value,
969 path: &Path,
970) -> io::Result<()> {
971 if settings.is_null() {
972 *settings = serde_json::json!({});
973 }
974 let settings_obj = settings.as_object_mut().ok_or_else(|| {
975 io::Error::new(
976 io::ErrorKind::InvalidData,
977 format!("{} is not a JSON object", path.display()),
978 )
979 })?;
980
981 let hooks_value = settings_obj
982 .entry("hooks")
983 .or_insert_with(|| serde_json::json!({}));
984 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
985 io::Error::new(
986 io::ErrorKind::InvalidData,
987 format!("{} \"hooks\" key is not a JSON object", path.display()),
988 )
989 })?;
990
991 let Some(ours_obj) = ours.as_object() else {
992 return Ok(());
993 };
994
995 for (event, our_array) in ours_obj {
996 let Some(our_entries) = our_array.as_array() else {
997 continue;
998 };
999
1000 let existing_value = hooks_obj
1001 .entry(event.clone())
1002 .or_insert_with(|| serde_json::json!([]));
1003 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1004 io::Error::new(
1005 io::ErrorKind::InvalidData,
1006 format!(
1007 "{} \"hooks\".\"{event}\" is not a JSON array",
1008 path.display()
1009 ),
1010 )
1011 })?;
1012
1013 for our_entry in our_entries {
1014 let our_command = entry_command(our_entry);
1015 let already_present = existing_array
1016 .iter()
1017 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1018 if !already_present {
1019 existing_array.push(our_entry.clone());
1020 }
1021 }
1022 }
1023
1024 Ok(())
1025}
1026
1027fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1030 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1031}
1032
1033fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1038 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1039 return false;
1040 };
1041 hooks
1042 .iter()
1043 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1044}
1045
1046pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1052 fs::create_dir_all(claude_dir)?;
1053
1054 let base = claude_dir.canonicalize()?;
1057
1058 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1060
1061 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1063}
1064
1065pub fn write_global_user_config_in(
1075 config_root: &Path,
1076 requested: Option<UserContext>,
1077) -> io::Result<Option<PathBuf>> {
1078 fs::create_dir_all(config_root)?;
1079 let mut config = crate::config::try_load_user_config_in(config_root)
1081 .ok()
1082 .flatten()
1083 .unwrap_or_default();
1084 let user_context = requested
1086 .or_else(|| config.user_context.clone())
1087 .unwrap_or(UserContext::Toggle(true));
1088 let active = user_context
1089 .resolve()
1090 .map(|_| user_context.path_in(config_root));
1091 config.user_context = Some(user_context);
1092 fs::write(user_config_path_in(config_root), config.to_toml())?;
1093 if let Some(ref ctx_path) = active {
1094 if !ctx_path.exists() {
1095 Context::default().save_to(ctx_path)?;
1096 }
1097 }
1098 Ok(active)
1099}
1100
1101#[cfg(test)]
1102mod tests {
1103 use super::*;
1104
1105 #[test]
1106 fn linked_worktree_primary_detects_linked_and_primary() {
1107 let tmp = tempfile::tempdir().unwrap();
1108 let repo = tmp.path().join("repo");
1109 let wt = tmp.path().join("linked-wt");
1110 std::fs::create_dir_all(&repo).unwrap();
1111 crate::test_helpers::init_git_repo(&repo);
1112 crate::test_helpers::add_worktree(&repo, &wt);
1113
1114 assert!(
1116 linked_worktree_primary(&repo).is_none(),
1117 "primary checkout must not be flagged as a linked worktree"
1118 );
1119 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1121 assert_eq!(
1122 primary.canonicalize().unwrap(),
1123 repo.canonicalize().unwrap(),
1124 "must resolve to the primary repo root"
1125 );
1126 }
1127
1128 #[test]
1129 fn linked_worktree_primary_none_for_non_git() {
1130 let tmp = tempfile::tempdir().unwrap();
1131 assert!(
1132 linked_worktree_primary(tmp.path()).is_none(),
1133 "a non-git directory is not a linked worktree"
1134 );
1135 }
1136
1137 #[test]
1138 fn parse_github_org_ssh() {
1139 assert_eq!(
1140 parse_github_org("git@github.com:myorg/myrepo.git"),
1141 Some("myorg".into())
1142 );
1143 }
1144
1145 #[test]
1146 fn parse_github_org_https() {
1147 assert_eq!(
1148 parse_github_org("https://github.com/myorg/myrepo"),
1149 Some("myorg".into())
1150 );
1151 }
1152
1153 #[test]
1154 fn parse_github_org_non_github_returns_none() {
1155 assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
1156 }
1157
1158 #[test]
1159 fn parse_github_org_invalid() {
1160 assert_eq!(parse_github_org("not-a-url"), None);
1161 }
1162
1163 #[test]
1164 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1165 let mut settings = serde_json::json!({});
1166 let ours = tracevault_hooks();
1167 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1168
1169 let hooks = settings.get("hooks").unwrap();
1170 for event in [
1171 "PreToolUse",
1172 "PostToolUse",
1173 "Notification",
1174 "Stop",
1175 "SessionStart",
1176 "UserPromptSubmit",
1177 ] {
1178 assert!(hooks.get(event).is_some(), "missing event {event}");
1179 }
1180 }
1181
1182 #[test]
1183 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1184 let mut settings = serde_json::json!({
1185 "model": "opus",
1186 "hooks": {
1187 "PreToolUse": [{
1188 "matcher": "",
1189 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1190 }]
1191 }
1192 });
1193 let ours = tracevault_hooks();
1194 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1195
1196 assert_eq!(settings.get("model").unwrap(), "opus");
1198
1199 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1200 assert_eq!(pre_tool_use.len(), 2);
1202 let commands: Vec<&str> = pre_tool_use
1203 .iter()
1204 .map(|e| entry_command(e).unwrap())
1205 .collect();
1206 assert!(commands.contains(&"my-own-hook"));
1207 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1208
1209 assert!(settings["hooks"]["SessionStart"].is_array());
1211 }
1212
1213 #[test]
1214 fn merge_hooks_is_idempotent() {
1215 let mut settings = serde_json::json!({});
1216 let ours = tracevault_hooks();
1217 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1218 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1219
1220 for event in [
1221 "PreToolUse",
1222 "PostToolUse",
1223 "Notification",
1224 "Stop",
1225 "SessionStart",
1226 "UserPromptSubmit",
1227 ] {
1228 let arr = settings["hooks"][event].as_array().unwrap();
1229 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1230 }
1231 }
1232
1233 #[test]
1234 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1235 let mut settings = serde_json::json!({
1239 "hooks": {
1240 "PreToolUse": [{
1241 "matcher": "Write|Edit|Bash",
1242 "hooks": [
1243 { "type": "command", "command": "other" },
1244 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1245 ]
1246 }]
1247 }
1248 });
1249 let ours = tracevault_hooks();
1250 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1251
1252 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1253 assert_eq!(
1254 pre_tool_use.len(),
1255 1,
1256 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1257 );
1258 }
1259
1260 #[test]
1261 fn merge_hooks_errors_on_non_object_top_level() {
1262 let mut settings = serde_json::json!([1, 2, 3]);
1263 let ours = tracevault_hooks();
1264 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1265 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1266 assert!(err.to_string().contains("settings.json"));
1267 }
1268
1269 #[test]
1270 fn merge_hooks_errors_on_non_object_top_level_number() {
1271 let mut settings = serde_json::json!(42);
1272 let ours = tracevault_hooks();
1273 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1274 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1275 }
1276
1277 #[test]
1278 fn merge_hooks_errors_on_non_object_hooks() {
1279 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1280 let ours = tracevault_hooks();
1281 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1282 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1283 assert!(err.to_string().contains("hooks"));
1284 }
1285
1286 #[test]
1287 fn merge_hooks_errors_on_non_array_event_value() {
1288 let mut settings = serde_json::json!({
1289 "hooks": {
1290 "PreToolUse": "not-an-array"
1291 }
1292 });
1293 let ours = tracevault_hooks();
1294 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1295 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1296 assert!(err.to_string().contains("PreToolUse"));
1297 }
1298
1299 #[test]
1300 fn install_global_hooks_writes_settings_and_claude_md() {
1301 let tmp = tempfile::tempdir().unwrap();
1302 let claude_dir = tmp.path().join(".claude");
1303
1304 install_global_hooks(&claude_dir).unwrap();
1305
1306 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1307 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1308 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1309 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1310 }
1311
1312 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1313 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1314 }
1315
1316 #[test]
1317 fn install_global_hooks_is_idempotent() {
1318 let tmp = tempfile::tempdir().unwrap();
1319 let claude_dir = tmp.path().join(".claude");
1320
1321 install_global_hooks(&claude_dir).unwrap();
1322 install_global_hooks(&claude_dir).unwrap();
1323
1324 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1325 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1326 for event in [
1327 "PreToolUse",
1328 "PostToolUse",
1329 "Notification",
1330 "Stop",
1331 "SessionStart",
1332 "UserPromptSubmit",
1333 ] {
1334 let arr = settings["hooks"][event].as_array().unwrap();
1335 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1336 }
1337
1338 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1339 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1340 assert_eq!(
1341 marker_count, 1,
1342 "CLAUDE.md marker should appear exactly once"
1343 );
1344 }
1345
1346 #[test]
1347 fn install_global_hooks_preserves_existing_claude_md_content() {
1348 let tmp = tempfile::tempdir().unwrap();
1349 let claude_dir = tmp.path().join(".claude");
1350 fs::create_dir_all(&claude_dir).unwrap();
1351 fs::write(
1352 claude_dir.join("CLAUDE.md"),
1353 "# My existing notes\nSome content.\n",
1354 )
1355 .unwrap();
1356
1357 install_global_hooks(&claude_dir).unwrap();
1358
1359 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1360 assert!(claude_md.contains("# My existing notes"));
1361 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1362 }
1363
1364 #[test]
1365 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1366 let tmp = tempfile::tempdir().unwrap();
1367 let claude_dir = tmp.path().join(".claude");
1368
1369 install_global_hooks(&claude_dir).unwrap();
1370
1371 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1372 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1373 assert!(settings["hooks"].get("SessionStart").is_some());
1374
1375 let leftover = fs::read_dir(&claude_dir)
1376 .unwrap()
1377 .filter_map(|e| e.ok())
1378 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1379 assert!(
1380 !leftover,
1381 "no settings.json.tmp should remain after install"
1382 );
1383 }
1384
1385 #[test]
1386 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1387 let tmp = tempfile::tempdir().unwrap();
1388 let claude_dir = tmp.path().join(".claude");
1389 fs::create_dir_all(&claude_dir).unwrap();
1390 let settings_path = claude_dir.join("settings.json");
1391 let original = "[1, 2, 3]";
1392 fs::write(&settings_path, original).unwrap();
1393
1394 let err = install_global_hooks(&claude_dir).unwrap_err();
1395 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1396
1397 let after = fs::read_to_string(&settings_path).unwrap();
1400 assert_eq!(after, original);
1401 let leftover = fs::read_dir(&claude_dir)
1402 .unwrap()
1403 .filter_map(|e| e.ok())
1404 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1405 assert!(!leftover, "no tmp file should be left behind on error");
1406 }
1407
1408 #[test]
1409 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1410 let tmp = tempfile::tempdir().unwrap();
1411 let claude_dir = tmp.path().join(".claude");
1412 fs::create_dir_all(&claude_dir).unwrap();
1413 let settings_path = claude_dir.join("settings.json");
1414 let original = r#"{"hooks": "oops"}"#;
1415 fs::write(&settings_path, original).unwrap();
1416
1417 let err = install_global_hooks(&claude_dir).unwrap_err();
1418 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1419
1420 let after = fs::read_to_string(&settings_path).unwrap();
1421 assert_eq!(after, original);
1422 }
1423
1424 #[test]
1425 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1426 let tmp = tempfile::tempdir().unwrap();
1427 let claude_dir = tmp.path().join(".claude");
1428 fs::create_dir_all(&claude_dir).unwrap();
1429 let settings_path = claude_dir.join("settings.json");
1430 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1431 fs::write(&settings_path, original).unwrap();
1432
1433 let err = install_global_hooks(&claude_dir).unwrap_err();
1434 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1435
1436 let after = fs::read_to_string(&settings_path).unwrap();
1437 assert_eq!(after, original);
1438 }
1439
1440 #[test]
1441 fn safe_join_allows_direct_child_file() {
1442 let tmp = tempfile::tempdir().unwrap();
1443 let base = tmp.path();
1444 let result = safe_join(base, "settings.json").unwrap();
1445 assert_eq!(result.parent(), Some(base));
1446 assert_eq!(result.file_name().unwrap(), "settings.json");
1447 }
1448
1449 #[test]
1450 fn safe_join_rejects_path_traversal() {
1451 let tmp = tempfile::tempdir().unwrap();
1452 let base = tmp.path();
1453 let result = safe_join(base, "../evil");
1454 assert!(result.is_err());
1455 let err = result.unwrap_err();
1456 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1457 assert!(err.to_string().contains("refusing to access path outside"));
1458 }
1459
1460 #[test]
1461 fn safe_join_rejects_absolute_path() {
1462 let tmp = tempfile::tempdir().unwrap();
1463 let base = tmp.path();
1464 let result = safe_join(base, "/etc/passwd");
1465 assert!(result.is_err());
1468 }
1469
1470 #[test]
1471 fn write_global_user_config_enables_and_creates_context() {
1472 let root = tempfile::tempdir().unwrap();
1473 let active = write_global_user_config_in(root.path(), None).unwrap();
1474 let cfg = crate::config::try_load_user_config_in(root.path())
1475 .unwrap()
1476 .unwrap();
1477 assert_eq!(
1480 cfg.user_context.unwrap().resolve_in(root.path()),
1481 Some(crate::config::default_user_context_path_in(root.path()))
1482 );
1483 let ctx = crate::config::default_user_context_path_in(root.path());
1484 assert_eq!(active, Some(ctx.clone()));
1485 assert!(ctx.exists());
1486 }
1487
1488 #[test]
1489 fn write_global_user_config_can_disable() {
1490 let root = tempfile::tempdir().unwrap();
1491 let active = write_global_user_config_in(
1492 root.path(),
1493 Some(crate::config::UserContext::Toggle(false)),
1494 )
1495 .unwrap();
1496 let cfg = crate::config::try_load_user_config_in(root.path())
1497 .unwrap()
1498 .unwrap();
1499 assert!(matches!(
1500 cfg.user_context,
1501 Some(crate::config::UserContext::Toggle(false))
1502 ));
1503 assert_eq!(active, None, "disabled → no active context path");
1504 assert!(
1506 !crate::config::default_user_context_path_in(root.path()).exists(),
1507 "disabled user context must not create a context.json"
1508 );
1509 }
1510
1511 #[test]
1512 fn write_global_user_config_custom_path_seeds_that_file_only() {
1513 let root = tempfile::tempdir().unwrap();
1514 let custom = root.path().join("custom-ctx.json");
1515 let active = write_global_user_config_in(
1516 root.path(),
1517 Some(crate::config::UserContext::Path(
1518 custom.to_string_lossy().into_owned(),
1519 )),
1520 )
1521 .unwrap();
1522 assert_eq!(active, Some(custom.clone()));
1523 assert!(custom.exists(), "the configured custom path must be seeded");
1524 assert!(
1525 !crate::config::default_user_context_path_in(root.path()).exists(),
1526 "the default context.json must NOT be created when a custom path is configured"
1527 );
1528 }
1529
1530 #[test]
1531 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1532 let root = tempfile::tempdir().unwrap();
1533 let custom = root.path().join("custom-ctx.json");
1534 write_global_user_config_in(
1536 root.path(),
1537 Some(crate::config::UserContext::Path(
1538 custom.to_string_lossy().into_owned(),
1539 )),
1540 )
1541 .unwrap();
1542 let active = write_global_user_config_in(root.path(), None).unwrap();
1544 assert_eq!(
1545 active,
1546 Some(custom.clone()),
1547 "re-run without flags must preserve the custom path"
1548 );
1549 let cfg = crate::config::try_load_user_config_in(root.path())
1550 .unwrap()
1551 .unwrap();
1552 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1553 }
1554
1555 #[test]
1556 fn install_global_codex_hooks_writes_and_is_idempotent() {
1557 let tmp = tempfile::tempdir().unwrap();
1558 let codex_dir = tmp.path().join(".codex");
1559
1560 install_global_codex_hooks(&codex_dir).unwrap();
1561 install_global_codex_hooks(&codex_dir).unwrap();
1562
1563 let v: serde_json::Value =
1564 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1565 .unwrap();
1566 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1567 let arr = v["hooks"][event].as_array().unwrap();
1568 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1569 }
1570 assert!(v["hooks"].get("PreToolUse").is_none());
1571 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1573 assert_eq!(
1574 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1575 1,
1576 "AGENTS.md workspace-mode block must appear exactly once"
1577 );
1578 let leftover = fs::read_dir(&codex_dir)
1580 .unwrap()
1581 .filter_map(|e| e.ok())
1582 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1583 assert!(!leftover);
1584 }
1585
1586 #[test]
1587 fn codex_hooks_has_expected_events_and_commands() {
1588 let h = codex_hooks();
1589 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1590 assert!(h.get(event).is_some(), "missing codex event {event}");
1591 }
1592 assert!(h.get("PreToolUse").is_none());
1596 assert!(h.get("Notification").is_none());
1597 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1599 assert_eq!(
1600 cmd("PostToolUse"),
1601 "tracevault stream --event post-tool-use --agent codex"
1602 );
1603 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1604 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1605 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1606 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1608 }
1609
1610 #[test]
1611 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1612 let tmp = tempfile::tempdir().unwrap();
1613 install_codex_hooks(tmp.path()).unwrap();
1614 install_codex_hooks(tmp.path()).unwrap();
1615
1616 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1617 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1618 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1619 let arr = v["hooks"][event].as_array().unwrap();
1620 assert_eq!(
1621 arr.len(),
1622 1,
1623 "event {event} must not be duplicated on re-run"
1624 );
1625 }
1626 assert!(v["hooks"].get("PreToolUse").is_none());
1627 }
1628
1629 #[test]
1630 fn install_codex_hooks_preserves_existing_user_hook() {
1631 let tmp = tempfile::tempdir().unwrap();
1632 let codex_dir = tmp.path().join(".codex");
1633 fs::create_dir_all(&codex_dir).unwrap();
1634 fs::write(
1637 codex_dir.join("hooks.json"),
1638 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1639 )
1640 .unwrap();
1641
1642 install_codex_hooks(tmp.path()).unwrap();
1643
1644 let v: serde_json::Value =
1645 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1646 .unwrap();
1647 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1649 .as_array()
1650 .unwrap()
1651 .iter()
1652 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1653 .collect();
1654 assert!(
1655 post_cmds.contains(&"my-own"),
1656 "user PostToolUse hook preserved"
1657 );
1658 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1659 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1661 .as_array()
1662 .unwrap()
1663 .iter()
1664 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1665 .collect();
1666 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1667 }
1668
1669 #[test]
1670 fn validate_init_flags_rejects_claude_settings_with_codex() {
1671 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1672 }
1673
1674 #[test]
1675 fn validate_init_flags_allows_codex_without_claude_settings() {
1676 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1677 }
1678
1679 #[test]
1680 fn validate_init_flags_allows_claude_with_claude_settings() {
1681 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1682 }
1683
1684 #[test]
1685 fn merge_hooks_into_file_rejects_parent_dir() {
1686 let tmp = tempfile::tempdir().unwrap();
1687 let bad = tmp.path().join("..").join("hooks.json");
1688 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1689 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1690 }
1691
1692 #[test]
1693 fn append_workspace_md_rejects_parent_dir() {
1694 let tmp = tempfile::tempdir().unwrap();
1695 let bad = tmp.path().join("..").join("AGENTS.md");
1696 let err = append_workspace_md(&bad).unwrap_err();
1697 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1698 }
1699
1700 #[tokio::test]
1701 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1702 let tmp = tempfile::tempdir().unwrap();
1703 let root = tmp.path();
1704 crate::test_helpers::init_git_repo(root);
1705
1706 let entry = init_in_directory(
1707 root,
1708 None,
1709 None,
1710 false,
1711 crate::config::UserContext::Toggle(false),
1712 crate::agent::Agent::Codex,
1713 )
1714 .await
1715 .unwrap();
1716
1717 assert!(root.join(".codex").join("hooks.json").exists());
1719 assert!(!root.join(".claude").join("settings.json").exists());
1720 assert_eq!(entry, ".codex/hooks.json");
1721
1722 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1724 assert!(gi.contains(".codex/hooks.json"));
1725 assert!(gi.contains(".tracevault/"));
1726 }
1727}