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, RegistrationPlan};
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 previous_repo_id = TracevaultConfig::load(project_root)
194 .and_then(|c| c.repo_id)
195 .and_then(|id| id.parse::<uuid::Uuid>().ok());
196
197 let mut config = TracevaultConfig::default();
199 if let Some(url) = server_url {
200 config.server_url = Some(url.to_string());
201 }
202 config.user_context = Some(user_context);
203 fs::write(
204 TracevaultConfig::config_path(project_root),
205 config.to_toml(),
206 )?;
207
208 match agent {
210 crate::agent::Agent::ClaudeCode => {
211 let target =
213 claude_target.expect("claude settings target is resolved for the Claude agent");
214 install_claude_hooks(project_root, target)?;
215 }
216 crate::agent::Agent::Codex => {
217 install_codex_hooks(project_root)?;
218 println!("{}", codex_hook_trust_notice());
219 }
220 crate::agent::Agent::Gsd => {
221 install_gsd_extension(Some(project_root))?;
229 }
230 crate::agent::Agent::OpenCode => {
231 install_opencode_plugin(Some(project_root))?;
232 }
233 }
234
235 install_git_hook(project_root)?;
237 install_post_commit_hook(project_root)?;
238
239 let detected = crate::hooks::detect_tools(project_root);
241 for tool in &detected {
242 println!(" Detected: {}", tool.name());
243 }
244
245 let (resolved_url, resolved_credential) =
250 crate::credentials::resolve_credentials_quiet(project_root)
251 .map_err(|e| io::Error::other(e.to_string()))?;
252 let effective_url = server_url.map(String::from).or(resolved_url);
253
254 if resolved_credential.is_none() {
255 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
256 } else if let (Some(url), Some(remote)) = (effective_url, remote_url) {
257 let client = ApiClient::with_credential(&url, resolved_credential);
258 let repo_name = git_repo_name(project_root);
259 let origin_url = remote.clone();
262
263 match crate::resolution::plan_registration(
267 &client,
268 &origin_url,
269 &repo_name,
270 previous_repo_id,
271 )
272 .await
273 {
274 Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
275 println!(
276 "Bound to existing repo {} (id: {repo_id}); not registering another record \
277 for this codebase",
278 codebase
279 .repos
280 .iter()
281 .find(|r| r.id == repo_id)
282 .map_or("", |r| r.name.as_str())
283 );
284 println!(
285 "{}",
286 crate::resolution::codebase_line(
287 codebase.remote.name.as_deref(),
288 &codebase.remote.normalized_url,
289 &codebase.remote.clone_status
290 )
291 );
292 persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
293 }
294 Ok(RegistrationPlan::Ambiguous(codebase)) => {
295 eprintln!(
296 "Warning: codebase {} already has {} repo records ({}) and none is named \
297 '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
298 .tracevault/config.toml to the one this checkout belongs to.",
299 codebase.display_name(),
300 codebase.repos.len(),
301 codebase.repo_list()
302 );
303 }
304 Ok(RegistrationPlan::Register) => {
305 register_new_repo(&client, project_root, repo_name, origin_url).await;
306 }
307 Err(e) => {
310 eprintln!(
311 "Warning: could not check the server for an existing repo of this remote \
312 ({e}); not registering. Run `tracevault init` again once the server is \
313 reachable."
314 );
315 }
316 }
317 }
318
319 Ok(hook_gitignore_entry)
320}
321
322pub(crate) fn persist_repo_binding(
329 project_root: &Path,
330 repo_id: uuid::Uuid,
331 codebase: Option<&crate::api_client::ResolveRemoteResponse>,
332) -> bool {
333 let Some(mut cfg) = TracevaultConfig::load(project_root) else {
334 return false;
335 };
336 cfg.repo_id = Some(repo_id.to_string());
337 if let Some(remote) = codebase {
338 cfg.remote_id = Some(remote.remote_id.to_string());
339 cfg.codebase_name = remote.name.clone();
340 }
341 fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml()).is_ok()
342}
343
344async fn register_new_repo(
348 client: &ApiClient,
349 project_root: &Path,
350 repo_name: String,
351 origin_url: String,
352) {
353 match client
354 .register_repo(crate::api_client::RegisterRepoRequest {
355 repo_name,
356 github_url: Some(origin_url.clone()),
357 })
358 .await
359 {
360 Ok(resp) => {
361 println!("Repo registered on server (id: {})", resp.repo_id);
362 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
364 cfg.repo_id = Some(resp.repo_id.to_string());
365 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
371 println!(
372 "{}",
373 crate::resolution::codebase_line(
374 remote.name.as_deref(),
375 &remote.normalized_url,
376 &remote.clone_status
377 )
378 );
379 cfg.remote_id = Some(remote.remote_id.to_string());
380 cfg.codebase_name = remote.name.clone();
381 }
382 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
383 }
384 }
385 Err(e) => {
386 eprintln!("{}", registration_failure_message(e.as_ref()));
387 }
388 }
389}
390
391fn registration_failure_message(err: &dyn std::error::Error) -> String {
406 let msg = err.to_string();
407 if msg.starts_with("Server returned 403 ") {
408 "Warning: you are not authorized to register this repo.".to_string()
409 } else if msg.starts_with("Server returned 404 ") {
410 "Warning: could not register repo on server (404) — this endpoint may not exist on \
411 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
412 once the server is upgraded."
413 .to_string()
414 } else {
415 format!("Warning: could not register repo on server: {err}")
416 }
417}
418
419fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
420 let path = project_root.join(".gitignore");
421 let existing = if path.exists() {
422 fs::read_to_string(&path)?
423 } else {
424 String::new()
425 };
426
427 let needed: Vec<&str> = [".tracevault/", settings_entry]
433 .iter()
434 .copied()
435 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
436 .collect();
437
438 if needed.is_empty() {
439 return Ok(());
440 }
441
442 let mut content = existing;
443 if !content.is_empty() && !content.ends_with('\n') {
444 content.push('\n');
445 }
446 content.push_str("\n# TraceVault — local only, do not commit\n");
447 for entry in needed {
448 content.push_str(entry);
449 content.push('\n');
450 }
451
452 fs::write(path, content)
453}
454
455const HOOK_MARKER: &str = "# tracevault:enforce";
456const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
457
458fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
459 let hooks_dir = project_root.join(".git/hooks");
460 fs::create_dir_all(&hooks_dir)?;
461
462 let hook_path = hooks_dir.join("pre-push");
463 let tracevault_block = format!(
470 "{HOOK_MARKER}\n\
471 # Capture git's pre-push ref list once; `check` uses it to determine\n\
472 # which files are being pushed.\n\
473 tracevault_prepush_stdin=$(cat)\n\
474 tracevault sync 2>/dev/null || true\n\
475 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
476 );
477
478 if hook_path.exists() {
479 let existing = fs::read_to_string(&hook_path)?;
480
481 if existing.contains(HOOK_MARKER) {
483 return Ok(());
484 }
485
486 if existing.contains(OLD_HOOK_MARKER) {
488 let mut new_content = String::new();
489 let mut skip = false;
490 for line in existing.lines() {
491 if line.contains(OLD_HOOK_MARKER) {
492 skip = true;
493 continue;
494 }
495 if skip {
496 if line.starts_with("tracevault ") {
498 continue;
499 }
500 skip = false;
501 }
502 new_content.push_str(line);
503 new_content.push('\n');
504 }
505 if !new_content.ends_with('\n') {
506 new_content.push('\n');
507 }
508 new_content.push_str(&tracevault_block);
509 fs::write(&hook_path, new_content)?;
510 } else {
511 let mut content = existing;
513 if !content.ends_with('\n') {
514 content.push('\n');
515 }
516 content.push_str(&tracevault_block);
517 fs::write(&hook_path, content)?;
518 }
519 } else {
520 let content = format!("#!/bin/sh\n{tracevault_block}");
521 fs::write(&hook_path, content)?;
522 }
523
524 #[cfg(unix)]
526 {
527 use std::os::unix::fs::PermissionsExt;
528 let mut perms = fs::metadata(&hook_path)?.permissions();
529 perms.set_mode(0o755);
530 fs::set_permissions(&hook_path, perms)?;
531 }
532
533 Ok(())
534}
535
536const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
537
538fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
539 let hooks_dir = project_root.join(".git/hooks");
540 fs::create_dir_all(&hooks_dir)?;
541
542 let hook_path = hooks_dir.join("post-commit");
543 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
544
545 if hook_path.exists() {
546 let existing = fs::read_to_string(&hook_path)?;
547
548 if existing.contains(POST_COMMIT_MARKER) {
549 return Ok(());
550 }
551
552 let mut content = existing;
553 if !content.ends_with('\n') {
554 content.push('\n');
555 }
556 content.push_str(&tracevault_block);
557 fs::write(&hook_path, content)?;
558 } else {
559 let content = format!("#!/bin/sh\n{tracevault_block}");
560 fs::write(&hook_path, content)?;
561 }
562
563 #[cfg(unix)]
564 {
565 use std::os::unix::fs::PermissionsExt;
566 let mut perms = fs::metadata(&hook_path)?.permissions();
567 perms.set_mode(0o755);
568 fs::set_permissions(&hook_path, perms)?;
569 }
570
571 Ok(())
572}
573
574fn install_claude_hooks(
575 project_root: &Path,
576 target: ClaudeSettingsTarget,
577) -> Result<(), io::Error> {
578 let claude_dir = project_root.join(".claude");
579 fs::create_dir_all(&claude_dir)?;
580
581 let filename = target.filename();
582 let settings_path = claude_dir.join(filename);
583 let mut settings: serde_json::Value = if settings_path.exists() {
584 let content = fs::read_to_string(&settings_path)?;
585 serde_json::from_str(&content).map_err(|e| {
586 io::Error::new(
587 io::ErrorKind::InvalidData,
588 format!("Failed to parse .claude/{filename}: {e}"),
589 )
590 })?
591 } else {
592 serde_json::json!({})
593 };
594
595 let hooks = tracevault_hooks();
596
597 let settings_obj = settings.as_object_mut().ok_or_else(|| {
599 io::Error::new(
600 io::ErrorKind::InvalidData,
601 format!(".claude/{filename} is not a JSON object"),
602 )
603 })?;
604
605 settings_obj.insert("hooks".to_string(), hooks);
606
607 let formatted = serde_json::to_string_pretty(&settings)
608 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
609 fs::write(&settings_path, formatted)?;
610
611 Ok(())
612}
613
614pub fn tracevault_hooks() -> serde_json::Value {
615 serde_json::json!({
616 "PreToolUse": [{
617 "matcher": "Write|Edit|Bash",
618 "hooks": [{
619 "type": "command",
620 "command": "tracevault stream --event pre-tool-use",
621 "timeout": 10,
622 "statusMessage": "TraceVault: streaming pre-tool event"
623 }]
624 }],
625 "PostToolUse": [{
626 "matcher": "",
627 "hooks": [{
628 "type": "command",
629 "command": "tracevault stream --event post-tool-use",
630 "timeout": 10,
631 "statusMessage": "TraceVault: streaming post-tool event"
632 }]
633 }],
634 "Notification": [{
635 "matcher": "",
636 "hooks": [{
637 "type": "command",
638 "command": "tracevault stream --event notification",
639 "timeout": 10,
640 "statusMessage": "TraceVault: streaming notification"
641 }]
642 }],
643 "Stop": [{
644 "matcher": "",
645 "hooks": [{
646 "type": "command",
647 "command": "tracevault stream --event stop",
648 "timeout": 10,
649 "statusMessage": "TraceVault: finalizing session"
650 }]
651 }],
652 "SessionStart": [{
653 "matcher": "",
654 "hooks": [{
655 "type": "command",
656 "command": "tracevault session-start",
657 "timeout": 10,
658 "statusMessage": "TraceVault: session start"
659 }]
660 }],
661 "UserPromptSubmit": [{
662 "matcher": "",
663 "hooks": [{
664 "type": "command",
665 "command": "tracevault user-prompt",
666 "timeout": 10,
667 "statusMessage": "TraceVault: policy reinforcement"
668 }]
669 }]
670 })
671}
672
673pub fn codex_hook_trust_notice() -> &'static str {
683 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
684 silently and no session is captured. Run `codex` once interactively in a repo and \
685 approve the hook-trust prompt; unattended runs (CI) can pass \
686 `--dangerously-bypass-hook-trust` instead."
687}
688
689pub fn codex_hooks() -> serde_json::Value {
699 serde_json::json!({
700 "SessionStart": [{
701 "matcher": "",
702 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
703 }],
704 "UserPromptSubmit": [{
705 "matcher": "",
706 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
707 }],
708 "PostToolUse": [{
709 "matcher": "",
710 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
711 }],
712 "Stop": [{
713 "matcher": "",
714 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
715 }]
716 })
717}
718
719const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
723const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
724const GSD_EXT_MANIFEST_JSON: &str =
725 include_str!("../../assets/gsd-extension/extension-manifest.json");
726
727fn gsd_extension_source_dir() -> io::Result<PathBuf> {
731 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
732 let config_dir = config_dir
733 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
734 Ok(config_dir.join("tracevault").join("gsd-extension"))
735}
736
737pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
761 let home =
762 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
763 let gsd_home = home.join(".gsd");
764
765 let source_dir = gsd_extension_source_dir()?;
766 fs::create_dir_all(&source_dir)?;
767 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
768 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
769 fs::write(
770 source_dir.join("extension-manifest.json"),
771 GSD_EXT_MANIFEST_JSON,
772 )?;
773
774 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
778 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
779 }
780
781 let local_flag = project_root.is_some();
785 let mut cmd = std::process::Command::new("gsd");
786 cmd.arg("install").arg(&source_dir);
787 if let Some(root) = project_root {
788 cmd.arg("-l");
789 cmd.current_dir(root);
790 }
791
792 let retry_hint = format!(
793 "gsd install {}{}",
794 source_dir.display(),
795 if local_flag { " -l" } else { "" }
796 );
797
798 match cmd.output() {
799 Ok(output) if output.status.success() => {
800 println!(
801 "TraceVault: installed and registered the GSD extension ({}).",
802 source_dir.display()
803 );
804 }
805 Ok(output) => {
806 eprintln!(
807 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
808 source_dir.display(),
809 String::from_utf8_lossy(&output.stderr),
810 );
811 }
812 Err(e) => {
813 eprintln!(
814 "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.",
815 source_dir.display(),
816 );
817 }
818 }
819
820 Ok(())
821}
822
823const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
826
827pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
843 let plugins_dir = match project_root {
844 Some(root) => root.join(".opencode").join("plugins"),
845 None => {
846 let config_dir =
847 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
848 config_dir
849 .ok_or_else(|| {
850 io::Error::new(
851 io::ErrorKind::NotFound,
852 "could not determine the config directory for the OpenCode plugin install",
853 )
854 })?
855 .join("opencode")
856 .join("plugins")
857 }
858 };
859
860 write_opencode_plugin_files(&plugins_dir)
861}
862
863fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
864 fs::create_dir_all(plugins_dir)?;
865 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
866 Ok(())
867}
868
869pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
881 let ext_root = gsd_home.join("extensions");
882 let reg_path = ext_root.join("registry.json");
883
884 let reg: Option<serde_json::Value> = if reg_path.exists() {
889 let content = fs::read_to_string(®_path)?;
890 let parsed: serde_json::Value = match serde_json::from_str(&content) {
891 Ok(v) => v,
892 Err(_) => return Ok(()), };
894 let corrupt = match parsed.as_object() {
895 None => true,
896 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
897 };
898 if corrupt {
899 return Ok(()); }
901 Some(parsed)
902 } else {
903 None
904 };
905
906 let stale = ext_root.join("tracevault-tracker");
908 if stale.exists() {
909 fs::remove_dir_all(&stale)?;
910 }
911
912 if let Some(mut reg) = reg {
914 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
915 let removed_tracker = entries.remove("tracevault-tracker").is_some();
916 let removed_inert = entries.remove("tracevault").is_some();
917 if removed_tracker || removed_inert {
918 let tmp = reg_path.with_extension("json.tmp");
920 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
921 fs::rename(&tmp, ®_path)?;
922 }
923 }
924 }
925 Ok(())
926}
927
928fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
938 if hooks_path
943 .components()
944 .any(|c| c == std::path::Component::ParentDir)
945 {
946 return Err(io::Error::new(
947 io::ErrorKind::InvalidInput,
948 format!("refusing to use path with '..': {}", hooks_path.display()),
949 ));
950 }
951 let mut root: serde_json::Value = if hooks_path.exists() {
952 let content = fs::read_to_string(hooks_path)?;
953 serde_json::from_str(&content).map_err(|e| {
954 io::Error::new(
955 io::ErrorKind::InvalidData,
956 format!("Failed to parse {}: {e}", hooks_path.display()),
957 )
958 })?
959 } else {
960 serde_json::json!({})
961 };
962
963 merge_hooks(&mut root, ours, hooks_path)?;
964
965 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
966 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
967 })?;
968 let tmp = hooks_path.with_extension("json.tmp");
969 fs::write(&tmp, formatted)?;
970 fs::rename(&tmp, hooks_path)?;
971 Ok(())
972}
973
974pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
978 let codex_dir = project_root.join(".codex");
979 fs::create_dir_all(&codex_dir)?;
980 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
981}
982
983pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
990 fs::create_dir_all(codex_dir)?;
991 let base = codex_dir.canonicalize()?;
993 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
994 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
995}
996
997const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1001
1002const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1003<!-- tracevault:workspace-mode -->
1004## TraceVault (workspace mode)
1005You may be running detached from any single repository. Before working on a repo, run
1006`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
1007output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
1008already be registered with TraceVault.
1009";
1010
1011fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1017 if md_path
1019 .components()
1020 .any(|c| c == std::path::Component::ParentDir)
1021 {
1022 return Err(io::Error::new(
1023 io::ErrorKind::InvalidInput,
1024 format!("refusing to use path with '..': {}", md_path.display()),
1025 ));
1026 }
1027 let existing = if md_path.exists() {
1028 fs::read_to_string(md_path)?
1029 } else {
1030 String::new()
1031 };
1032 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1033 return Ok(());
1034 }
1035 let mut content = existing;
1036 if !content.is_empty() && !content.ends_with('\n') {
1037 content.push('\n');
1038 }
1039 if !content.is_empty() {
1040 content.push('\n');
1041 }
1042 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1043 fs::write(md_path, content)
1044}
1045
1046fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1050 let joined = base.join(name);
1051 if joined.parent() != Some(base) {
1052 return Err(io::Error::new(
1053 io::ErrorKind::InvalidInput,
1054 format!(
1055 "refusing to access path outside {}: {}",
1056 base.display(),
1057 joined.display()
1058 ),
1059 ));
1060 }
1061 Ok(joined)
1062}
1063
1064fn merge_hooks(
1077 settings: &mut serde_json::Value,
1078 ours: &serde_json::Value,
1079 path: &Path,
1080) -> io::Result<()> {
1081 if settings.is_null() {
1082 *settings = serde_json::json!({});
1083 }
1084 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1085 io::Error::new(
1086 io::ErrorKind::InvalidData,
1087 format!("{} is not a JSON object", path.display()),
1088 )
1089 })?;
1090
1091 let hooks_value = settings_obj
1092 .entry("hooks")
1093 .or_insert_with(|| serde_json::json!({}));
1094 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1095 io::Error::new(
1096 io::ErrorKind::InvalidData,
1097 format!("{} \"hooks\" key is not a JSON object", path.display()),
1098 )
1099 })?;
1100
1101 let Some(ours_obj) = ours.as_object() else {
1102 return Ok(());
1103 };
1104
1105 for (event, our_array) in ours_obj {
1106 let Some(our_entries) = our_array.as_array() else {
1107 continue;
1108 };
1109
1110 let existing_value = hooks_obj
1111 .entry(event.clone())
1112 .or_insert_with(|| serde_json::json!([]));
1113 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
1114 io::Error::new(
1115 io::ErrorKind::InvalidData,
1116 format!(
1117 "{} \"hooks\".\"{event}\" is not a JSON array",
1118 path.display()
1119 ),
1120 )
1121 })?;
1122
1123 for our_entry in our_entries {
1124 let our_command = entry_command(our_entry);
1125 let already_present = existing_array
1126 .iter()
1127 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
1128 if !already_present {
1129 existing_array.push(our_entry.clone());
1130 }
1131 }
1132 }
1133
1134 Ok(())
1135}
1136
1137fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1140 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1141}
1142
1143fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
1148 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
1149 return false;
1150 };
1151 hooks
1152 .iter()
1153 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
1154}
1155
1156pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1162 fs::create_dir_all(claude_dir)?;
1163
1164 let base = claude_dir.canonicalize()?;
1167
1168 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1170
1171 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1173}
1174
1175pub fn write_global_user_config_in(
1185 config_root: &Path,
1186 requested: Option<UserContext>,
1187) -> io::Result<Option<PathBuf>> {
1188 fs::create_dir_all(config_root)?;
1189 let mut config = crate::config::try_load_user_config_in(config_root)
1191 .ok()
1192 .flatten()
1193 .unwrap_or_default();
1194 let user_context = requested
1196 .or_else(|| config.user_context.clone())
1197 .unwrap_or(UserContext::Toggle(true));
1198 let active = user_context
1199 .resolve()
1200 .map(|_| user_context.path_in(config_root));
1201 config.user_context = Some(user_context);
1202 fs::write(user_config_path_in(config_root), config.to_toml())?;
1203 if let Some(ref ctx_path) = active {
1204 if !ctx_path.exists() {
1205 Context::default().save_to(ctx_path)?;
1206 }
1207 }
1208 Ok(active)
1209}
1210
1211#[cfg(test)]
1212mod tests {
1213 use super::*;
1214 use std::io::{BufRead, BufReader, Write};
1215 use std::net::TcpListener;
1216 use std::thread;
1217
1218 #[test]
1224 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1225 let notice = codex_hook_trust_notice();
1226 assert!(
1227 notice.contains("hook trust"),
1228 "notice must name what is missing: {notice}"
1229 );
1230 assert!(
1231 notice.contains("codex") && notice.contains("approve"),
1232 "notice must tell the user to run codex and approve the prompt: {notice}"
1233 );
1234 assert!(
1235 notice.contains("--dangerously-bypass-hook-trust"),
1236 "notice must name the flag for unattended/CI runs: {notice}"
1237 );
1238 assert!(
1239 notice.contains("silently"),
1240 "notice must say the failure is silent, which is why it needs saying: {notice}"
1241 );
1242 }
1243
1244 fn spawn_once(response: String) -> String {
1247 let response: &'static str = Box::leak(response.into_boxed_str());
1248 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1249 let addr = listener.local_addr().unwrap();
1250 thread::spawn(move || {
1251 if let Ok((stream, _)) = listener.accept() {
1252 let mut reader = BufReader::new(stream);
1253 let mut request_line = String::new();
1254 let _ = reader.read_line(&mut request_line);
1255 let mut stream = reader.into_inner();
1256 let _ = stream.write_all(response.as_bytes());
1257 let _ = stream.flush();
1258 }
1259 });
1260 format!("http://{addr}")
1261 }
1262
1263 fn http_response(status: &str, body: &str) -> String {
1266 format!(
1267 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1268 status,
1269 body.len(),
1270 body
1271 )
1272 }
1273
1274 fn add_origin_remote(dir: &Path, url: &str) {
1275 let ok = std::process::Command::new("git")
1276 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1277 .status()
1278 .expect("git remote add failed")
1279 .success();
1280 assert!(ok, "git remote add must succeed");
1281 }
1282
1283 #[test]
1284 fn linked_worktree_primary_detects_linked_and_primary() {
1285 let tmp = tempfile::tempdir().unwrap();
1286 let repo = tmp.path().join("repo");
1287 let wt = tmp.path().join("linked-wt");
1288 std::fs::create_dir_all(&repo).unwrap();
1289 crate::test_helpers::init_git_repo(&repo);
1290 crate::test_helpers::add_worktree(&repo, &wt);
1291
1292 assert!(
1294 linked_worktree_primary(&repo).is_none(),
1295 "primary checkout must not be flagged as a linked worktree"
1296 );
1297 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1299 assert_eq!(
1300 primary.canonicalize().unwrap(),
1301 repo.canonicalize().unwrap(),
1302 "must resolve to the primary repo root"
1303 );
1304 }
1305
1306 #[test]
1307 fn linked_worktree_primary_none_for_non_git() {
1308 let tmp = tempfile::tempdir().unwrap();
1309 assert!(
1310 linked_worktree_primary(tmp.path()).is_none(),
1311 "a non-git directory is not a linked worktree"
1312 );
1313 }
1314
1315 #[test]
1316 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1317 let mut settings = serde_json::json!({});
1318 let ours = tracevault_hooks();
1319 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1320
1321 let hooks = settings.get("hooks").unwrap();
1322 for event in [
1323 "PreToolUse",
1324 "PostToolUse",
1325 "Notification",
1326 "Stop",
1327 "SessionStart",
1328 "UserPromptSubmit",
1329 ] {
1330 assert!(hooks.get(event).is_some(), "missing event {event}");
1331 }
1332 }
1333
1334 #[test]
1335 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1336 let mut settings = serde_json::json!({
1337 "model": "opus",
1338 "hooks": {
1339 "PreToolUse": [{
1340 "matcher": "",
1341 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1342 }]
1343 }
1344 });
1345 let ours = tracevault_hooks();
1346 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1347
1348 assert_eq!(settings.get("model").unwrap(), "opus");
1350
1351 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1352 assert_eq!(pre_tool_use.len(), 2);
1354 let commands: Vec<&str> = pre_tool_use
1355 .iter()
1356 .map(|e| entry_command(e).unwrap())
1357 .collect();
1358 assert!(commands.contains(&"my-own-hook"));
1359 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1360
1361 assert!(settings["hooks"]["SessionStart"].is_array());
1363 }
1364
1365 #[test]
1366 fn merge_hooks_is_idempotent() {
1367 let mut settings = serde_json::json!({});
1368 let ours = tracevault_hooks();
1369 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1370 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1371
1372 for event in [
1373 "PreToolUse",
1374 "PostToolUse",
1375 "Notification",
1376 "Stop",
1377 "SessionStart",
1378 "UserPromptSubmit",
1379 ] {
1380 let arr = settings["hooks"][event].as_array().unwrap();
1381 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1382 }
1383 }
1384
1385 #[test]
1386 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
1387 let mut settings = serde_json::json!({
1391 "hooks": {
1392 "PreToolUse": [{
1393 "matcher": "Write|Edit|Bash",
1394 "hooks": [
1395 { "type": "command", "command": "other" },
1396 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1397 ]
1398 }]
1399 }
1400 });
1401 let ours = tracevault_hooks();
1402 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1403
1404 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1405 assert_eq!(
1406 pre_tool_use.len(),
1407 1,
1408 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1409 );
1410 }
1411
1412 #[test]
1413 fn merge_hooks_errors_on_non_object_top_level() {
1414 let mut settings = serde_json::json!([1, 2, 3]);
1415 let ours = tracevault_hooks();
1416 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1417 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1418 assert!(err.to_string().contains("settings.json"));
1419 }
1420
1421 #[test]
1422 fn merge_hooks_errors_on_non_object_top_level_number() {
1423 let mut settings = serde_json::json!(42);
1424 let ours = tracevault_hooks();
1425 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1426 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1427 }
1428
1429 #[test]
1430 fn merge_hooks_errors_on_non_object_hooks() {
1431 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1432 let ours = tracevault_hooks();
1433 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1434 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1435 assert!(err.to_string().contains("hooks"));
1436 }
1437
1438 #[test]
1439 fn merge_hooks_errors_on_non_array_event_value() {
1440 let mut settings = serde_json::json!({
1441 "hooks": {
1442 "PreToolUse": "not-an-array"
1443 }
1444 });
1445 let ours = tracevault_hooks();
1446 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1447 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1448 assert!(err.to_string().contains("PreToolUse"));
1449 }
1450
1451 #[test]
1452 fn install_global_hooks_writes_settings_and_claude_md() {
1453 let tmp = tempfile::tempdir().unwrap();
1454 let claude_dir = tmp.path().join(".claude");
1455
1456 install_global_hooks(&claude_dir).unwrap();
1457
1458 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1459 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1460 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1461 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1462 }
1463
1464 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1465 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1466 }
1467
1468 #[test]
1469 fn install_global_hooks_is_idempotent() {
1470 let tmp = tempfile::tempdir().unwrap();
1471 let claude_dir = tmp.path().join(".claude");
1472
1473 install_global_hooks(&claude_dir).unwrap();
1474 install_global_hooks(&claude_dir).unwrap();
1475
1476 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1477 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1478 for event in [
1479 "PreToolUse",
1480 "PostToolUse",
1481 "Notification",
1482 "Stop",
1483 "SessionStart",
1484 "UserPromptSubmit",
1485 ] {
1486 let arr = settings["hooks"][event].as_array().unwrap();
1487 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1488 }
1489
1490 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1491 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1492 assert_eq!(
1493 marker_count, 1,
1494 "CLAUDE.md marker should appear exactly once"
1495 );
1496 }
1497
1498 #[test]
1499 fn install_global_hooks_preserves_existing_claude_md_content() {
1500 let tmp = tempfile::tempdir().unwrap();
1501 let claude_dir = tmp.path().join(".claude");
1502 fs::create_dir_all(&claude_dir).unwrap();
1503 fs::write(
1504 claude_dir.join("CLAUDE.md"),
1505 "# My existing notes\nSome content.\n",
1506 )
1507 .unwrap();
1508
1509 install_global_hooks(&claude_dir).unwrap();
1510
1511 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1512 assert!(claude_md.contains("# My existing notes"));
1513 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1514 }
1515
1516 #[test]
1517 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1518 let tmp = tempfile::tempdir().unwrap();
1519 let claude_dir = tmp.path().join(".claude");
1520
1521 install_global_hooks(&claude_dir).unwrap();
1522
1523 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1524 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1525 assert!(settings["hooks"].get("SessionStart").is_some());
1526
1527 let leftover = fs::read_dir(&claude_dir)
1528 .unwrap()
1529 .filter_map(|e| e.ok())
1530 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1531 assert!(
1532 !leftover,
1533 "no settings.json.tmp should remain after install"
1534 );
1535 }
1536
1537 #[test]
1538 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1539 let tmp = tempfile::tempdir().unwrap();
1540 let claude_dir = tmp.path().join(".claude");
1541 fs::create_dir_all(&claude_dir).unwrap();
1542 let settings_path = claude_dir.join("settings.json");
1543 let original = "[1, 2, 3]";
1544 fs::write(&settings_path, original).unwrap();
1545
1546 let err = install_global_hooks(&claude_dir).unwrap_err();
1547 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1548
1549 let after = fs::read_to_string(&settings_path).unwrap();
1552 assert_eq!(after, original);
1553 let leftover = fs::read_dir(&claude_dir)
1554 .unwrap()
1555 .filter_map(|e| e.ok())
1556 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1557 assert!(!leftover, "no tmp file should be left behind on error");
1558 }
1559
1560 #[test]
1561 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1562 let tmp = tempfile::tempdir().unwrap();
1563 let claude_dir = tmp.path().join(".claude");
1564 fs::create_dir_all(&claude_dir).unwrap();
1565 let settings_path = claude_dir.join("settings.json");
1566 let original = r#"{"hooks": "oops"}"#;
1567 fs::write(&settings_path, original).unwrap();
1568
1569 let err = install_global_hooks(&claude_dir).unwrap_err();
1570 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1571
1572 let after = fs::read_to_string(&settings_path).unwrap();
1573 assert_eq!(after, original);
1574 }
1575
1576 #[test]
1577 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1578 let tmp = tempfile::tempdir().unwrap();
1579 let claude_dir = tmp.path().join(".claude");
1580 fs::create_dir_all(&claude_dir).unwrap();
1581 let settings_path = claude_dir.join("settings.json");
1582 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1583 fs::write(&settings_path, original).unwrap();
1584
1585 let err = install_global_hooks(&claude_dir).unwrap_err();
1586 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1587
1588 let after = fs::read_to_string(&settings_path).unwrap();
1589 assert_eq!(after, original);
1590 }
1591
1592 #[test]
1593 fn safe_join_allows_direct_child_file() {
1594 let tmp = tempfile::tempdir().unwrap();
1595 let base = tmp.path();
1596 let result = safe_join(base, "settings.json").unwrap();
1597 assert_eq!(result.parent(), Some(base));
1598 assert_eq!(result.file_name().unwrap(), "settings.json");
1599 }
1600
1601 #[test]
1602 fn safe_join_rejects_path_traversal() {
1603 let tmp = tempfile::tempdir().unwrap();
1604 let base = tmp.path();
1605 let result = safe_join(base, "../evil");
1606 assert!(result.is_err());
1607 let err = result.unwrap_err();
1608 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1609 assert!(err.to_string().contains("refusing to access path outside"));
1610 }
1611
1612 #[test]
1613 fn safe_join_rejects_absolute_path() {
1614 let tmp = tempfile::tempdir().unwrap();
1615 let base = tmp.path();
1616 let result = safe_join(base, "/etc/passwd");
1617 assert!(result.is_err());
1620 }
1621
1622 #[test]
1623 fn write_global_user_config_enables_and_creates_context() {
1624 let root = tempfile::tempdir().unwrap();
1625 let active = write_global_user_config_in(root.path(), None).unwrap();
1626 let cfg = crate::config::try_load_user_config_in(root.path())
1627 .unwrap()
1628 .unwrap();
1629 assert_eq!(
1632 cfg.user_context.unwrap().resolve_in(root.path()),
1633 Some(crate::config::default_user_context_path_in(root.path()))
1634 );
1635 let ctx = crate::config::default_user_context_path_in(root.path());
1636 assert_eq!(active, Some(ctx.clone()));
1637 assert!(ctx.exists());
1638 }
1639
1640 #[test]
1641 fn write_global_user_config_can_disable() {
1642 let root = tempfile::tempdir().unwrap();
1643 let active = write_global_user_config_in(
1644 root.path(),
1645 Some(crate::config::UserContext::Toggle(false)),
1646 )
1647 .unwrap();
1648 let cfg = crate::config::try_load_user_config_in(root.path())
1649 .unwrap()
1650 .unwrap();
1651 assert!(matches!(
1652 cfg.user_context,
1653 Some(crate::config::UserContext::Toggle(false))
1654 ));
1655 assert_eq!(active, None, "disabled → no active context path");
1656 assert!(
1658 !crate::config::default_user_context_path_in(root.path()).exists(),
1659 "disabled user context must not create a context.json"
1660 );
1661 }
1662
1663 #[test]
1664 fn write_global_user_config_custom_path_seeds_that_file_only() {
1665 let root = tempfile::tempdir().unwrap();
1666 let custom = root.path().join("custom-ctx.json");
1667 let active = write_global_user_config_in(
1668 root.path(),
1669 Some(crate::config::UserContext::Path(
1670 custom.to_string_lossy().into_owned(),
1671 )),
1672 )
1673 .unwrap();
1674 assert_eq!(active, Some(custom.clone()));
1675 assert!(custom.exists(), "the configured custom path must be seeded");
1676 assert!(
1677 !crate::config::default_user_context_path_in(root.path()).exists(),
1678 "the default context.json must NOT be created when a custom path is configured"
1679 );
1680 }
1681
1682 #[test]
1683 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1684 let root = tempfile::tempdir().unwrap();
1685 let custom = root.path().join("custom-ctx.json");
1686 write_global_user_config_in(
1688 root.path(),
1689 Some(crate::config::UserContext::Path(
1690 custom.to_string_lossy().into_owned(),
1691 )),
1692 )
1693 .unwrap();
1694 let active = write_global_user_config_in(root.path(), None).unwrap();
1696 assert_eq!(
1697 active,
1698 Some(custom.clone()),
1699 "re-run without flags must preserve the custom path"
1700 );
1701 let cfg = crate::config::try_load_user_config_in(root.path())
1702 .unwrap()
1703 .unwrap();
1704 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1705 }
1706
1707 #[test]
1708 fn install_global_codex_hooks_writes_and_is_idempotent() {
1709 let tmp = tempfile::tempdir().unwrap();
1710 let codex_dir = tmp.path().join(".codex");
1711
1712 install_global_codex_hooks(&codex_dir).unwrap();
1713 install_global_codex_hooks(&codex_dir).unwrap();
1714
1715 let v: serde_json::Value =
1716 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1717 .unwrap();
1718 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1719 let arr = v["hooks"][event].as_array().unwrap();
1720 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1721 }
1722 assert!(v["hooks"].get("PreToolUse").is_none());
1723 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1725 assert_eq!(
1726 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1727 1,
1728 "AGENTS.md workspace-mode block must appear exactly once"
1729 );
1730 let leftover = fs::read_dir(&codex_dir)
1732 .unwrap()
1733 .filter_map(|e| e.ok())
1734 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1735 assert!(!leftover);
1736 }
1737
1738 #[test]
1739 fn codex_hooks_has_expected_events_and_commands() {
1740 let h = codex_hooks();
1741 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1742 assert!(h.get(event).is_some(), "missing codex event {event}");
1743 }
1744 assert!(h.get("PreToolUse").is_none());
1748 assert!(h.get("Notification").is_none());
1749 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1751 assert_eq!(
1752 cmd("PostToolUse"),
1753 "tracevault stream --event post-tool-use --agent codex"
1754 );
1755 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1756 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1757 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1758 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1760 }
1761
1762 #[test]
1763 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1764 let tmp = tempfile::tempdir().unwrap();
1765 install_codex_hooks(tmp.path()).unwrap();
1766 install_codex_hooks(tmp.path()).unwrap();
1767
1768 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1769 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1770 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1771 let arr = v["hooks"][event].as_array().unwrap();
1772 assert_eq!(
1773 arr.len(),
1774 1,
1775 "event {event} must not be duplicated on re-run"
1776 );
1777 }
1778 assert!(v["hooks"].get("PreToolUse").is_none());
1779 }
1780
1781 #[test]
1782 fn install_codex_hooks_preserves_existing_user_hook() {
1783 let tmp = tempfile::tempdir().unwrap();
1784 let codex_dir = tmp.path().join(".codex");
1785 fs::create_dir_all(&codex_dir).unwrap();
1786 fs::write(
1789 codex_dir.join("hooks.json"),
1790 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1791 )
1792 .unwrap();
1793
1794 install_codex_hooks(tmp.path()).unwrap();
1795
1796 let v: serde_json::Value =
1797 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1798 .unwrap();
1799 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1801 .as_array()
1802 .unwrap()
1803 .iter()
1804 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1805 .collect();
1806 assert!(
1807 post_cmds.contains(&"my-own"),
1808 "user PostToolUse hook preserved"
1809 );
1810 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1811 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1813 .as_array()
1814 .unwrap()
1815 .iter()
1816 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1817 .collect();
1818 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1819 }
1820
1821 #[test]
1822 fn validate_init_flags_rejects_claude_settings_with_codex() {
1823 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1824 }
1825
1826 #[test]
1827 fn validate_init_flags_allows_codex_without_claude_settings() {
1828 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1829 }
1830
1831 #[test]
1832 fn validate_init_flags_allows_claude_with_claude_settings() {
1833 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1834 }
1835
1836 #[test]
1837 fn merge_hooks_into_file_rejects_parent_dir() {
1838 let tmp = tempfile::tempdir().unwrap();
1839 let bad = tmp.path().join("..").join("hooks.json");
1840 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1841 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1842 }
1843
1844 #[test]
1845 fn append_workspace_md_rejects_parent_dir() {
1846 let tmp = tempfile::tempdir().unwrap();
1847 let bad = tmp.path().join("..").join("AGENTS.md");
1848 let err = append_workspace_md(&bad).unwrap_err();
1849 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1850 }
1851
1852 #[tokio::test]
1853 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1854 let tmp = tempfile::tempdir().unwrap();
1855 let root = tmp.path();
1856 crate::test_helpers::init_git_repo(root);
1857
1858 let entry = init_in_directory(
1859 root,
1860 None,
1861 None,
1862 false,
1863 crate::config::UserContext::Toggle(false),
1864 crate::agent::Agent::Codex,
1865 )
1866 .await
1867 .unwrap();
1868
1869 assert!(root.join(".codex").join("hooks.json").exists());
1871 assert!(!root.join(".claude").join("settings.json").exists());
1872 assert_eq!(entry, ".codex/hooks.json");
1873
1874 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1876 assert!(gi.contains(".codex/hooks.json"));
1877 assert!(gi.contains(".tracevault/"));
1878 }
1879
1880 #[tokio::test]
1892 async fn init_in_directory_registers_repo_and_persists_repo_id() {
1893 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1894 let tmp = tempfile::tempdir().unwrap();
1895 let root = tmp.path();
1896 crate::test_helpers::init_git_repo(root);
1897 add_origin_remote(root, "git@github.com:org/repo.git");
1898
1899 let repo_id = "11111111-1111-4111-8111-111111111111";
1900 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
1901 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
1904 http_response("404 Not Found", NO_REMOTE),
1905 http_response("200 OK", &body),
1906 ]);
1907
1908 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1909 _guard.set("XDG_CONFIG_HOME", tmp.path());
1910 _guard.set("TRACEVAULT_API_KEY", "tok");
1911 _guard.remove("TRACEVAULT_SERVER_URL");
1912
1913 init_in_directory(
1914 root,
1915 Some(&base),
1916 None,
1917 true,
1918 crate::config::UserContext::Toggle(false),
1919 crate::agent::Agent::Codex,
1920 )
1921 .await
1922 .unwrap();
1923
1924 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1925 assert_eq!(
1926 cfg.repo_id,
1927 Some(repo_id.to_string()),
1928 "successful registration must persist repo_id to config.toml"
1929 );
1930 }
1931
1932 #[tokio::test]
1938 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
1939 let _env_lock = crate::test_helpers::lock_env_mutation().await;
1940 let tmp = tempfile::tempdir().unwrap();
1941 let root = tmp.path();
1942 crate::test_helpers::init_git_repo(root);
1943 add_origin_remote(root, "git@github.com:org/repo.git");
1944
1945 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
1946 http_response("404 Not Found", NO_REMOTE),
1947 http_response("403 Forbidden", ""),
1948 ]);
1949
1950 let mut _guard = crate::test_helpers::EnvVarGuard::new();
1951 _guard.set("XDG_CONFIG_HOME", tmp.path());
1952 _guard.set("TRACEVAULT_API_KEY", "tok");
1953 _guard.remove("TRACEVAULT_SERVER_URL");
1954
1955 let entry = init_in_directory(
1956 root,
1957 Some(&base),
1958 None,
1959 true,
1960 crate::config::UserContext::Toggle(false),
1961 crate::agent::Agent::Codex,
1962 )
1963 .await
1964 .expect("a registration failure (403) must not abort init itself");
1965 assert_eq!(entry, ".codex/hooks.json");
1966
1967 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
1968 assert!(
1969 cfg.repo_id.is_none(),
1970 "a 403 registration failure must not persist a repo_id"
1971 );
1972 }
1973
1974 #[tokio::test]
1979 async fn registration_failure_message_flags_403_as_not_authorized() {
1980 let base = spawn_once(http_response("403 Forbidden", ""));
1981 let client = ApiClient::new(&base, Some("tok"));
1982 let err = client
1983 .register_repo(crate::api_client::RegisterRepoRequest {
1984 repo_name: "repo".into(),
1985 github_url: Some("git@github.com:org/repo.git".into()),
1986 })
1987 .await
1988 .unwrap_err();
1989 let msg = registration_failure_message(err.as_ref());
1990 assert!(
1991 msg.contains("not authorized"),
1992 "403 registration failure must surface a not-authorized message; got: {msg}"
1993 );
1994 }
1995
1996 #[tokio::test]
1999 async fn registration_failure_message_generic_for_non_403() {
2000 let base = spawn_once(http_response("500 Internal Server Error", ""));
2001 let client = ApiClient::new(&base, Some("tok"));
2002 let err = client
2003 .register_repo(crate::api_client::RegisterRepoRequest {
2004 repo_name: "repo".into(),
2005 github_url: Some("git@github.com:org/repo.git".into()),
2006 })
2007 .await
2008 .unwrap_err();
2009 let msg = registration_failure_message(err.as_ref());
2010 assert!(
2011 msg.contains("could not register repo on server"),
2012 "got: {msg}"
2013 );
2014 assert!(!msg.contains("not authorized"), "got: {msg}");
2015 }
2016
2017 #[tokio::test]
2022 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2023 let base = spawn_once(http_response(
2024 "500 Internal Server Error",
2025 "upstream error 403 from proxy",
2026 ));
2027 let client = ApiClient::new(&base, Some("tok"));
2028 let err = client
2029 .register_repo(crate::api_client::RegisterRepoRequest {
2030 repo_name: "repo".into(),
2031 github_url: Some("git@github.com:org/repo.git".into()),
2032 })
2033 .await
2034 .unwrap_err();
2035 let msg = registration_failure_message(err.as_ref());
2036 assert!(
2037 !msg.contains("not authorized"),
2038 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2039 );
2040 assert!(
2041 msg.contains("could not register repo on server"),
2042 "got: {msg}"
2043 );
2044 }
2045
2046 #[tokio::test]
2050 async fn registration_failure_message_flags_404_as_version_mismatch() {
2051 let base = spawn_once(http_response("404 Not Found", ""));
2052 let client = ApiClient::new(&base, Some("tok"));
2053 let err = client
2054 .register_repo(crate::api_client::RegisterRepoRequest {
2055 repo_name: "repo".into(),
2056 github_url: Some("git@github.com:org/repo.git".into()),
2057 })
2058 .await
2059 .unwrap_err();
2060 let msg = registration_failure_message(err.as_ref());
2061 assert!(
2062 msg.to_lowercase().contains("version mismatch"),
2063 "a 404 registration failure should hint at a version mismatch; got: {msg}"
2064 );
2065 }
2066
2067 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2071 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2072 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2073 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2074
2075 fn resolve_remote_ok() -> String {
2076 http_response(
2077 "200 OK",
2078 &format!(
2079 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2080 ),
2081 )
2082 }
2083
2084 fn remote_detail(repos: &[(&str, &str)]) -> String {
2085 let repos: Vec<String> = repos
2086 .iter()
2087 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
2088 .collect();
2089 http_response(
2090 "200 OK",
2091 &format!(
2092 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
2093 repos.join(",")
2094 ),
2095 )
2096 }
2097
2098 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
2101 let (base, rx) = crate::test_helpers::spawn_seq(responses);
2102 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2103 _guard.set("XDG_CONFIG_HOME", root);
2104 _guard.set("TRACEVAULT_API_KEY", "tok");
2105 _guard.remove("TRACEVAULT_SERVER_URL");
2106
2107 init_in_directory(
2108 root,
2109 Some(&base),
2110 None,
2111 true,
2112 crate::config::UserContext::Toggle(false),
2113 crate::agent::Agent::Codex,
2114 )
2115 .await
2116 .expect("init succeeds");
2117
2118 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2119 (cfg.repo_id, rx.try_iter().collect())
2120 }
2121
2122 fn registered(requests: &[String]) -> bool {
2123 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
2124 }
2125
2126 #[tokio::test]
2129 async fn init_binds_the_existing_repo_of_a_known_remote() {
2130 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2131 let tmp = tempfile::tempdir().unwrap();
2132 crate::test_helpers::init_git_repo(tmp.path());
2133 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2134
2135 let (repo_id, requests) = init_against(
2136 tmp.path(),
2137 vec![
2138 resolve_remote_ok(),
2139 remote_detail(&[(CANONICAL, "tracevault")]),
2140 ],
2141 )
2142 .await;
2143
2144 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2145 assert!(!registered(&requests), "requests: {requests:?}");
2146 }
2147
2148 #[tokio::test]
2151 async fn init_binds_the_record_named_like_the_checkout() {
2152 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2153 let tmp = tempfile::tempdir().unwrap();
2154 crate::test_helpers::init_git_repo(tmp.path());
2155 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2156 let dir_name = crate::resolution::git_repo_name(tmp.path());
2157
2158 let (repo_id, requests) = init_against(
2159 tmp.path(),
2160 vec![
2161 resolve_remote_ok(),
2162 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
2163 ],
2164 )
2165 .await;
2166
2167 assert_eq!(repo_id.as_deref(), Some(STRAY));
2168 assert!(!registered(&requests));
2169 }
2170
2171 #[tokio::test]
2173 async fn init_rerun_keeps_the_previously_bound_repo() {
2174 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2175 let tmp = tempfile::tempdir().unwrap();
2176 crate::test_helpers::init_git_repo(tmp.path());
2177 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2178 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
2179 fs::write(
2180 tmp.path().join(".tracevault/config.toml"),
2181 format!("repo_id = \"{STRAY}\"\n"),
2182 )
2183 .unwrap();
2184
2185 let (repo_id, requests) = init_against(
2186 tmp.path(),
2187 vec![
2188 resolve_remote_ok(),
2189 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2190 ],
2191 )
2192 .await;
2193
2194 assert_eq!(repo_id.as_deref(), Some(STRAY));
2195 assert!(!registered(&requests));
2196 }
2197
2198 #[tokio::test]
2200 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
2201 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2202 let tmp = tempfile::tempdir().unwrap();
2203 crate::test_helpers::init_git_repo(tmp.path());
2204 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2205
2206 let (repo_id, requests) = init_against(
2207 tmp.path(),
2208 vec![
2209 resolve_remote_ok(),
2210 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
2211 ],
2212 )
2213 .await;
2214
2215 assert_eq!(repo_id, None);
2216 assert!(!registered(&requests));
2217 }
2218
2219 #[tokio::test]
2222 async fn init_registers_for_a_codebase_without_live_repos() {
2223 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2224 let tmp = tempfile::tempdir().unwrap();
2225 crate::test_helpers::init_git_repo(tmp.path());
2226 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2227
2228 let (repo_id, requests) = init_against(
2229 tmp.path(),
2230 vec![
2231 resolve_remote_ok(),
2232 remote_detail(&[]),
2233 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
2234 ],
2235 )
2236 .await;
2237
2238 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
2239 assert!(registered(&requests));
2240 }
2241
2242 #[tokio::test]
2244 async fn init_does_not_register_when_the_remote_check_fails() {
2245 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2246 let tmp = tempfile::tempdir().unwrap();
2247 crate::test_helpers::init_git_repo(tmp.path());
2248 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
2249
2250 let (repo_id, requests) = init_against(
2251 tmp.path(),
2252 vec![http_response("500 Internal Server Error", "{}")],
2253 )
2254 .await;
2255
2256 assert_eq!(repo_id, None);
2257 assert!(!registered(&requests));
2258 }
2259}