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!(
373 "{HOOK_MARKER}\n\
374 # Capture git's pre-push ref list once; `check` uses it to determine\n\
375 # which files are being pushed.\n\
376 tracevault_prepush_stdin=$(cat)\n\
377 tracevault sync 2>/dev/null || true\n\
378 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
379 );
380
381 if hook_path.exists() {
382 let existing = fs::read_to_string(&hook_path)?;
383
384 if existing.contains(HOOK_MARKER) {
386 return Ok(());
387 }
388
389 if existing.contains(OLD_HOOK_MARKER) {
391 let mut new_content = String::new();
392 let mut skip = false;
393 for line in existing.lines() {
394 if line.contains(OLD_HOOK_MARKER) {
395 skip = true;
396 continue;
397 }
398 if skip {
399 if line.starts_with("tracevault ") {
401 continue;
402 }
403 skip = false;
404 }
405 new_content.push_str(line);
406 new_content.push('\n');
407 }
408 if !new_content.ends_with('\n') {
409 new_content.push('\n');
410 }
411 new_content.push_str(&tracevault_block);
412 fs::write(&hook_path, new_content)?;
413 } else {
414 let mut content = existing;
416 if !content.ends_with('\n') {
417 content.push('\n');
418 }
419 content.push_str(&tracevault_block);
420 fs::write(&hook_path, content)?;
421 }
422 } else {
423 let content = format!("#!/bin/sh\n{tracevault_block}");
424 fs::write(&hook_path, content)?;
425 }
426
427 #[cfg(unix)]
429 {
430 use std::os::unix::fs::PermissionsExt;
431 let mut perms = fs::metadata(&hook_path)?.permissions();
432 perms.set_mode(0o755);
433 fs::set_permissions(&hook_path, perms)?;
434 }
435
436 Ok(())
437}
438
439const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
440
441fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
442 let hooks_dir = project_root.join(".git/hooks");
443 fs::create_dir_all(&hooks_dir)?;
444
445 let hook_path = hooks_dir.join("post-commit");
446 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
447
448 if hook_path.exists() {
449 let existing = fs::read_to_string(&hook_path)?;
450
451 if existing.contains(POST_COMMIT_MARKER) {
452 return Ok(());
453 }
454
455 let mut content = existing;
456 if !content.ends_with('\n') {
457 content.push('\n');
458 }
459 content.push_str(&tracevault_block);
460 fs::write(&hook_path, content)?;
461 } else {
462 let content = format!("#!/bin/sh\n{tracevault_block}");
463 fs::write(&hook_path, content)?;
464 }
465
466 #[cfg(unix)]
467 {
468 use std::os::unix::fs::PermissionsExt;
469 let mut perms = fs::metadata(&hook_path)?.permissions();
470 perms.set_mode(0o755);
471 fs::set_permissions(&hook_path, perms)?;
472 }
473
474 Ok(())
475}
476
477fn install_claude_hooks(
478 project_root: &Path,
479 target: ClaudeSettingsTarget,
480) -> Result<(), io::Error> {
481 let claude_dir = project_root.join(".claude");
482 fs::create_dir_all(&claude_dir)?;
483
484 let filename = target.filename();
485 let settings_path = claude_dir.join(filename);
486 let mut settings: serde_json::Value = if settings_path.exists() {
487 let content = fs::read_to_string(&settings_path)?;
488 serde_json::from_str(&content).map_err(|e| {
489 io::Error::new(
490 io::ErrorKind::InvalidData,
491 format!("Failed to parse .claude/{filename}: {e}"),
492 )
493 })?
494 } else {
495 serde_json::json!({})
496 };
497
498 let hooks = tracevault_hooks();
499
500 let settings_obj = settings.as_object_mut().ok_or_else(|| {
502 io::Error::new(
503 io::ErrorKind::InvalidData,
504 format!(".claude/{filename} is not a JSON object"),
505 )
506 })?;
507
508 settings_obj.insert("hooks".to_string(), hooks);
509
510 let formatted = serde_json::to_string_pretty(&settings)
511 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
512 fs::write(&settings_path, formatted)?;
513
514 Ok(())
515}
516
517pub fn tracevault_hooks() -> serde_json::Value {
518 serde_json::json!({
519 "PreToolUse": [{
520 "matcher": "Write|Edit|Bash",
521 "hooks": [{
522 "type": "command",
523 "command": "tracevault stream --event pre-tool-use",
524 "timeout": 10,
525 "statusMessage": "TraceVault: streaming pre-tool event"
526 }]
527 }],
528 "PostToolUse": [{
529 "matcher": "",
530 "hooks": [{
531 "type": "command",
532 "command": "tracevault stream --event post-tool-use",
533 "timeout": 10,
534 "statusMessage": "TraceVault: streaming post-tool event"
535 }]
536 }],
537 "Notification": [{
538 "matcher": "",
539 "hooks": [{
540 "type": "command",
541 "command": "tracevault stream --event notification",
542 "timeout": 10,
543 "statusMessage": "TraceVault: streaming notification"
544 }]
545 }],
546 "Stop": [{
547 "matcher": "",
548 "hooks": [{
549 "type": "command",
550 "command": "tracevault stream --event stop",
551 "timeout": 10,
552 "statusMessage": "TraceVault: finalizing session"
553 }]
554 }],
555 "SessionStart": [{
556 "matcher": "",
557 "hooks": [{
558 "type": "command",
559 "command": "tracevault session-start",
560 "timeout": 10,
561 "statusMessage": "TraceVault: session start"
562 }]
563 }],
564 "UserPromptSubmit": [{
565 "matcher": "",
566 "hooks": [{
567 "type": "command",
568 "command": "tracevault user-prompt",
569 "timeout": 10,
570 "statusMessage": "TraceVault: policy reinforcement"
571 }]
572 }]
573 })
574}
575
576pub fn codex_hooks() -> serde_json::Value {
587 serde_json::json!({
588 "SessionStart": [{
589 "matcher": "",
590 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
591 }],
592 "UserPromptSubmit": [{
593 "matcher": "",
594 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
595 }],
596 "PostToolUse": [{
597 "matcher": "",
598 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
599 }],
600 "Stop": [{
601 "matcher": "",
602 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
603 }]
604 })
605}
606
607const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
611const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
612const GSD_EXT_MANIFEST_JSON: &str =
613 include_str!("../../assets/gsd-extension/extension-manifest.json");
614
615fn gsd_extension_source_dir() -> io::Result<PathBuf> {
619 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
620 let config_dir = config_dir
621 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
622 Ok(config_dir.join("tracevault").join("gsd-extension"))
623}
624
625pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
649 let home =
650 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
651 let gsd_home = home.join(".gsd");
652
653 let source_dir = gsd_extension_source_dir()?;
654 fs::create_dir_all(&source_dir)?;
655 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
656 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
657 fs::write(
658 source_dir.join("extension-manifest.json"),
659 GSD_EXT_MANIFEST_JSON,
660 )?;
661
662 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
666 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
667 }
668
669 let local_flag = project_root.is_some();
673 let mut cmd = std::process::Command::new("gsd");
674 cmd.arg("install").arg(&source_dir);
675 if let Some(root) = project_root {
676 cmd.arg("-l");
677 cmd.current_dir(root);
678 }
679
680 let retry_hint = format!(
681 "gsd install {}{}",
682 source_dir.display(),
683 if local_flag { " -l" } else { "" }
684 );
685
686 match cmd.output() {
687 Ok(output) if output.status.success() => {
688 println!(
689 "TraceVault: installed and registered the GSD extension ({}).",
690 source_dir.display()
691 );
692 }
693 Ok(output) => {
694 eprintln!(
695 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
696 source_dir.display(),
697 String::from_utf8_lossy(&output.stderr),
698 );
699 }
700 Err(e) => {
701 eprintln!(
702 "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.",
703 source_dir.display(),
704 );
705 }
706 }
707
708 Ok(())
709}
710
711const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
714
715pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
731 let plugins_dir = match project_root {
732 Some(root) => root.join(".opencode").join("plugins"),
733 None => {
734 let config_dir =
735 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
736 config_dir
737 .ok_or_else(|| {
738 io::Error::new(
739 io::ErrorKind::NotFound,
740 "could not determine the config directory for the OpenCode plugin install",
741 )
742 })?
743 .join("opencode")
744 .join("plugins")
745 }
746 };
747
748 write_opencode_plugin_files(&plugins_dir)
749}
750
751fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
752 fs::create_dir_all(plugins_dir)?;
753 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
754 Ok(())
755}
756
757pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
769 let ext_root = gsd_home.join("extensions");
770 let reg_path = ext_root.join("registry.json");
771
772 let reg: Option<serde_json::Value> = if reg_path.exists() {
777 let content = fs::read_to_string(®_path)?;
778 let parsed: serde_json::Value = match serde_json::from_str(&content) {
779 Ok(v) => v,
780 Err(_) => return Ok(()), };
782 let corrupt = match parsed.as_object() {
783 None => true,
784 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
785 };
786 if corrupt {
787 return Ok(()); }
789 Some(parsed)
790 } else {
791 None
792 };
793
794 let stale = ext_root.join("tracevault-tracker");
796 if stale.exists() {
797 fs::remove_dir_all(&stale)?;
798 }
799
800 if let Some(mut reg) = reg {
802 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
803 let removed_tracker = entries.remove("tracevault-tracker").is_some();
804 let removed_inert = entries.remove("tracevault").is_some();
805 if removed_tracker || removed_inert {
806 let tmp = reg_path.with_extension("json.tmp");
808 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
809 fs::rename(&tmp, ®_path)?;
810 }
811 }
812 }
813 Ok(())
814}
815
816fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
826 if hooks_path
831 .components()
832 .any(|c| c == std::path::Component::ParentDir)
833 {
834 return Err(io::Error::new(
835 io::ErrorKind::InvalidInput,
836 format!("refusing to use path with '..': {}", hooks_path.display()),
837 ));
838 }
839 let mut root: serde_json::Value = if hooks_path.exists() {
840 let content = fs::read_to_string(hooks_path)?;
841 serde_json::from_str(&content).map_err(|e| {
842 io::Error::new(
843 io::ErrorKind::InvalidData,
844 format!("Failed to parse {}: {e}", hooks_path.display()),
845 )
846 })?
847 } else {
848 serde_json::json!({})
849 };
850
851 merge_hooks(&mut root, ours, hooks_path)?;
852
853 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
854 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
855 })?;
856 let tmp = hooks_path.with_extension("json.tmp");
857 fs::write(&tmp, formatted)?;
858 fs::rename(&tmp, hooks_path)?;
859 Ok(())
860}
861
862pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
866 let codex_dir = project_root.join(".codex");
867 fs::create_dir_all(&codex_dir)?;
868 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
869}
870
871pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
878 fs::create_dir_all(codex_dir)?;
879 let base = codex_dir.canonicalize()?;
881 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
882 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
883}
884
885const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
889
890const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
891<!-- tracevault:workspace-mode -->
892## TraceVault (workspace mode)
893You may be running detached from any single repository. Before working on a repo, run
894`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
895output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
896already be registered with TraceVault.
897";
898
899fn append_workspace_md(md_path: &Path) -> io::Result<()> {
905 if md_path
907 .components()
908 .any(|c| c == std::path::Component::ParentDir)
909 {
910 return Err(io::Error::new(
911 io::ErrorKind::InvalidInput,
912 format!("refusing to use path with '..': {}", md_path.display()),
913 ));
914 }
915 let existing = if md_path.exists() {
916 fs::read_to_string(md_path)?
917 } else {
918 String::new()
919 };
920 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
921 return Ok(());
922 }
923 let mut content = existing;
924 if !content.is_empty() && !content.ends_with('\n') {
925 content.push('\n');
926 }
927 if !content.is_empty() {
928 content.push('\n');
929 }
930 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
931 fs::write(md_path, content)
932}
933
934fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
938 let joined = base.join(name);
939 if joined.parent() != Some(base) {
940 return Err(io::Error::new(
941 io::ErrorKind::InvalidInput,
942 format!(
943 "refusing to access path outside {}: {}",
944 base.display(),
945 joined.display()
946 ),
947 ));
948 }
949 Ok(joined)
950}
951
952fn merge_hooks(
965 settings: &mut serde_json::Value,
966 ours: &serde_json::Value,
967 path: &Path,
968) -> io::Result<()> {
969 if settings.is_null() {
970 *settings = serde_json::json!({});
971 }
972 let settings_obj = settings.as_object_mut().ok_or_else(|| {
973 io::Error::new(
974 io::ErrorKind::InvalidData,
975 format!("{} is not a JSON object", path.display()),
976 )
977 })?;
978
979 let hooks_value = settings_obj
980 .entry("hooks")
981 .or_insert_with(|| serde_json::json!({}));
982 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
983 io::Error::new(
984 io::ErrorKind::InvalidData,
985 format!("{} \"hooks\" key is not a JSON object", path.display()),
986 )
987 })?;
988
989 let Some(ours_obj) = ours.as_object() else {
990 return Ok(());
991 };
992
993 for (event, our_array) in ours_obj {
994 let Some(our_entries) = our_array.as_array() else {
995 continue;
996 };
997
998 let existing_value = hooks_obj
999 .entry(event.clone())
1000 .or_insert_with(|| serde_json::json!([]));
1001 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1002 io::Error::new(
1003 io::ErrorKind::InvalidData,
1004 format!(
1005 "{} \"hooks\".\"{event}\" is not a JSON array",
1006 path.display()
1007 ),
1008 )
1009 })?;
1010
1011 for our_entry in our_entries {
1012 let our_command = entry_command(our_entry);
1013 let already_present = existing_array
1014 .iter()
1015 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1016 if !already_present {
1017 existing_array.push(our_entry.clone());
1018 }
1019 }
1020 }
1021
1022 Ok(())
1023}
1024
1025fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1028 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1029}
1030
1031fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1036 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1037 return false;
1038 };
1039 hooks
1040 .iter()
1041 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1042}
1043
1044pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1050 fs::create_dir_all(claude_dir)?;
1051
1052 let base = claude_dir.canonicalize()?;
1055
1056 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1058
1059 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1061}
1062
1063pub fn write_global_user_config_in(
1073 config_root: &Path,
1074 requested: Option<UserContext>,
1075) -> io::Result<Option<PathBuf>> {
1076 fs::create_dir_all(config_root)?;
1077 let mut config = crate::config::try_load_user_config_in(config_root)
1079 .ok()
1080 .flatten()
1081 .unwrap_or_default();
1082 let user_context = requested
1084 .or_else(|| config.user_context.clone())
1085 .unwrap_or(UserContext::Toggle(true));
1086 let active = user_context
1087 .resolve()
1088 .map(|_| user_context.path_in(config_root));
1089 config.user_context = Some(user_context);
1090 fs::write(user_config_path_in(config_root), config.to_toml())?;
1091 if let Some(ref ctx_path) = active {
1092 if !ctx_path.exists() {
1093 Context::default().save_to(ctx_path)?;
1094 }
1095 }
1096 Ok(active)
1097}
1098
1099#[cfg(test)]
1100mod tests {
1101 use super::*;
1102 use std::io::{BufRead, BufReader, Write};
1103 use std::net::TcpListener;
1104 use std::thread;
1105
1106 fn spawn_once(response: String) -> String {
1109 let response: &'static str = Box::leak(response.into_boxed_str());
1110 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1111 let addr = listener.local_addr().unwrap();
1112 thread::spawn(move || {
1113 if let Ok((stream, _)) = listener.accept() {
1114 let mut reader = BufReader::new(stream);
1115 let mut request_line = String::new();
1116 let _ = reader.read_line(&mut request_line);
1117 let mut stream = reader.into_inner();
1118 let _ = stream.write_all(response.as_bytes());
1119 let _ = stream.flush();
1120 }
1121 });
1122 format!("http://{addr}")
1123 }
1124
1125 fn http_response(status: &str, body: &str) -> String {
1128 format!(
1129 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1130 status,
1131 body.len(),
1132 body
1133 )
1134 }
1135
1136 fn add_origin_remote(dir: &Path, url: &str) {
1137 let ok = std::process::Command::new("git")
1138 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1139 .status()
1140 .expect("git remote add failed")
1141 .success();
1142 assert!(ok, "git remote add must succeed");
1143 }
1144
1145 #[test]
1146 fn linked_worktree_primary_detects_linked_and_primary() {
1147 let tmp = tempfile::tempdir().unwrap();
1148 let repo = tmp.path().join("repo");
1149 let wt = tmp.path().join("linked-wt");
1150 std::fs::create_dir_all(&repo).unwrap();
1151 crate::test_helpers::init_git_repo(&repo);
1152 crate::test_helpers::add_worktree(&repo, &wt);
1153
1154 assert!(
1156 linked_worktree_primary(&repo).is_none(),
1157 "primary checkout must not be flagged as a linked worktree"
1158 );
1159 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1161 assert_eq!(
1162 primary.canonicalize().unwrap(),
1163 repo.canonicalize().unwrap(),
1164 "must resolve to the primary repo root"
1165 );
1166 }
1167
1168 #[test]
1169 fn linked_worktree_primary_none_for_non_git() {
1170 let tmp = tempfile::tempdir().unwrap();
1171 assert!(
1172 linked_worktree_primary(tmp.path()).is_none(),
1173 "a non-git directory is not a linked worktree"
1174 );
1175 }
1176
1177 #[test]
1178 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1179 let mut settings = serde_json::json!({});
1180 let ours = tracevault_hooks();
1181 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1182
1183 let hooks = settings.get("hooks").unwrap();
1184 for event in [
1185 "PreToolUse",
1186 "PostToolUse",
1187 "Notification",
1188 "Stop",
1189 "SessionStart",
1190 "UserPromptSubmit",
1191 ] {
1192 assert!(hooks.get(event).is_some(), "missing event {event}");
1193 }
1194 }
1195
1196 #[test]
1197 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1198 let mut settings = serde_json::json!({
1199 "model": "opus",
1200 "hooks": {
1201 "PreToolUse": [{
1202 "matcher": "",
1203 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1204 }]
1205 }
1206 });
1207 let ours = tracevault_hooks();
1208 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1209
1210 assert_eq!(settings.get("model").unwrap(), "opus");
1212
1213 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1214 assert_eq!(pre_tool_use.len(), 2);
1216 let commands: Vec<&str> = pre_tool_use
1217 .iter()
1218 .map(|e| entry_command(e).unwrap())
1219 .collect();
1220 assert!(commands.contains(&"my-own-hook"));
1221 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1222
1223 assert!(settings["hooks"]["SessionStart"].is_array());
1225 }
1226
1227 #[test]
1228 fn merge_hooks_is_idempotent() {
1229 let mut settings = serde_json::json!({});
1230 let ours = tracevault_hooks();
1231 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1232 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1233
1234 for event in [
1235 "PreToolUse",
1236 "PostToolUse",
1237 "Notification",
1238 "Stop",
1239 "SessionStart",
1240 "UserPromptSubmit",
1241 ] {
1242 let arr = settings["hooks"][event].as_array().unwrap();
1243 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1244 }
1245 }
1246
1247 #[test]
1248 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1249 let mut settings = serde_json::json!({
1253 "hooks": {
1254 "PreToolUse": [{
1255 "matcher": "Write|Edit|Bash",
1256 "hooks": [
1257 { "type": "command", "command": "other" },
1258 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1259 ]
1260 }]
1261 }
1262 });
1263 let ours = tracevault_hooks();
1264 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1265
1266 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1267 assert_eq!(
1268 pre_tool_use.len(),
1269 1,
1270 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1271 );
1272 }
1273
1274 #[test]
1275 fn merge_hooks_errors_on_non_object_top_level() {
1276 let mut settings = serde_json::json!([1, 2, 3]);
1277 let ours = tracevault_hooks();
1278 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1279 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1280 assert!(err.to_string().contains("settings.json"));
1281 }
1282
1283 #[test]
1284 fn merge_hooks_errors_on_non_object_top_level_number() {
1285 let mut settings = serde_json::json!(42);
1286 let ours = tracevault_hooks();
1287 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1288 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1289 }
1290
1291 #[test]
1292 fn merge_hooks_errors_on_non_object_hooks() {
1293 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1294 let ours = tracevault_hooks();
1295 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1296 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1297 assert!(err.to_string().contains("hooks"));
1298 }
1299
1300 #[test]
1301 fn merge_hooks_errors_on_non_array_event_value() {
1302 let mut settings = serde_json::json!({
1303 "hooks": {
1304 "PreToolUse": "not-an-array"
1305 }
1306 });
1307 let ours = tracevault_hooks();
1308 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1309 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1310 assert!(err.to_string().contains("PreToolUse"));
1311 }
1312
1313 #[test]
1314 fn install_global_hooks_writes_settings_and_claude_md() {
1315 let tmp = tempfile::tempdir().unwrap();
1316 let claude_dir = tmp.path().join(".claude");
1317
1318 install_global_hooks(&claude_dir).unwrap();
1319
1320 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1321 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1322 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1323 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1324 }
1325
1326 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1327 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1328 }
1329
1330 #[test]
1331 fn install_global_hooks_is_idempotent() {
1332 let tmp = tempfile::tempdir().unwrap();
1333 let claude_dir = tmp.path().join(".claude");
1334
1335 install_global_hooks(&claude_dir).unwrap();
1336 install_global_hooks(&claude_dir).unwrap();
1337
1338 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1339 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1340 for event in [
1341 "PreToolUse",
1342 "PostToolUse",
1343 "Notification",
1344 "Stop",
1345 "SessionStart",
1346 "UserPromptSubmit",
1347 ] {
1348 let arr = settings["hooks"][event].as_array().unwrap();
1349 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1350 }
1351
1352 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1353 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1354 assert_eq!(
1355 marker_count, 1,
1356 "CLAUDE.md marker should appear exactly once"
1357 );
1358 }
1359
1360 #[test]
1361 fn install_global_hooks_preserves_existing_claude_md_content() {
1362 let tmp = tempfile::tempdir().unwrap();
1363 let claude_dir = tmp.path().join(".claude");
1364 fs::create_dir_all(&claude_dir).unwrap();
1365 fs::write(
1366 claude_dir.join("CLAUDE.md"),
1367 "# My existing notes\nSome content.\n",
1368 )
1369 .unwrap();
1370
1371 install_global_hooks(&claude_dir).unwrap();
1372
1373 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1374 assert!(claude_md.contains("# My existing notes"));
1375 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1376 }
1377
1378 #[test]
1379 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1380 let tmp = tempfile::tempdir().unwrap();
1381 let claude_dir = tmp.path().join(".claude");
1382
1383 install_global_hooks(&claude_dir).unwrap();
1384
1385 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1386 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1387 assert!(settings["hooks"].get("SessionStart").is_some());
1388
1389 let leftover = fs::read_dir(&claude_dir)
1390 .unwrap()
1391 .filter_map(|e| e.ok())
1392 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1393 assert!(
1394 !leftover,
1395 "no settings.json.tmp should remain after install"
1396 );
1397 }
1398
1399 #[test]
1400 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1401 let tmp = tempfile::tempdir().unwrap();
1402 let claude_dir = tmp.path().join(".claude");
1403 fs::create_dir_all(&claude_dir).unwrap();
1404 let settings_path = claude_dir.join("settings.json");
1405 let original = "[1, 2, 3]";
1406 fs::write(&settings_path, original).unwrap();
1407
1408 let err = install_global_hooks(&claude_dir).unwrap_err();
1409 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1410
1411 let after = fs::read_to_string(&settings_path).unwrap();
1414 assert_eq!(after, original);
1415 let leftover = fs::read_dir(&claude_dir)
1416 .unwrap()
1417 .filter_map(|e| e.ok())
1418 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1419 assert!(!leftover, "no tmp file should be left behind on error");
1420 }
1421
1422 #[test]
1423 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1424 let tmp = tempfile::tempdir().unwrap();
1425 let claude_dir = tmp.path().join(".claude");
1426 fs::create_dir_all(&claude_dir).unwrap();
1427 let settings_path = claude_dir.join("settings.json");
1428 let original = r#"{"hooks": "oops"}"#;
1429 fs::write(&settings_path, original).unwrap();
1430
1431 let err = install_global_hooks(&claude_dir).unwrap_err();
1432 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1433
1434 let after = fs::read_to_string(&settings_path).unwrap();
1435 assert_eq!(after, original);
1436 }
1437
1438 #[test]
1439 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1440 let tmp = tempfile::tempdir().unwrap();
1441 let claude_dir = tmp.path().join(".claude");
1442 fs::create_dir_all(&claude_dir).unwrap();
1443 let settings_path = claude_dir.join("settings.json");
1444 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1445 fs::write(&settings_path, original).unwrap();
1446
1447 let err = install_global_hooks(&claude_dir).unwrap_err();
1448 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1449
1450 let after = fs::read_to_string(&settings_path).unwrap();
1451 assert_eq!(after, original);
1452 }
1453
1454 #[test]
1455 fn safe_join_allows_direct_child_file() {
1456 let tmp = tempfile::tempdir().unwrap();
1457 let base = tmp.path();
1458 let result = safe_join(base, "settings.json").unwrap();
1459 assert_eq!(result.parent(), Some(base));
1460 assert_eq!(result.file_name().unwrap(), "settings.json");
1461 }
1462
1463 #[test]
1464 fn safe_join_rejects_path_traversal() {
1465 let tmp = tempfile::tempdir().unwrap();
1466 let base = tmp.path();
1467 let result = safe_join(base, "../evil");
1468 assert!(result.is_err());
1469 let err = result.unwrap_err();
1470 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1471 assert!(err.to_string().contains("refusing to access path outside"));
1472 }
1473
1474 #[test]
1475 fn safe_join_rejects_absolute_path() {
1476 let tmp = tempfile::tempdir().unwrap();
1477 let base = tmp.path();
1478 let result = safe_join(base, "/etc/passwd");
1479 assert!(result.is_err());
1482 }
1483
1484 #[test]
1485 fn write_global_user_config_enables_and_creates_context() {
1486 let root = tempfile::tempdir().unwrap();
1487 let active = write_global_user_config_in(root.path(), None).unwrap();
1488 let cfg = crate::config::try_load_user_config_in(root.path())
1489 .unwrap()
1490 .unwrap();
1491 assert_eq!(
1494 cfg.user_context.unwrap().resolve_in(root.path()),
1495 Some(crate::config::default_user_context_path_in(root.path()))
1496 );
1497 let ctx = crate::config::default_user_context_path_in(root.path());
1498 assert_eq!(active, Some(ctx.clone()));
1499 assert!(ctx.exists());
1500 }
1501
1502 #[test]
1503 fn write_global_user_config_can_disable() {
1504 let root = tempfile::tempdir().unwrap();
1505 let active = write_global_user_config_in(
1506 root.path(),
1507 Some(crate::config::UserContext::Toggle(false)),
1508 )
1509 .unwrap();
1510 let cfg = crate::config::try_load_user_config_in(root.path())
1511 .unwrap()
1512 .unwrap();
1513 assert!(matches!(
1514 cfg.user_context,
1515 Some(crate::config::UserContext::Toggle(false))
1516 ));
1517 assert_eq!(active, None, "disabled → no active context path");
1518 assert!(
1520 !crate::config::default_user_context_path_in(root.path()).exists(),
1521 "disabled user context must not create a context.json"
1522 );
1523 }
1524
1525 #[test]
1526 fn write_global_user_config_custom_path_seeds_that_file_only() {
1527 let root = tempfile::tempdir().unwrap();
1528 let custom = root.path().join("custom-ctx.json");
1529 let active = write_global_user_config_in(
1530 root.path(),
1531 Some(crate::config::UserContext::Path(
1532 custom.to_string_lossy().into_owned(),
1533 )),
1534 )
1535 .unwrap();
1536 assert_eq!(active, Some(custom.clone()));
1537 assert!(custom.exists(), "the configured custom path must be seeded");
1538 assert!(
1539 !crate::config::default_user_context_path_in(root.path()).exists(),
1540 "the default context.json must NOT be created when a custom path is configured"
1541 );
1542 }
1543
1544 #[test]
1545 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1546 let root = tempfile::tempdir().unwrap();
1547 let custom = root.path().join("custom-ctx.json");
1548 write_global_user_config_in(
1550 root.path(),
1551 Some(crate::config::UserContext::Path(
1552 custom.to_string_lossy().into_owned(),
1553 )),
1554 )
1555 .unwrap();
1556 let active = write_global_user_config_in(root.path(), None).unwrap();
1558 assert_eq!(
1559 active,
1560 Some(custom.clone()),
1561 "re-run without flags must preserve the custom path"
1562 );
1563 let cfg = crate::config::try_load_user_config_in(root.path())
1564 .unwrap()
1565 .unwrap();
1566 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1567 }
1568
1569 #[test]
1570 fn install_global_codex_hooks_writes_and_is_idempotent() {
1571 let tmp = tempfile::tempdir().unwrap();
1572 let codex_dir = tmp.path().join(".codex");
1573
1574 install_global_codex_hooks(&codex_dir).unwrap();
1575 install_global_codex_hooks(&codex_dir).unwrap();
1576
1577 let v: serde_json::Value =
1578 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1579 .unwrap();
1580 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1581 let arr = v["hooks"][event].as_array().unwrap();
1582 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1583 }
1584 assert!(v["hooks"].get("PreToolUse").is_none());
1585 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1587 assert_eq!(
1588 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1589 1,
1590 "AGENTS.md workspace-mode block must appear exactly once"
1591 );
1592 let leftover = fs::read_dir(&codex_dir)
1594 .unwrap()
1595 .filter_map(|e| e.ok())
1596 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1597 assert!(!leftover);
1598 }
1599
1600 #[test]
1601 fn codex_hooks_has_expected_events_and_commands() {
1602 let h = codex_hooks();
1603 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1604 assert!(h.get(event).is_some(), "missing codex event {event}");
1605 }
1606 assert!(h.get("PreToolUse").is_none());
1610 assert!(h.get("Notification").is_none());
1611 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1613 assert_eq!(
1614 cmd("PostToolUse"),
1615 "tracevault stream --event post-tool-use --agent codex"
1616 );
1617 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1618 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1619 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1620 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1622 }
1623
1624 #[test]
1625 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1626 let tmp = tempfile::tempdir().unwrap();
1627 install_codex_hooks(tmp.path()).unwrap();
1628 install_codex_hooks(tmp.path()).unwrap();
1629
1630 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1631 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1632 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1633 let arr = v["hooks"][event].as_array().unwrap();
1634 assert_eq!(
1635 arr.len(),
1636 1,
1637 "event {event} must not be duplicated on re-run"
1638 );
1639 }
1640 assert!(v["hooks"].get("PreToolUse").is_none());
1641 }
1642
1643 #[test]
1644 fn install_codex_hooks_preserves_existing_user_hook() {
1645 let tmp = tempfile::tempdir().unwrap();
1646 let codex_dir = tmp.path().join(".codex");
1647 fs::create_dir_all(&codex_dir).unwrap();
1648 fs::write(
1651 codex_dir.join("hooks.json"),
1652 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1653 )
1654 .unwrap();
1655
1656 install_codex_hooks(tmp.path()).unwrap();
1657
1658 let v: serde_json::Value =
1659 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1660 .unwrap();
1661 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1663 .as_array()
1664 .unwrap()
1665 .iter()
1666 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1667 .collect();
1668 assert!(
1669 post_cmds.contains(&"my-own"),
1670 "user PostToolUse hook preserved"
1671 );
1672 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1673 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1675 .as_array()
1676 .unwrap()
1677 .iter()
1678 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1679 .collect();
1680 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1681 }
1682
1683 #[test]
1684 fn validate_init_flags_rejects_claude_settings_with_codex() {
1685 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1686 }
1687
1688 #[test]
1689 fn validate_init_flags_allows_codex_without_claude_settings() {
1690 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1691 }
1692
1693 #[test]
1694 fn validate_init_flags_allows_claude_with_claude_settings() {
1695 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1696 }
1697
1698 #[test]
1699 fn merge_hooks_into_file_rejects_parent_dir() {
1700 let tmp = tempfile::tempdir().unwrap();
1701 let bad = tmp.path().join("..").join("hooks.json");
1702 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1703 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1704 }
1705
1706 #[test]
1707 fn append_workspace_md_rejects_parent_dir() {
1708 let tmp = tempfile::tempdir().unwrap();
1709 let bad = tmp.path().join("..").join("AGENTS.md");
1710 let err = append_workspace_md(&bad).unwrap_err();
1711 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1712 }
1713
1714 #[tokio::test]
1715 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1716 let tmp = tempfile::tempdir().unwrap();
1717 let root = tmp.path();
1718 crate::test_helpers::init_git_repo(root);
1719
1720 let entry = init_in_directory(
1721 root,
1722 None,
1723 None,
1724 false,
1725 crate::config::UserContext::Toggle(false),
1726 crate::agent::Agent::Codex,
1727 )
1728 .await
1729 .unwrap();
1730
1731 assert!(root.join(".codex").join("hooks.json").exists());
1733 assert!(!root.join(".claude").join("settings.json").exists());
1734 assert_eq!(entry, ".codex/hooks.json");
1735
1736 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1738 assert!(gi.contains(".codex/hooks.json"));
1739 assert!(gi.contains(".tracevault/"));
1740 }
1741
1742 #[tokio::test]
1754 async fn init_in_directory_registers_repo_and_persists_repo_id() {
1755 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1756 let tmp = tempfile::tempdir().unwrap();
1757 let root = tmp.path();
1758 crate::test_helpers::init_git_repo(root);
1759 add_origin_remote(root, "git@github.com:org/repo.git");
1760
1761 let repo_id = "11111111-1111-4111-8111-111111111111";
1762 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
1763 let base = spawn_once(http_response("200 OK", &body));
1764
1765 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1766 _guard.set("XDG_CONFIG_HOME", tmp.path());
1767 _guard.set("TRACEVAULT_API_KEY", "tok");
1768 _guard.remove("TRACEVAULT_SERVER_URL");
1769
1770 init_in_directory(
1771 root,
1772 Some(&base),
1773 None,
1774 true,
1775 crate::config::UserContext::Toggle(false),
1776 crate::agent::Agent::Codex,
1777 )
1778 .await
1779 .unwrap();
1780
1781 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1782 assert_eq!(
1783 cfg.repo_id,
1784 Some(repo_id.to_string()),
1785 "successful registration must persist repo_id to config.toml"
1786 );
1787 }
1788
1789 #[tokio::test]
1795 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
1796 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1797 let tmp = tempfile::tempdir().unwrap();
1798 let root = tmp.path();
1799 crate::test_helpers::init_git_repo(root);
1800 add_origin_remote(root, "git@github.com:org/repo.git");
1801
1802 let base = spawn_once(http_response("403 Forbidden", ""));
1803
1804 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1805 _guard.set("XDG_CONFIG_HOME", tmp.path());
1806 _guard.set("TRACEVAULT_API_KEY", "tok");
1807 _guard.remove("TRACEVAULT_SERVER_URL");
1808
1809 let entry = init_in_directory(
1810 root,
1811 Some(&base),
1812 None,
1813 true,
1814 crate::config::UserContext::Toggle(false),
1815 crate::agent::Agent::Codex,
1816 )
1817 .await
1818 .expect("a registration failure (403) must not abort init itself");
1819 assert_eq!(entry, ".codex/hooks.json");
1820
1821 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1822 assert!(
1823 cfg.repo_id.is_none(),
1824 "a 403 registration failure must not persist a repo_id"
1825 );
1826 }
1827
1828 #[tokio::test]
1833 async fn registration_failure_message_flags_403_as_not_authorized() {
1834 let base = spawn_once(http_response("403 Forbidden", ""));
1835 let client = ApiClient::new(&base, Some("tok"));
1836 let err = client
1837 .register_repo(crate::api_client::RegisterRepoRequest {
1838 repo_name: "repo".into(),
1839 github_url: Some("git@github.com:org/repo.git".into()),
1840 })
1841 .await
1842 .unwrap_err();
1843 let msg = registration_failure_message(err.as_ref());
1844 assert!(
1845 msg.contains("not authorized"),
1846 "403 registration failure must surface a not-authorized message; got: {msg}"
1847 );
1848 }
1849
1850 #[tokio::test]
1853 async fn registration_failure_message_generic_for_non_403() {
1854 let base = spawn_once(http_response("500 Internal Server Error", ""));
1855 let client = ApiClient::new(&base, Some("tok"));
1856 let err = client
1857 .register_repo(crate::api_client::RegisterRepoRequest {
1858 repo_name: "repo".into(),
1859 github_url: Some("git@github.com:org/repo.git".into()),
1860 })
1861 .await
1862 .unwrap_err();
1863 let msg = registration_failure_message(err.as_ref());
1864 assert!(
1865 msg.contains("could not register repo on server"),
1866 "got: {msg}"
1867 );
1868 assert!(!msg.contains("not authorized"), "got: {msg}");
1869 }
1870
1871 #[tokio::test]
1876 async fn registration_failure_message_does_not_misclassify_403_in_body() {
1877 let base = spawn_once(http_response(
1878 "500 Internal Server Error",
1879 "upstream error 403 from proxy",
1880 ));
1881 let client = ApiClient::new(&base, Some("tok"));
1882 let err = client
1883 .register_repo(crate::api_client::RegisterRepoRequest {
1884 repo_name: "repo".into(),
1885 github_url: Some("git@github.com:org/repo.git".into()),
1886 })
1887 .await
1888 .unwrap_err();
1889 let msg = registration_failure_message(err.as_ref());
1890 assert!(
1891 !msg.contains("not authorized"),
1892 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
1893 );
1894 assert!(
1895 msg.contains("could not register repo on server"),
1896 "got: {msg}"
1897 );
1898 }
1899
1900 #[tokio::test]
1904 async fn registration_failure_message_flags_404_as_version_mismatch() {
1905 let base = spawn_once(http_response("404 Not Found", ""));
1906 let client = ApiClient::new(&base, Some("tok"));
1907 let err = client
1908 .register_repo(crate::api_client::RegisterRepoRequest {
1909 repo_name: "repo".into(),
1910 github_url: Some("git@github.com:org/repo.git".into()),
1911 })
1912 .await
1913 .unwrap_err();
1914 let msg = registration_failure_message(err.as_ref());
1915 assert!(
1916 msg.to_lowercase().contains("version mismatch"),
1917 "a 404 registration failure should hint at a version mismatch; got: {msg}"
1918 );
1919 }
1920}