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