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
109 | crate::agent::Agent::Gsd
110 | crate::agent::Agent::OpenCode
111 | crate::agent::Agent::Amp
112 ) && claude_settings_set
113 {
114 return Err("--claude-settings only applies to --agent claude-code".to_string());
115 }
116 Ok(())
117}
118
119pub async fn init_in_directory(
124 project_root: &Path,
125 server_url: Option<&str>,
126 claude_settings: Option<ClaudeSettingsTarget>,
127 no_gitignore: bool,
128 user_context: Option<UserContext>,
129 agent: crate::agent::Agent,
130) -> Result<String, io::Error> {
131 if !project_root.join(".git").exists() {
133 return Err(io::Error::new(
134 io::ErrorKind::NotFound,
135 "Not a git repository. Run 'git init' first.",
136 ));
137 }
138
139 if let Some(primary) = linked_worktree_primary(project_root) {
145 return Err(io::Error::new(
146 io::ErrorKind::Unsupported,
147 format!(
148 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
149 cd there and run it again — all worktrees share the primary's .tracevault/.",
150 primary.display()
151 ),
152 ));
153 }
154
155 let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
159 io::Error::new(
160 io::ErrorKind::InvalidData,
161 format!(
162 "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
163 then run `tracevault init` again."
164 ),
165 )
166 })?;
167
168 let (resolved_url, resolved_credential) =
177 crate::credentials::resolve_credentials_quiet(project_root)
178 .map_err(|e| io::Error::other(e.to_string()))?;
179 let effective_url = server_url.map(String::from).or(resolved_url.clone());
180 if resolved_credential.is_none() {
181 return Err(io::Error::new(
182 io::ErrorKind::PermissionDenied,
183 not_logged_in_message(effective_url.as_deref()),
184 ));
185 }
186
187 let mut existing_config = existing_config;
192 if let (Some(cfg), Some(url)) = (existing_config.as_mut(), effective_url.as_deref()) {
193 if cfg.default_project.is_some() {
194 match credential_url_mismatch(resolved_url.as_deref(), server_url) {
197 Some(msg) => eprintln!(
198 "Warning: not migrating default_project: {msg}. Run `tracevault sync` \
199 once logged in to that server."
200 ),
201 None => {
202 let client = ApiClient::with_credential(url, resolved_credential.clone());
203 migrate_config_in_init(cfg, &client).await?;
204 }
205 }
206 }
207 }
208
209 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
212 {
213 crate::agent::Agent::ClaudeCode => {
214 let target = resolve_claude_target(claude_settings)?;
215 (Some(target), target.gitignore_entry().to_string())
216 }
217 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
218 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
224 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
229 crate::agent::Agent::Amp => (None, AMP_PLUGIN_GITIGNORE_ENTRY.to_string()),
232 };
233
234 let config_dir = TracevaultConfig::config_dir(project_root);
236 fs::create_dir_all(&config_dir)?;
237 fs::create_dir_all(config_dir.join("sessions"))?;
238 fs::create_dir_all(config_dir.join("cache"))?;
239 TracevaultConfig::ensure_gitignore(&config_dir)?;
242
243 if !no_gitignore {
245 update_root_gitignore(project_root, &hook_gitignore_entry)?;
246 }
247
248 let remote_url = git_remote_url(project_root);
250 if remote_url.is_none() {
251 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
252 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
253 }
254
255 let mut config = existing_config.unwrap_or_default();
260 if let Some(url) = server_url {
261 config.server_url = Some(url.to_string());
262 }
263 config.user_context = user_context
264 .or(config.user_context)
265 .or(Some(UserContext::Toggle(true)));
266 config.save(project_root)?;
267
268 let previous_repo_id = config
271 .repo_id
272 .as_deref()
273 .and_then(|id| id.parse::<uuid::Uuid>().ok());
274
275 match agent {
277 crate::agent::Agent::ClaudeCode => {
278 let target =
280 claude_target.expect("claude settings target is resolved for the Claude agent");
281 install_claude_hooks(project_root, target)?;
282 }
283 crate::agent::Agent::Codex => {
284 install_codex_hooks(project_root)?;
285 println!("{}", codex_hook_trust_notice());
286 }
287 crate::agent::Agent::Gsd => {
288 install_gsd_extension(Some(project_root))?;
296 }
297 crate::agent::Agent::OpenCode => {
298 install_opencode_plugin(Some(project_root))?;
299 }
300 crate::agent::Agent::Amp => {
301 let path = install_amp_plugin(Some(project_root))?;
302 println!("Installed the TraceVault Amp plugin in {}", path.display());
303 println!("{}", amp_headless_notice());
304 }
305 }
306
307 install_git_hook(project_root)?;
309 install_post_commit_hook(project_root)?;
310
311 let detected = crate::hooks::detect_tools(project_root);
313 for tool in &detected {
314 println!(" Detected: {}", tool.name());
315 }
316
317 if let (Some(url), Some(remote)) = (effective_url, remote_url) {
318 let client = ApiClient::with_credential(&url, resolved_credential);
319 let repo_name = git_repo_name(project_root);
320 let origin_url = remote.clone();
323
324 match crate::resolution::plan_registration(
328 &client,
329 &origin_url,
330 &repo_name,
331 previous_repo_id,
332 )
333 .await
334 {
335 Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
336 println!(
337 "Bound to existing repo {} (id: {repo_id}); not registering another record \
338 for this codebase",
339 codebase
340 .repos
341 .iter()
342 .find(|r| r.id == repo_id)
343 .map_or("", |r| r.name.as_str())
344 );
345 println!(
346 "{}",
347 crate::resolution::codebase_line(
348 codebase.remote.name.as_deref(),
349 &codebase.remote.normalized_url,
350 &codebase.remote.clone_status
351 )
352 );
353 persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
354 }
355 Ok(RegistrationPlan::Ambiguous(codebase)) => {
356 eprintln!(
357 "Warning: codebase {} already has {} repo records ({}) and none is named \
358 '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
359 .tracevault/config.toml to the one this checkout belongs to.",
360 codebase.display_name(),
361 codebase.repos.len(),
362 codebase.repo_list()
363 );
364 }
365 Ok(RegistrationPlan::Register) => {
366 register_new_repo(&client, project_root, repo_name, origin_url).await;
367 }
368 Err(e) => {
371 eprintln!(
372 "Warning: could not check the server for an existing repo of this remote \
373 ({e}); not registering. Run `tracevault init` again once the server is \
374 reachable."
375 );
376 }
377 }
378 }
379
380 Ok(hook_gitignore_entry)
381}
382
383async fn migrate_config_in_init(
388 config: &mut TracevaultConfig,
389 client: &ApiClient,
390) -> Result<(), io::Error> {
391 use crate::commands::migrate::{migrate_default_project, migration_report, ResolveNameError};
392 match migrate_default_project(config, client).await {
393 Ok(migration) => {
394 if let Some(line) = migration_report(&migration) {
395 println!("{line}");
396 }
397 Ok(())
398 }
399 Err(ResolveNameError::Unreachable(e)) => {
400 eprintln!(
401 "Warning: could not migrate default_project (could not list projects: {e}); \
402 it stays unused for capture until `tracevault sync` succeeds."
403 );
404 Ok(())
405 }
406 Err(e @ ResolveNameError::Name(_)) => {
407 Err(io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))
408 }
409 }
410}
411
412pub async fn migrate_cwd_config(cwd: &Path) -> Result<(), io::Error> {
420 let root = crate::paths::resolve_project_root(cwd).root;
421 let Ok(Some(mut config)) = TracevaultConfig::try_load(&root) else {
422 return Ok(());
423 };
424 if config.default_project.is_none() {
425 return Ok(());
426 }
427 let Ok((Some(url), credential @ Some(_))) =
428 crate::credentials::resolve_credentials_quiet(&root)
429 else {
430 eprintln!(
431 "Warning: {} has a legacy default_project that needs a login to migrate; run \
432 `tracevault sync` there once logged in.",
433 TracevaultConfig::config_path(&root).display()
434 );
435 return Ok(());
436 };
437 let client = ApiClient::with_credential(&url, credential);
438 migrate_config_in_init(&mut config, &client).await?;
439 if config.default_project.is_none() {
440 config.save(&root)?;
441 }
442 Ok(())
443}
444
445fn credential_url_mismatch(resolved: Option<&str>, explicit: Option<&str>) -> Option<String> {
453 let env_key = std::env::var("TRACEVAULT_API_KEY")
454 .ok()
455 .is_some_and(|k| !k.trim().is_empty());
456 if env_key {
457 return None;
458 }
459 let (resolved, explicit) = (resolved?, explicit?);
460 (!crate::credentials::same_server(resolved, explicit)).then(|| {
461 format!(
462 "the credential in use is for {resolved}, not --server-url {explicit}; log in \
463 there first (`tracevault login --server-url {explicit}`) or omit --server-url"
464 )
465 })
466}
467
468#[derive(Debug)]
470pub struct WorkspaceInit {
471 pub project_id: uuid::Uuid,
472 pub project_name: String,
473 pub config_path: PathBuf,
475}
476
477pub async fn init_workspace(
493 dir: &Path,
494 project_name: &str,
495 server_url: Option<&str>,
496) -> Result<WorkspaceInit, io::Error> {
497 let resolved = crate::paths::resolve_project_root(dir);
498 if resolved.source == crate::paths::ProjectRootSource::Git {
499 let same = match (resolved.root.canonicalize(), dir.canonicalize()) {
500 (Ok(a), Ok(b)) => a == b,
501 _ => resolved.root == dir,
502 };
503 if !same {
504 return Err(io::Error::new(
505 io::ErrorKind::InvalidInput,
506 format!(
507 "{} is inside the git repo {}; sessions here read that repo's \
508 .tracevault/config.toml, so a workspace binding here would never be used. \
509 Run `tracevault init --workspace` from the repo root or from a directory \
510 that is not inside a repo.",
511 dir.display(),
512 resolved.root.display()
513 ),
514 ));
515 }
516 }
517
518 let existing = TracevaultConfig::try_load(dir).map_err(|e| {
519 io::Error::new(
520 io::ErrorKind::InvalidData,
521 format!(
522 "cannot read the existing .tracevault/config.toml ({e}). Fix or remove it, \
523 then run `tracevault init --workspace` again."
524 ),
525 )
526 })?;
527
528 let (resolved_url, credential) = crate::credentials::resolve_credentials_quiet(dir)
529 .map_err(|e| io::Error::other(e.to_string()))?;
530 if let Some(msg) = credential_url_mismatch(resolved_url.as_deref(), server_url) {
533 return Err(io::Error::new(io::ErrorKind::PermissionDenied, msg));
534 }
535 let url = server_url.map(String::from).or(resolved_url);
536 let (Some(url), Some(_)) = (url.as_deref(), credential.as_ref()) else {
537 return Err(io::Error::new(
538 io::ErrorKind::PermissionDenied,
539 format!(
540 "Not logged in. `init --workspace` resolves the project name on the server, \
541 so nothing was written.\nLog in, then run it again:\n\n \
542 tracevault login --server-url {}\n \
543 tracevault init --workspace --project {project_name}",
544 url.as_deref().unwrap_or("<URL>")
545 ),
546 ));
547 };
548 let client = ApiClient::with_credential(url, credential);
549 let project = crate::commands::migrate::resolve_project_by_name(&client, project_name)
550 .await
551 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
552
553 let config_dir = TracevaultConfig::config_dir(dir);
554 fs::create_dir_all(&config_dir)?;
555 TracevaultConfig::ensure_gitignore(&config_dir)?;
556
557 let mut config = existing.unwrap_or_default();
558 if let Some(url) = server_url {
559 config.server_url = Some(url.to_string());
560 }
561 config.project_id = Some(project.id.to_string());
562 config.project_name = Some(project.name.clone());
563 config.default_project = None;
564 config.save(dir)?;
565
566 Ok(WorkspaceInit {
567 project_id: project.id,
568 project_name: project.name,
569 config_path: TracevaultConfig::config_path(dir),
570 })
571}
572
573pub fn not_logged_in_message(url: Option<&str>) -> String {
578 let url = url.unwrap_or("<URL>");
579 format!(
580 "Not logged in. Without a login TraceVault cannot register this repo, and its hooks \
581 would record nothing, so nothing was installed.\n\
582 Log in, then run init again:\n\
583 \n tracevault login --server-url {url}\n tracevault init\n\n\
584 (In CI, set TRACEVAULT_API_KEY instead of logging in.)"
585 )
586}
587
588pub(crate) fn persist_repo_binding(
595 project_root: &Path,
596 repo_id: uuid::Uuid,
597 codebase: Option<&crate::api_client::ResolveRemoteResponse>,
598) -> bool {
599 let Some(mut cfg) = TracevaultConfig::load(project_root) else {
600 return false;
601 };
602 cfg.repo_id = Some(repo_id.to_string());
603 if let Some(remote) = codebase {
604 cfg.remote_id = Some(remote.remote_id.to_string());
605 cfg.codebase_name = remote.name.clone();
606 }
607 cfg.save(project_root).is_ok()
608}
609
610async fn register_new_repo(
614 client: &ApiClient,
615 project_root: &Path,
616 repo_name: String,
617 origin_url: String,
618) {
619 match client
620 .register_repo(crate::api_client::RegisterRepoRequest {
621 repo_name,
622 github_url: Some(origin_url.clone()),
623 })
624 .await
625 {
626 Ok(resp) => {
627 println!("Repo registered on server (id: {})", resp.repo_id);
628 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
630 cfg.repo_id = Some(resp.repo_id.to_string());
631 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
637 println!(
638 "{}",
639 crate::resolution::codebase_line(
640 remote.name.as_deref(),
641 &remote.normalized_url,
642 &remote.clone_status
643 )
644 );
645 cfg.remote_id = Some(remote.remote_id.to_string());
646 cfg.codebase_name = remote.name.clone();
647 }
648 let _ = cfg.save(project_root);
649 }
650 }
651 Err(e) => {
652 eprintln!("{}", registration_failure_message(e.as_ref()));
653 }
654 }
655}
656
657fn registration_failure_message(err: &dyn std::error::Error) -> String {
672 let msg = err.to_string();
673 if msg.starts_with("Server returned 403 ") {
674 "Warning: you are not authorized to register this repo.".to_string()
675 } else if msg.starts_with("Server returned 404 ") {
676 "Warning: could not register repo on server (404) — this endpoint may not exist on \
677 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
678 once the server is upgraded."
679 .to_string()
680 } else {
681 format!("Warning: could not register repo on server: {err}")
682 }
683}
684
685fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
686 let path = project_root.join(".gitignore");
687 let existing = if path.exists() {
688 fs::read_to_string(&path)?
689 } else {
690 String::new()
691 };
692
693 let needed: Vec<&str> = [".tracevault/", settings_entry]
699 .iter()
700 .copied()
701 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
702 .collect();
703
704 if needed.is_empty() {
705 return Ok(());
706 }
707
708 let mut content = existing;
709 if !content.is_empty() && !content.ends_with('\n') {
710 content.push('\n');
711 }
712 content.push_str("\n# TraceVault — local only, do not commit\n");
713 for entry in needed {
714 content.push_str(entry);
715 content.push('\n');
716 }
717
718 fs::write(path, content)
719}
720
721const HOOK_MARKER: &str = "# tracevault:enforce";
722const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
723
724fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
725 let hooks_dir = project_root.join(".git/hooks");
726 fs::create_dir_all(&hooks_dir)?;
727
728 let hook_path = hooks_dir.join("pre-push");
729 let tracevault_block = format!(
736 "{HOOK_MARKER}\n\
737 # Capture git's pre-push ref list once; `check` uses it to determine\n\
738 # which files are being pushed.\n\
739 tracevault_prepush_stdin=$(cat)\n\
740 tracevault sync 2>/dev/null || true\n\
741 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
742 );
743
744 if hook_path.exists() {
745 let existing = fs::read_to_string(&hook_path)?;
746
747 if existing.contains(HOOK_MARKER) {
749 return Ok(());
750 }
751
752 if existing.contains(OLD_HOOK_MARKER) {
754 let mut new_content = String::new();
755 let mut skip = false;
756 for line in existing.lines() {
757 if line.contains(OLD_HOOK_MARKER) {
758 skip = true;
759 continue;
760 }
761 if skip {
762 if line.starts_with("tracevault ") {
764 continue;
765 }
766 skip = false;
767 }
768 new_content.push_str(line);
769 new_content.push('\n');
770 }
771 if !new_content.ends_with('\n') {
772 new_content.push('\n');
773 }
774 new_content.push_str(&tracevault_block);
775 fs::write(&hook_path, new_content)?;
776 } else {
777 let mut content = existing;
779 if !content.ends_with('\n') {
780 content.push('\n');
781 }
782 content.push_str(&tracevault_block);
783 fs::write(&hook_path, content)?;
784 }
785 } else {
786 let content = format!("#!/bin/sh\n{tracevault_block}");
787 fs::write(&hook_path, content)?;
788 }
789
790 #[cfg(unix)]
792 {
793 use std::os::unix::fs::PermissionsExt;
794 let mut perms = fs::metadata(&hook_path)?.permissions();
795 perms.set_mode(0o755);
796 fs::set_permissions(&hook_path, perms)?;
797 }
798
799 Ok(())
800}
801
802const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
803
804fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
805 let hooks_dir = project_root.join(".git/hooks");
806 fs::create_dir_all(&hooks_dir)?;
807
808 let hook_path = hooks_dir.join("post-commit");
809 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
810
811 if hook_path.exists() {
812 let existing = fs::read_to_string(&hook_path)?;
813
814 if existing.contains(POST_COMMIT_MARKER) {
815 return Ok(());
816 }
817
818 let mut content = existing;
819 if !content.ends_with('\n') {
820 content.push('\n');
821 }
822 content.push_str(&tracevault_block);
823 fs::write(&hook_path, content)?;
824 } else {
825 let content = format!("#!/bin/sh\n{tracevault_block}");
826 fs::write(&hook_path, content)?;
827 }
828
829 #[cfg(unix)]
830 {
831 use std::os::unix::fs::PermissionsExt;
832 let mut perms = fs::metadata(&hook_path)?.permissions();
833 perms.set_mode(0o755);
834 fs::set_permissions(&hook_path, perms)?;
835 }
836
837 Ok(())
838}
839
840fn install_claude_hooks(
841 project_root: &Path,
842 target: ClaudeSettingsTarget,
843) -> Result<(), io::Error> {
844 let claude_dir = project_root.join(".claude");
845 fs::create_dir_all(&claude_dir)?;
846 merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
847}
848
849pub fn tracevault_hooks() -> serde_json::Value {
850 serde_json::json!({
851 "PreToolUse": [{
852 "matcher": "Write|Edit|Bash",
853 "hooks": [{
854 "type": "command",
855 "command": "tracevault stream --event pre-tool-use",
856 "timeout": 10,
857 "statusMessage": "TraceVault: streaming pre-tool event"
858 }]
859 }],
860 "PostToolUse": [{
861 "matcher": "",
862 "hooks": [{
863 "type": "command",
864 "command": "tracevault stream --event post-tool-use",
865 "timeout": 10,
866 "statusMessage": "TraceVault: streaming post-tool event"
867 }]
868 }],
869 "Notification": [{
870 "matcher": "",
871 "hooks": [{
872 "type": "command",
873 "command": "tracevault stream --event notification",
874 "timeout": 10,
875 "statusMessage": "TraceVault: streaming notification"
876 }]
877 }],
878 "Stop": [{
879 "matcher": "",
880 "hooks": [{
881 "type": "command",
882 "command": "tracevault stream --event stop",
883 "timeout": 10,
884 "statusMessage": "TraceVault: finalizing session"
885 }]
886 }],
887 "SessionEnd": [{
890 "matcher": "",
891 "hooks": [{
892 "type": "command",
893 "command": "tracevault stream --event session-end",
894 "timeout": 10,
895 "statusMessage": "TraceVault: sending session cost"
896 }]
897 }],
898 "SubagentStop": [{
901 "matcher": "",
902 "hooks": [{
903 "type": "command",
904 "command": "tracevault stream --event subagent-stop",
905 "timeout": 10,
906 "statusMessage": "TraceVault: streaming subagent transcript"
907 }]
908 }],
909 "SessionStart": [{
910 "matcher": "",
911 "hooks": [{
912 "type": "command",
913 "command": "tracevault session-start",
914 "timeout": 10,
915 "statusMessage": "TraceVault: session start"
916 }]
917 }],
918 "UserPromptSubmit": [{
919 "matcher": "",
920 "hooks": [{
921 "type": "command",
922 "command": "tracevault user-prompt",
923 "timeout": 10,
924 "statusMessage": "TraceVault: policy reinforcement"
925 }]
926 }]
927 })
928}
929
930pub fn codex_hook_trust_notice() -> &'static str {
940 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
941 silently and no session is captured. Run `codex` once interactively in a repo and \
942 approve the hook-trust prompt; unattended runs (CI) can pass \
943 `--dangerously-bypass-hook-trust` instead."
944}
945
946pub fn codex_hooks() -> serde_json::Value {
956 serde_json::json!({
957 "SessionStart": [{
958 "matcher": "",
959 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
960 }],
961 "UserPromptSubmit": [{
962 "matcher": "",
963 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
964 }],
965 "PostToolUse": [{
966 "matcher": "",
967 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
968 }],
969 "Stop": [{
970 "matcher": "",
971 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
972 }]
973 })
974}
975
976const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
980const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
981const GSD_EXT_MANIFEST_JSON: &str =
982 include_str!("../../assets/gsd-extension/extension-manifest.json");
983
984fn gsd_extension_source_dir() -> io::Result<PathBuf> {
988 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
989 let config_dir = config_dir
990 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
991 Ok(config_dir.join("tracevault").join("gsd-extension"))
992}
993
994pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
1018 let home =
1019 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
1020 let gsd_home = home.join(".gsd");
1021
1022 let source_dir = gsd_extension_source_dir()?;
1023 fs::create_dir_all(&source_dir)?;
1024 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
1025 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
1026 fs::write(
1027 source_dir.join("extension-manifest.json"),
1028 GSD_EXT_MANIFEST_JSON,
1029 )?;
1030
1031 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
1035 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
1036 }
1037
1038 let local_flag = project_root.is_some();
1042 let mut cmd = std::process::Command::new("gsd");
1043 cmd.arg("install").arg(&source_dir);
1044 if let Some(root) = project_root {
1045 cmd.arg("-l");
1046 cmd.current_dir(root);
1047 }
1048
1049 let retry_hint = format!(
1050 "gsd install {}{}",
1051 source_dir.display(),
1052 if local_flag { " -l" } else { "" }
1053 );
1054
1055 match cmd.output() {
1056 Ok(output) if output.status.success() => {
1057 println!(
1058 "TraceVault: installed and registered the GSD extension ({}).",
1059 source_dir.display()
1060 );
1061 }
1062 Ok(output) => {
1063 eprintln!(
1064 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
1065 source_dir.display(),
1066 String::from_utf8_lossy(&output.stderr),
1067 );
1068 }
1069 Err(e) => {
1070 eprintln!(
1071 "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.",
1072 source_dir.display(),
1073 );
1074 }
1075 }
1076
1077 Ok(())
1078}
1079
1080const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
1083
1084pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
1100 let plugins_dir = match project_root {
1101 Some(root) => root.join(".opencode").join("plugins"),
1102 None => {
1103 let config_dir =
1104 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
1105 config_dir
1106 .ok_or_else(|| {
1107 io::Error::new(
1108 io::ErrorKind::NotFound,
1109 "could not determine the config directory for the OpenCode plugin install",
1110 )
1111 })?
1112 .join("opencode")
1113 .join("plugins")
1114 }
1115 };
1116
1117 write_opencode_plugin_files(&plugins_dir)
1118}
1119
1120fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
1121 fs::create_dir_all(plugins_dir)?;
1122 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
1123 Ok(())
1124}
1125
1126pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");
1129
1130const AMP_PLUGIN_GITIGNORE_ENTRY: &str = ".amp/plugins/tracevault/";
1132
1133pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
1142 let plugins_dir = match project_root {
1143 Some(root) => root.join(".amp").join("plugins"),
1144 None => amp_user_config_dir()
1145 .ok_or_else(|| {
1146 io::Error::new(
1147 io::ErrorKind::NotFound,
1148 "could not determine the config directory for the Amp plugin install",
1149 )
1150 })?
1151 .join("plugins"),
1152 };
1153 let plugin_dir = plugins_dir.join("tracevault");
1154 fs::create_dir_all(&plugin_dir)?;
1155 let path = plugin_dir.join("index.ts");
1156 fs::write(&path, AMP_PLUGIN_INDEX)?;
1157 Ok(path)
1158}
1159
1160fn amp_user_config_dir() -> Option<PathBuf> {
1164 let xdg = std::env::var_os("XDG_CONFIG_HOME")
1165 .map(PathBuf::from)
1166 .filter(|p| p.is_absolute());
1167 xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
1168 .map(|c| c.join("amp"))
1169}
1170
1171pub fn amp_headless_notice() -> &'static str {
1176 "Amp loads the plugin in interactive sessions. For headless runs use \
1177`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
1178starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
1179path), so allow what it needs up front.\n\
1180The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
1181unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
1182ampcode.com, or exports it, can read them."
1183}
1184
1185pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
1197 let ext_root = gsd_home.join("extensions");
1198 let reg_path = ext_root.join("registry.json");
1199
1200 let reg: Option<serde_json::Value> = if reg_path.exists() {
1205 let content = fs::read_to_string(®_path)?;
1206 let parsed: serde_json::Value = match serde_json::from_str(&content) {
1207 Ok(v) => v,
1208 Err(_) => return Ok(()), };
1210 let corrupt = match parsed.as_object() {
1211 None => true,
1212 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
1213 };
1214 if corrupt {
1215 return Ok(()); }
1217 Some(parsed)
1218 } else {
1219 None
1220 };
1221
1222 let stale = ext_root.join("tracevault-tracker");
1224 if stale.exists() {
1225 fs::remove_dir_all(&stale)?;
1226 }
1227
1228 if let Some(mut reg) = reg {
1230 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
1231 let removed_tracker = entries.remove("tracevault-tracker").is_some();
1232 let removed_inert = entries.remove("tracevault").is_some();
1233 if removed_tracker || removed_inert {
1234 let tmp = reg_path.with_extension("json.tmp");
1236 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
1237 fs::rename(&tmp, ®_path)?;
1238 }
1239 }
1240 }
1241 Ok(())
1242}
1243
1244fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
1254 update_json_file(hooks_path, "its hooks", |root| {
1255 merge_hooks(root, ours, hooks_path)
1256 })
1257}
1258
1259pub(crate) fn update_json_file(
1267 path: &Path,
1268 what: &str,
1269 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
1270) -> io::Result<()> {
1271 if path
1276 .components()
1277 .any(|c| c == std::path::Component::ParentDir)
1278 {
1279 return Err(io::Error::new(
1280 io::ErrorKind::InvalidInput,
1281 format!("refusing to use path with '..': {}", path.display()),
1282 ));
1283 }
1284 let target = match fs::symlink_metadata(path) {
1288 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
1289 _ => path.to_path_buf(),
1290 };
1291 for _ in 0..3 {
1297 let existing = read_existing(&target)?;
1298 let mut root: serde_json::Value = match &existing {
1299 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1300 io::Error::new(
1301 io::ErrorKind::InvalidData,
1302 format!("Failed to parse {}: {e}", path.display()),
1303 )
1304 })?,
1305 None => serde_json::json!({}),
1306 };
1307
1308 let before = existing.is_some().then(|| root.to_string());
1309 mutate(&mut root)?;
1310 if before.as_deref() == Some(root.to_string().as_str())
1311 || (existing.is_none() && root == serde_json::json!({}))
1312 {
1313 return Ok(());
1314 }
1315
1316 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1317 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1318 })?;
1319 let tmp = unique_temp_sibling(&target);
1320 let published = write_owner_only(&tmp, formatted.as_bytes())
1321 .and_then(|()| {
1322 match &existing {
1325 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1326 None => Ok(()),
1327 }
1328 })
1329 .and_then(|()| {
1330 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1331 == existing.as_ref().map(|(_, c)| c.clone());
1332 if unchanged {
1333 fs::rename(&tmp, &target).map(|()| true)
1334 } else {
1335 Ok(false)
1336 }
1337 });
1338 match published {
1339 Ok(true) => return Ok(()),
1340 Ok(false) => {
1341 let _ = fs::remove_file(&tmp);
1342 }
1343 Err(e) => {
1344 let _ = fs::remove_file(&tmp);
1345 return Err(e);
1346 }
1347 }
1348 }
1349 Err(io::Error::other(format!(
1350 "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1351 path.display()
1352 )))
1353}
1354
1355fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1357 let permissions = match fs::metadata(path) {
1358 Ok(meta) => meta.permissions(),
1359 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1360 Err(e) => return Err(e),
1361 };
1362 Ok(Some((permissions, fs::read_to_string(path)?)))
1363}
1364
1365fn unique_temp_sibling(target: &Path) -> PathBuf {
1369 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1370 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1371 let nanos = std::time::SystemTime::now()
1372 .duration_since(std::time::UNIX_EPOCH)
1373 .map(|d| d.subsec_nanos())
1374 .unwrap_or_default();
1375 let mut name = target.file_name().unwrap_or_default().to_os_string();
1376 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1377 target.with_file_name(name)
1378}
1379
1380fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1384 let mut options = fs::OpenOptions::new();
1385 options.write(true).create_new(true);
1386 #[cfg(unix)]
1387 {
1388 use std::os::unix::fs::OpenOptionsExt;
1389 options.mode(0o600);
1390 }
1391 options.open(path)?.write_all(contents)
1392}
1393
1394pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1398 let codex_dir = project_root.join(".codex");
1399 fs::create_dir_all(&codex_dir)?;
1400 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1401}
1402
1403pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1410 fs::create_dir_all(codex_dir)?;
1411 let base = codex_dir.canonicalize()?;
1413 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1414 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1415}
1416
1417const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1421
1422const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1423<!-- tracevault:workspace-mode -->
1424## TraceVault (workspace mode)
1425A session started in a registered repo's checkout is bound to that repo automatically. To work
1426on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1427policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1428one-off. Repos must already be registered with TraceVault. In a directory bound to a project
1429with `tracevault init --workspace`, sessions are recorded to that project without it, so
1430`repo switch` there is optional: it only adds the repo and its policies.
1431";
1432
1433const PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS: &[&str] = &[
1437 "\
1438<!-- tracevault:workspace-mode -->
1439## TraceVault (workspace mode)
1440You may be running detached from any single repository. Before working on a repo, run
1441`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
1442output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
1443already be registered with TraceVault.
1444",
1445 "\
1446<!-- tracevault:workspace-mode -->
1447## TraceVault (workspace mode)
1448A session started in a registered repo's checkout is bound to that repo automatically. To work
1449on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1450policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1451one-off. Repos must already be registered with TraceVault.
1452",
1453];
1454
1455fn replace_managed_block(content: &str) -> String {
1460 if content.contains(GLOBAL_CLAUDE_MD_BLOCK) {
1461 return content.to_string();
1462 }
1463 PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS
1464 .iter()
1465 .find(|old| content.contains(*old))
1466 .map_or_else(
1467 || content.to_string(),
1468 |old| content.replacen(old, GLOBAL_CLAUDE_MD_BLOCK, 1),
1469 )
1470}
1471
1472fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1479 if md_path
1481 .components()
1482 .any(|c| c == std::path::Component::ParentDir)
1483 {
1484 return Err(io::Error::new(
1485 io::ErrorKind::InvalidInput,
1486 format!("refusing to use path with '..': {}", md_path.display()),
1487 ));
1488 }
1489 let existing = if md_path.exists() {
1490 fs::read_to_string(md_path)?
1491 } else {
1492 String::new()
1493 };
1494 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1495 let replaced = replace_managed_block(&existing);
1498 if replaced != existing {
1499 fs::write(md_path, replaced)?;
1500 }
1501 return Ok(());
1502 }
1503 let mut content = existing;
1504 if !content.is_empty() && !content.ends_with('\n') {
1505 content.push('\n');
1506 }
1507 if !content.is_empty() {
1508 content.push('\n');
1509 }
1510 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1511 fs::write(md_path, content)
1512}
1513
1514pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1518 let joined = base.join(name);
1519 if joined.parent() != Some(base) {
1520 return Err(io::Error::new(
1521 io::ErrorKind::InvalidInput,
1522 format!(
1523 "refusing to access path outside {}: {}",
1524 base.display(),
1525 joined.display()
1526 ),
1527 ));
1528 }
1529 Ok(joined)
1530}
1531
1532const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1538
1539fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1540 hook.get("command")
1541 .and_then(|c| c.as_str())
1542 .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1543}
1544
1545fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1552 let mut slot = None;
1553 let mut kept = Vec::with_capacity(entries.len());
1554 for mut entry in entries.drain(..) {
1555 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1556 let before = inner.len();
1557 inner.retain(|hook| !is_tracevault_hook(hook));
1558 if inner.is_empty() && before > 0 {
1559 slot.get_or_insert(kept.len());
1560 continue;
1561 }
1562 }
1563 kept.push(entry);
1564 }
1565 *entries = kept;
1566 slot
1567}
1568
1569fn merge_hooks(
1583 settings: &mut serde_json::Value,
1584 ours: &serde_json::Value,
1585 path: &Path,
1586) -> io::Result<()> {
1587 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1588 io::Error::new(
1589 io::ErrorKind::InvalidData,
1590 format!("{} is not a JSON object", path.display()),
1591 )
1592 })?;
1593
1594 let hooks_value = settings_obj
1595 .entry("hooks")
1596 .or_insert_with(|| serde_json::json!({}));
1597 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1598 io::Error::new(
1599 io::ErrorKind::InvalidData,
1600 format!("{} \"hooks\" key is not a JSON object", path.display()),
1601 )
1602 })?;
1603
1604 let empty = serde_json::Map::new();
1605 let ours_obj = ours.as_object().unwrap_or(&empty);
1606
1607 for event in ours_obj.keys() {
1609 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1610 return Err(io::Error::new(
1611 io::ErrorKind::InvalidData,
1612 format!(
1613 "{} \"hooks\".\"{event}\" is not a JSON array",
1614 path.display()
1615 ),
1616 ));
1617 }
1618 }
1619
1620 let mut emptied = Vec::new();
1621 for (event, value) in hooks_obj.iter_mut() {
1622 let Some(existing) = value.as_array_mut() else {
1623 continue;
1624 };
1625 let had_entries = !existing.is_empty();
1626 let slot = strip_tracevault_hooks(existing);
1627 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1628 match our_entries {
1629 Some(our_entries) => {
1630 let at = slot.unwrap_or(existing.len());
1631 existing.splice(at..at, our_entries.iter().cloned());
1632 }
1633 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1634 None => {}
1635 }
1636 }
1637 hooks_obj.retain(|event, _| !emptied.contains(event));
1639
1640 for (event, our_array) in ours_obj {
1641 if !hooks_obj.contains_key(event) {
1642 hooks_obj.insert(event.clone(), our_array.clone());
1643 }
1644 }
1645
1646 Ok(())
1647}
1648
1649pub(crate) fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
1653 let text = match fs::read_to_string(path) {
1654 Ok(text) => text,
1655 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
1656 Err(e) => return Err(e),
1657 };
1658 let settings: serde_json::Value =
1659 serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1660 Ok(settings
1661 .get("hooks")
1662 .and_then(|h| h.as_object())
1663 .into_iter()
1664 .flat_map(|events| events.values())
1665 .filter_map(|groups| groups.as_array())
1666 .flatten()
1667 .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
1668 .flatten()
1669 .any(is_tracevault_hook))
1670}
1671
1672pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
1676 merge_hooks_into_file(path, &tracevault_hooks())
1677}
1678
1679pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1685 fs::create_dir_all(claude_dir)?;
1686
1687 let base = claude_dir.canonicalize()?;
1690
1691 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1693
1694 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1696}
1697
1698pub fn write_global_user_config_in(
1708 config_root: &Path,
1709 requested: Option<UserContext>,
1710) -> io::Result<Option<PathBuf>> {
1711 fs::create_dir_all(config_root)?;
1712 let mut config = crate::config::try_load_user_config_in(config_root)
1714 .ok()
1715 .flatten()
1716 .unwrap_or_default();
1717 let user_context = requested
1719 .or_else(|| config.user_context.clone())
1720 .unwrap_or(UserContext::Toggle(true));
1721 let active = user_context
1722 .resolve()
1723 .map(|_| user_context.path_in(config_root));
1724 config.user_context = Some(user_context);
1725 fs::write(user_config_path_in(config_root), config.to_toml())?;
1726 if let Some(ref ctx_path) = active {
1727 if !ctx_path.exists() {
1728 Context::default().save_to(ctx_path)?;
1729 }
1730 }
1731 Ok(active)
1732}
1733
1734#[cfg(test)]
1735mod tests {
1736 use super::*;
1737 use std::io::{BufRead, BufReader, Write};
1738 use std::net::TcpListener;
1739 use std::thread;
1740
1741 #[test]
1747 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1748 let notice = codex_hook_trust_notice();
1749 assert!(
1750 notice.contains("hook trust"),
1751 "notice must name what is missing: {notice}"
1752 );
1753 assert!(
1754 notice.contains("codex") && notice.contains("approve"),
1755 "notice must tell the user to run codex and approve the prompt: {notice}"
1756 );
1757 assert!(
1758 notice.contains("--dangerously-bypass-hook-trust"),
1759 "notice must name the flag for unattended/CI runs: {notice}"
1760 );
1761 assert!(
1762 notice.contains("silently"),
1763 "notice must say the failure is silent, which is why it needs saying: {notice}"
1764 );
1765 }
1766
1767 fn spawn_once(response: String) -> String {
1770 let response: &'static str = Box::leak(response.into_boxed_str());
1771 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1772 let addr = listener.local_addr().unwrap();
1773 thread::spawn(move || {
1774 if let Ok((stream, _)) = listener.accept() {
1775 let mut reader = BufReader::new(stream);
1776 let mut request_line = String::new();
1777 let _ = reader.read_line(&mut request_line);
1778 let mut stream = reader.into_inner();
1779 let _ = stream.write_all(response.as_bytes());
1780 let _ = stream.flush();
1781 }
1782 });
1783 format!("http://{addr}")
1784 }
1785
1786 fn http_response(status: &str, body: &str) -> String {
1789 format!(
1790 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1791 status,
1792 body.len(),
1793 body
1794 )
1795 }
1796
1797 fn add_origin_remote(dir: &Path, url: &str) {
1798 let ok = std::process::Command::new("git")
1799 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1800 .status()
1801 .expect("git remote add failed")
1802 .success();
1803 assert!(ok, "git remote add must succeed");
1804 }
1805
1806 #[test]
1807 fn linked_worktree_primary_detects_linked_and_primary() {
1808 let tmp = tempfile::tempdir().unwrap();
1809 let repo = tmp.path().join("repo");
1810 let wt = tmp.path().join("linked-wt");
1811 std::fs::create_dir_all(&repo).unwrap();
1812 crate::test_helpers::init_git_repo(&repo);
1813 crate::test_helpers::add_worktree(&repo, &wt);
1814
1815 assert!(
1817 linked_worktree_primary(&repo).is_none(),
1818 "primary checkout must not be flagged as a linked worktree"
1819 );
1820 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1822 assert_eq!(
1823 primary.canonicalize().unwrap(),
1824 repo.canonicalize().unwrap(),
1825 "must resolve to the primary repo root"
1826 );
1827 }
1828
1829 #[test]
1830 fn linked_worktree_primary_none_for_non_git() {
1831 let tmp = tempfile::tempdir().unwrap();
1832 assert!(
1833 linked_worktree_primary(tmp.path()).is_none(),
1834 "a non-git directory is not a linked worktree"
1835 );
1836 }
1837
1838 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1840 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1841 }
1842
1843 #[test]
1844 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1845 let mut settings = serde_json::json!({});
1846 let ours = tracevault_hooks();
1847 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1848
1849 let hooks = settings.get("hooks").unwrap();
1850 for event in [
1851 "PreToolUse",
1852 "PostToolUse",
1853 "Notification",
1854 "Stop",
1855 "SessionEnd",
1856 "SubagentStop",
1857 "SessionStart",
1858 "UserPromptSubmit",
1859 ] {
1860 assert!(hooks.get(event).is_some(), "missing event {event}");
1861 }
1862 }
1863
1864 #[test]
1865 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1866 let mut settings = serde_json::json!({
1867 "model": "opus",
1868 "hooks": {
1869 "PreToolUse": [{
1870 "matcher": "",
1871 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1872 }]
1873 }
1874 });
1875 let ours = tracevault_hooks();
1876 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1877
1878 assert_eq!(settings.get("model").unwrap(), "opus");
1880
1881 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1882 assert_eq!(pre_tool_use.len(), 2);
1884 let commands: Vec<&str> = pre_tool_use
1885 .iter()
1886 .map(|e| entry_command(e).unwrap())
1887 .collect();
1888 assert!(commands.contains(&"my-own-hook"));
1889 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1890
1891 assert!(settings["hooks"]["SessionStart"].is_array());
1893 }
1894
1895 #[test]
1896 fn merge_hooks_is_idempotent() {
1897 let mut settings = serde_json::json!({});
1898 let ours = tracevault_hooks();
1899 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1900 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1901
1902 for event in [
1903 "PreToolUse",
1904 "PostToolUse",
1905 "Notification",
1906 "Stop",
1907 "SessionEnd",
1908 "SubagentStop",
1909 "SessionStart",
1910 "UserPromptSubmit",
1911 ] {
1912 let arr = settings["hooks"][event].as_array().unwrap();
1913 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1914 }
1915 }
1916
1917 #[test]
1918 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1919 let mut settings = serde_json::json!({
1923 "hooks": {
1924 "PreToolUse": [{
1925 "matcher": "Write|Edit|Bash",
1926 "hooks": [
1927 { "type": "command", "command": "other", "timeout": 3 },
1928 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1929 ]
1930 }]
1931 }
1932 });
1933 merge_hooks(
1934 &mut settings,
1935 &tracevault_hooks(),
1936 Path::new("settings.json"),
1937 )
1938 .unwrap();
1939
1940 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1941 assert_eq!(
1942 pre_tool_use[0],
1943 serde_json::json!({
1944 "matcher": "Write|Edit|Bash",
1945 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1946 })
1947 );
1948 assert_eq!(
1949 &pre_tool_use[1..],
1950 tracevault_hooks()["PreToolUse"].as_array().unwrap()
1951 );
1952 }
1953
1954 fn stale_tracevault_hooks() -> serde_json::Value {
1957 let entry = |matcher: &str, event: &str| {
1958 serde_json::json!([{
1959 "matcher": matcher,
1960 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1961 }])
1962 };
1963 serde_json::json!({
1964 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1965 "PostToolUse": entry("", "post-tool-use"),
1966 "Notification": entry("", "notification"),
1967 "Stop": entry("", "stop"),
1968 })
1969 }
1970
1971 #[test]
1972 fn merge_hooks_upgrades_stale_tracevault_entries() {
1973 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1974 merge_hooks(
1975 &mut settings,
1976 &tracevault_hooks(),
1977 Path::new("settings.json"),
1978 )
1979 .unwrap();
1980 assert_eq!(settings["hooks"], tracevault_hooks());
1981 }
1982
1983 #[test]
1984 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1985 let mut settings = serde_json::json!({
1988 "hooks": {
1989 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1990 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1991 "Custom": "left alone"
1992 }
1993 });
1994 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1995
1996 let hooks = settings["hooks"].as_object().unwrap();
1997 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
1998 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
1999 assert_eq!(hooks["Custom"], "left alone");
2000 for (event, entries) in codex_hooks().as_object().unwrap() {
2001 assert_eq!(&hooks[event], entries, "{event}");
2002 }
2003 }
2004
2005 #[test]
2006 fn merge_hooks_rerun_keeps_our_entry_in_place() {
2007 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
2010 settings["hooks"]["Stop"]
2011 .as_array_mut()
2012 .unwrap()
2013 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
2014 let before = settings.clone();
2015 merge_hooks(
2016 &mut settings,
2017 &tracevault_hooks(),
2018 Path::new("settings.json"),
2019 )
2020 .unwrap();
2021 assert_eq!(settings.to_string(), before.to_string());
2022 }
2023
2024 #[test]
2025 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
2026 let foreign = serde_json::json!({
2027 "matcher": "",
2028 "hooks": [
2029 { "type": "command", "command": "tracevault-wrapper stream" },
2030 { "type": "command", "command": "echo tracevault stream" },
2031 { "type": "command", "command": " tracevault check" }
2032 ]
2033 });
2034 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
2035 merge_hooks(
2036 &mut settings,
2037 &tracevault_hooks(),
2038 Path::new("settings.json"),
2039 )
2040 .unwrap();
2041 assert_eq!(settings["hooks"]["Stop"][0], foreign);
2042 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
2043 }
2044
2045 #[test]
2046 fn merge_hooks_errors_on_non_object_top_level() {
2047 let mut settings = serde_json::json!([1, 2, 3]);
2048 let ours = tracevault_hooks();
2049 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2050 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2051 assert!(err.to_string().contains("settings.json"));
2052 }
2053
2054 #[test]
2055 fn merge_hooks_errors_on_non_object_top_level_number() {
2056 let mut settings = serde_json::json!(42);
2057 let ours = tracevault_hooks();
2058 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2059 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2060 }
2061
2062 #[test]
2063 fn merge_hooks_errors_on_non_object_hooks() {
2064 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
2065 let ours = tracevault_hooks();
2066 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2067 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2068 assert!(err.to_string().contains("hooks"));
2069 }
2070
2071 #[test]
2072 fn merge_hooks_errors_on_non_array_event_value() {
2073 let mut settings = serde_json::json!({
2074 "hooks": {
2075 "PreToolUse": "not-an-array"
2076 }
2077 });
2078 let ours = tracevault_hooks();
2079 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2080 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2081 assert!(err.to_string().contains("PreToolUse"));
2082 }
2083
2084 #[test]
2085 fn install_global_hooks_writes_settings_and_claude_md() {
2086 let tmp = tempfile::tempdir().unwrap();
2087 let claude_dir = tmp.path().join(".claude");
2088
2089 install_global_hooks(&claude_dir).unwrap();
2090
2091 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2092 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2093 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
2094 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
2095 }
2096
2097 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2098 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2099 }
2100
2101 #[test]
2102 fn install_global_hooks_is_idempotent() {
2103 let tmp = tempfile::tempdir().unwrap();
2104 let claude_dir = tmp.path().join(".claude");
2105
2106 install_global_hooks(&claude_dir).unwrap();
2107 install_global_hooks(&claude_dir).unwrap();
2108
2109 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2110 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2111 for event in [
2112 "PreToolUse",
2113 "PostToolUse",
2114 "Notification",
2115 "Stop",
2116 "SessionEnd",
2117 "SubagentStop",
2118 "SessionStart",
2119 "UserPromptSubmit",
2120 ] {
2121 let arr = settings["hooks"][event].as_array().unwrap();
2122 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
2123 }
2124
2125 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2126 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
2127 assert_eq!(
2128 marker_count, 1,
2129 "CLAUDE.md marker should appear exactly once"
2130 );
2131 }
2132
2133 #[test]
2134 fn install_global_hooks_preserves_existing_claude_md_content() {
2135 let tmp = tempfile::tempdir().unwrap();
2136 let claude_dir = tmp.path().join(".claude");
2137 fs::create_dir_all(&claude_dir).unwrap();
2138 fs::write(
2139 claude_dir.join("CLAUDE.md"),
2140 "# My existing notes\nSome content.\n",
2141 )
2142 .unwrap();
2143
2144 install_global_hooks(&claude_dir).unwrap();
2145
2146 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2147 assert!(claude_md.contains("# My existing notes"));
2148 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2149 }
2150
2151 #[test]
2152 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
2153 let tmp = tempfile::tempdir().unwrap();
2154 let claude_dir = tmp.path().join(".claude");
2155
2156 install_global_hooks(&claude_dir).unwrap();
2157
2158 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2159 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2160 assert!(settings["hooks"].get("SessionStart").is_some());
2161
2162 let leftover = fs::read_dir(&claude_dir)
2163 .unwrap()
2164 .filter_map(|e| e.ok())
2165 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2166 assert!(
2167 !leftover,
2168 "no settings.json.tmp should remain after install"
2169 );
2170 }
2171
2172 #[test]
2173 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
2174 let tmp = tempfile::tempdir().unwrap();
2175 let claude_dir = tmp.path().join(".claude");
2176 fs::create_dir_all(&claude_dir).unwrap();
2177 let settings_path = claude_dir.join("settings.json");
2178 let original = "[1, 2, 3]";
2179 fs::write(&settings_path, original).unwrap();
2180
2181 let err = install_global_hooks(&claude_dir).unwrap_err();
2182 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2183
2184 let after = fs::read_to_string(&settings_path).unwrap();
2187 assert_eq!(after, original);
2188 let leftover = fs::read_dir(&claude_dir)
2189 .unwrap()
2190 .filter_map(|e| e.ok())
2191 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2192 assert!(!leftover, "no tmp file should be left behind on error");
2193 }
2194
2195 #[test]
2196 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
2197 let tmp = tempfile::tempdir().unwrap();
2198 let claude_dir = tmp.path().join(".claude");
2199 fs::create_dir_all(&claude_dir).unwrap();
2200 let settings_path = claude_dir.join("settings.json");
2201 let original = r#"{"hooks": "oops"}"#;
2202 fs::write(&settings_path, original).unwrap();
2203
2204 let err = install_global_hooks(&claude_dir).unwrap_err();
2205 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2206
2207 let after = fs::read_to_string(&settings_path).unwrap();
2208 assert_eq!(after, original);
2209 }
2210
2211 #[test]
2212 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
2213 let tmp = tempfile::tempdir().unwrap();
2214 let claude_dir = tmp.path().join(".claude");
2215 fs::create_dir_all(&claude_dir).unwrap();
2216 let settings_path = claude_dir.join("settings.json");
2217 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
2218 fs::write(&settings_path, original).unwrap();
2219
2220 let err = install_global_hooks(&claude_dir).unwrap_err();
2221 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2222
2223 let after = fs::read_to_string(&settings_path).unwrap();
2224 assert_eq!(after, original);
2225 }
2226
2227 #[test]
2228 fn safe_join_allows_direct_child_file() {
2229 let tmp = tempfile::tempdir().unwrap();
2230 let base = tmp.path();
2231 let result = safe_join(base, "settings.json").unwrap();
2232 assert_eq!(result.parent(), Some(base));
2233 assert_eq!(result.file_name().unwrap(), "settings.json");
2234 }
2235
2236 #[test]
2237 fn safe_join_rejects_path_traversal() {
2238 let tmp = tempfile::tempdir().unwrap();
2239 let base = tmp.path();
2240 let result = safe_join(base, "../evil");
2241 assert!(result.is_err());
2242 let err = result.unwrap_err();
2243 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2244 assert!(err.to_string().contains("refusing to access path outside"));
2245 }
2246
2247 #[test]
2248 fn safe_join_rejects_absolute_path() {
2249 let tmp = tempfile::tempdir().unwrap();
2250 let base = tmp.path();
2251 let result = safe_join(base, "/etc/passwd");
2252 assert!(result.is_err());
2255 }
2256
2257 #[test]
2258 fn write_global_user_config_enables_and_creates_context() {
2259 let root = tempfile::tempdir().unwrap();
2260 let active = write_global_user_config_in(root.path(), None).unwrap();
2261 let cfg = crate::config::try_load_user_config_in(root.path())
2262 .unwrap()
2263 .unwrap();
2264 assert_eq!(
2267 cfg.user_context.unwrap().resolve_in(root.path()),
2268 Some(crate::config::default_user_context_path_in(root.path()))
2269 );
2270 let ctx = crate::config::default_user_context_path_in(root.path());
2271 assert_eq!(active, Some(ctx.clone()));
2272 assert!(ctx.exists());
2273 }
2274
2275 #[test]
2276 fn write_global_user_config_can_disable() {
2277 let root = tempfile::tempdir().unwrap();
2278 let active = write_global_user_config_in(
2279 root.path(),
2280 Some(crate::config::UserContext::Toggle(false)),
2281 )
2282 .unwrap();
2283 let cfg = crate::config::try_load_user_config_in(root.path())
2284 .unwrap()
2285 .unwrap();
2286 assert!(matches!(
2287 cfg.user_context,
2288 Some(crate::config::UserContext::Toggle(false))
2289 ));
2290 assert_eq!(active, None, "disabled → no active context path");
2291 assert!(
2293 !crate::config::default_user_context_path_in(root.path()).exists(),
2294 "disabled user context must not create a context.json"
2295 );
2296 }
2297
2298 #[test]
2299 fn write_global_user_config_custom_path_seeds_that_file_only() {
2300 let root = tempfile::tempdir().unwrap();
2301 let custom = root.path().join("custom-ctx.json");
2302 let active = write_global_user_config_in(
2303 root.path(),
2304 Some(crate::config::UserContext::Path(
2305 custom.to_string_lossy().into_owned(),
2306 )),
2307 )
2308 .unwrap();
2309 assert_eq!(active, Some(custom.clone()));
2310 assert!(custom.exists(), "the configured custom path must be seeded");
2311 assert!(
2312 !crate::config::default_user_context_path_in(root.path()).exists(),
2313 "the default context.json must NOT be created when a custom path is configured"
2314 );
2315 }
2316
2317 #[test]
2318 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
2319 let root = tempfile::tempdir().unwrap();
2320 let custom = root.path().join("custom-ctx.json");
2321 write_global_user_config_in(
2323 root.path(),
2324 Some(crate::config::UserContext::Path(
2325 custom.to_string_lossy().into_owned(),
2326 )),
2327 )
2328 .unwrap();
2329 let active = write_global_user_config_in(root.path(), None).unwrap();
2331 assert_eq!(
2332 active,
2333 Some(custom.clone()),
2334 "re-run without flags must preserve the custom path"
2335 );
2336 let cfg = crate::config::try_load_user_config_in(root.path())
2337 .unwrap()
2338 .unwrap();
2339 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
2340 }
2341
2342 #[test]
2343 fn install_global_codex_hooks_writes_and_is_idempotent() {
2344 let tmp = tempfile::tempdir().unwrap();
2345 let codex_dir = tmp.path().join(".codex");
2346
2347 install_global_codex_hooks(&codex_dir).unwrap();
2348 install_global_codex_hooks(&codex_dir).unwrap();
2349
2350 let v: serde_json::Value =
2351 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2352 .unwrap();
2353 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2354 let arr = v["hooks"][event].as_array().unwrap();
2355 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
2356 }
2357 assert!(v["hooks"].get("PreToolUse").is_none());
2358 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
2360 assert_eq!(
2361 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
2362 1,
2363 "AGENTS.md workspace-mode block must appear exactly once"
2364 );
2365 let leftover = fs::read_dir(&codex_dir)
2367 .unwrap()
2368 .filter_map(|e| e.ok())
2369 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2370 assert!(!leftover);
2371 }
2372
2373 #[test]
2374 fn codex_hooks_has_expected_events_and_commands() {
2375 let h = codex_hooks();
2376 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2377 assert!(h.get(event).is_some(), "missing codex event {event}");
2378 }
2379 assert!(h.get("PreToolUse").is_none());
2383 assert!(h.get("Notification").is_none());
2384 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2386 assert_eq!(
2387 cmd("PostToolUse"),
2388 "tracevault stream --event post-tool-use --agent codex"
2389 );
2390 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2391 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2392 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2393 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2395 }
2396
2397 #[test]
2398 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2399 let tmp = tempfile::tempdir().unwrap();
2400 install_codex_hooks(tmp.path()).unwrap();
2401 install_codex_hooks(tmp.path()).unwrap();
2402
2403 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2404 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2405 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2406 let arr = v["hooks"][event].as_array().unwrap();
2407 assert_eq!(
2408 arr.len(),
2409 1,
2410 "event {event} must not be duplicated on re-run"
2411 );
2412 }
2413 assert!(v["hooks"].get("PreToolUse").is_none());
2414 }
2415
2416 #[test]
2417 fn install_codex_hooks_preserves_existing_user_hook() {
2418 let tmp = tempfile::tempdir().unwrap();
2419 let codex_dir = tmp.path().join(".codex");
2420 fs::create_dir_all(&codex_dir).unwrap();
2421 fs::write(
2424 codex_dir.join("hooks.json"),
2425 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2426 )
2427 .unwrap();
2428
2429 install_codex_hooks(tmp.path()).unwrap();
2430
2431 let v: serde_json::Value =
2432 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2433 .unwrap();
2434 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2436 .as_array()
2437 .unwrap()
2438 .iter()
2439 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2440 .collect();
2441 assert!(
2442 post_cmds.contains(&"my-own"),
2443 "user PostToolUse hook preserved"
2444 );
2445 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2446 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2448 .as_array()
2449 .unwrap()
2450 .iter()
2451 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2452 .collect();
2453 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2454 }
2455
2456 const FOREIGN_SETTINGS: &str = r#"{
2460 "permissions": { "allow": ["Bash(ls)"] },
2461 "hooks": {
2462 "PreToolUse": [
2463 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2464 { "matcher": "Write|Edit", "hooks": [
2465 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2466 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2467 ] }
2468 ],
2469 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2470 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2471 },
2472 "model": "opus"
2473}"#;
2474
2475 fn expected_foreign_entries() -> Vec<String> {
2479 [
2480 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2481 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2482 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2483 ]
2484 .map(String::from)
2485 .to_vec()
2486 }
2487
2488 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2489 entry["hooks"]
2490 .as_array()
2491 .unwrap()
2492 .iter()
2493 .any(is_tracevault_hook)
2494 }
2495
2496 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2497 let v: serde_json::Value =
2498 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2499 assert_eq!(
2500 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2501 ["permissions", "hooks", "model"],
2502 "top-level keys kept, in their order"
2503 );
2504 assert_eq!(
2505 v["permissions"],
2506 serde_json::json!({ "allow": ["Bash(ls)"] })
2507 );
2508 let hooks = v["hooks"].as_object().unwrap();
2509 let foreign: Vec<String> = hooks
2510 .values()
2511 .flat_map(|entries| entries.as_array().unwrap())
2512 .filter(|e| !holds_tracevault_hook(e))
2513 .map(|e| e.to_string())
2514 .collect();
2515 assert_eq!(foreign, expected_foreign_entries());
2516 let ours = ours.as_object().unwrap();
2517 for (event, entries) in hooks {
2518 let mine: Vec<&serde_json::Value> = entries
2519 .as_array()
2520 .unwrap()
2521 .iter()
2522 .filter(|e| holds_tracevault_hook(e))
2523 .collect();
2524 let want: Vec<&serde_json::Value> = ours
2525 .get(event)
2526 .map(|o| o.as_array().unwrap().iter().collect())
2527 .unwrap_or_default();
2528 assert_eq!(mine, want, "TraceVault entries under {event}");
2529 }
2530 for event in ours.keys() {
2531 assert!(hooks.contains_key(event), "missing {event}");
2532 }
2533 }
2534
2535 #[test]
2536 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2537 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2538 let tmp = tempfile::tempdir().unwrap();
2539 let path = tmp.path().join(".claude").join(target.filename());
2540 fs::create_dir_all(path.parent().unwrap()).unwrap();
2541 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2542
2543 install_claude_hooks(tmp.path(), target).unwrap();
2544 assert_installed_over_foreign(&path, &tracevault_hooks());
2545
2546 let after_first = fs::read(&path).unwrap();
2548 install_claude_hooks(tmp.path(), target).unwrap();
2549 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2550 }
2551 }
2552
2553 #[test]
2554 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2555 let tmp = tempfile::tempdir().unwrap();
2556 let claude_dir = tmp.path().join(".claude");
2557 fs::create_dir_all(&claude_dir).unwrap();
2558 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2559
2560 install_global_hooks(&claude_dir).unwrap();
2561 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2562 }
2563
2564 #[test]
2565 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2566 for global in [false, true] {
2567 let tmp = tempfile::tempdir().unwrap();
2568 let codex_dir = tmp.path().join(".codex");
2569 fs::create_dir_all(&codex_dir).unwrap();
2570 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2571
2572 if global {
2573 install_global_codex_hooks(&codex_dir).unwrap();
2574 } else {
2575 install_codex_hooks(tmp.path()).unwrap();
2576 }
2577 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2578 }
2579 }
2580
2581 #[test]
2582 fn up_to_date_hook_file_is_not_rewritten() {
2583 let tmp = tempfile::tempdir().unwrap();
2585 let path = tmp.path().join(".claude/settings.json");
2586 fs::create_dir_all(path.parent().unwrap()).unwrap();
2587 let mut body = Vec::new();
2588 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
2589 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2590 serde::Serialize::serialize(
2591 &serde_json::json!({ "hooks": tracevault_hooks() }),
2592 &mut ser,
2593 )
2594 .unwrap();
2595 fs::write(&path, &body).unwrap();
2596
2597 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2598 assert_eq!(fs::read(&path).unwrap(), body);
2599 }
2600
2601 #[test]
2602 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2603 for (target, body) in [
2604 (ClaudeSettingsTarget::Shared, "{ not json"),
2605 (ClaudeSettingsTarget::Local, "[1, 2]"),
2606 (ClaudeSettingsTarget::Shared, "null"),
2607 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2608 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2609 ] {
2610 let tmp = tempfile::tempdir().unwrap();
2611 let path = tmp.path().join(".claude").join(target.filename());
2612 fs::create_dir_all(path.parent().unwrap()).unwrap();
2613 fs::write(&path, body).unwrap();
2614
2615 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2616 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2617 assert_eq!(
2618 fs::read_to_string(&path).unwrap(),
2619 body,
2620 "file must be untouched"
2621 );
2622 assert_eq!(
2623 fs::read_dir(path.parent().unwrap()).unwrap().count(),
2624 1,
2625 "no temp file left behind"
2626 );
2627 }
2628 }
2629
2630 #[test]
2631 fn concurrent_installs_never_publish_a_partial_file() {
2632 let tmp = tempfile::tempdir().unwrap();
2638 let path = tmp.path().join("settings.json");
2639 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2640 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2641 let reader = {
2642 let (path, done) = (path.clone(), done.clone());
2643 std::thread::spawn(move || {
2644 while !done.load(std::sync::atomic::Ordering::Relaxed) {
2645 let body = fs::read_to_string(&path).unwrap();
2646 serde_json::from_str::<serde_json::Value>(&body).unwrap();
2647 }
2648 })
2649 };
2650 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2651 .into_iter()
2652 .map(|ours| {
2653 let path = path.clone();
2654 std::thread::spawn(move || {
2655 for _ in 0..200 {
2656 if let Err(e) = merge_hooks_into_file(&path, &ours) {
2657 assert!(e.to_string().contains("kept changing"), "{e}");
2658 }
2659 }
2660 })
2661 })
2662 .collect();
2663 for writer in writers {
2664 writer.join().unwrap();
2665 }
2666 done.store(true, std::sync::atomic::Ordering::Relaxed);
2667 reader.join().unwrap();
2668 let v: serde_json::Value =
2669 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2670 assert_eq!(v["model"], "opus");
2671 assert_eq!(
2672 fs::read_dir(tmp.path()).unwrap().count(),
2673 1,
2674 "no temp file left"
2675 );
2676 }
2677
2678 #[cfg(unix)]
2679 #[test]
2680 fn install_claude_hooks_keeps_file_permissions() {
2681 use std::os::unix::fs::PermissionsExt;
2682 let tmp = tempfile::tempdir().unwrap();
2683 let path = tmp.path().join(".claude/settings.local.json");
2684 fs::create_dir_all(path.parent().unwrap()).unwrap();
2685 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2686 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2687
2688 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2689
2690 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2691 assert_eq!(mode, 0o600);
2692 assert_installed_over_foreign(&path, &tracevault_hooks());
2693 }
2694
2695 #[cfg(unix)]
2696 #[test]
2697 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2698 let tmp = tempfile::tempdir().unwrap();
2699 let central = tmp.path().join("central/claude-settings.json");
2700 fs::create_dir_all(central.parent().unwrap()).unwrap();
2701 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
2702 let link = tmp.path().join("repo/.claude/settings.json");
2703 fs::create_dir_all(link.parent().unwrap()).unwrap();
2704 std::os::unix::fs::symlink(¢ral, &link).unwrap();
2705
2706 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2707
2708 assert!(fs::symlink_metadata(&link)
2709 .unwrap()
2710 .file_type()
2711 .is_symlink());
2712 assert_installed_over_foreign(¢ral, &tracevault_hooks());
2713 }
2714
2715 #[cfg(unix)]
2716 #[test]
2717 fn install_claude_hooks_refuses_dangling_symlink() {
2718 let tmp = tempfile::tempdir().unwrap();
2719 let link = tmp.path().join(".claude/settings.json");
2720 fs::create_dir_all(link.parent().unwrap()).unwrap();
2721 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2722
2723 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2724 assert!(fs::symlink_metadata(&link)
2725 .unwrap()
2726 .file_type()
2727 .is_symlink());
2728 assert!(!tmp.path().join("gone.json").exists());
2729 }
2730
2731 #[test]
2732 fn validate_init_flags_rejects_claude_settings_with_codex() {
2733 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2734 }
2735
2736 #[test]
2737 fn validate_init_flags_allows_codex_without_claude_settings() {
2738 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2739 }
2740
2741 #[test]
2742 fn validate_init_flags_allows_claude_with_claude_settings() {
2743 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2744 }
2745
2746 #[test]
2747 fn merge_hooks_into_file_rejects_parent_dir() {
2748 let tmp = tempfile::tempdir().unwrap();
2749 let bad = tmp.path().join("..").join("hooks.json");
2750 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2751 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2752 }
2753
2754 #[test]
2755 fn append_workspace_md_rejects_parent_dir() {
2756 let tmp = tempfile::tempdir().unwrap();
2757 let bad = tmp.path().join("..").join("AGENTS.md");
2758 let err = append_workspace_md(&bad).unwrap_err();
2759 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2760 }
2761
2762 #[tokio::test]
2763 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2764 let tmp = tempfile::tempdir().unwrap();
2765 let root = tmp.path();
2766 crate::test_helpers::init_git_repo(root);
2767 fs::create_dir_all(root.join(".tracevault")).unwrap();
2770 fs::write(
2771 root.join(".tracevault/config.toml"),
2772 "api_key = \"tvk_test\"\n",
2773 )
2774 .unwrap();
2775
2776 let entry = init_in_directory(
2777 root,
2778 None,
2779 None,
2780 false,
2781 Some(crate::config::UserContext::Toggle(false)),
2782 crate::agent::Agent::Codex,
2783 )
2784 .await
2785 .unwrap();
2786
2787 assert!(root.join(".codex").join("hooks.json").exists());
2789 assert!(!root.join(".claude").join("settings.json").exists());
2790 assert_eq!(entry, ".codex/hooks.json");
2791
2792 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2794 assert!(gi.contains(".codex/hooks.json"));
2795 assert!(gi.contains(".tracevault/"));
2796 }
2797
2798 #[tokio::test]
2810 async fn init_in_directory_registers_repo_and_persists_repo_id() {
2811 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2812 let tmp = tempfile::tempdir().unwrap();
2813 let root = tmp.path();
2814 crate::test_helpers::init_git_repo(root);
2815 add_origin_remote(root, "git@github.com:org/repo.git");
2816
2817 let repo_id = "11111111-1111-4111-8111-111111111111";
2818 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2819 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2822 http_response("404 Not Found", NO_REMOTE),
2823 http_response("200 OK", &body),
2824 ]);
2825
2826 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2827 _guard.set("XDG_CONFIG_HOME", tmp.path());
2828 _guard.set("TRACEVAULT_API_KEY", "tok");
2829 _guard.remove("TRACEVAULT_SERVER_URL");
2830
2831 init_in_directory(
2832 root,
2833 Some(&base),
2834 None,
2835 true,
2836 Some(crate::config::UserContext::Toggle(false)),
2837 crate::agent::Agent::Codex,
2838 )
2839 .await
2840 .unwrap();
2841
2842 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2843 assert_eq!(
2844 cfg.repo_id,
2845 Some(repo_id.to_string()),
2846 "successful registration must persist repo_id to config.toml"
2847 );
2848 }
2849
2850 #[tokio::test]
2856 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2857 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2858 let tmp = tempfile::tempdir().unwrap();
2859 let root = tmp.path();
2860 crate::test_helpers::init_git_repo(root);
2861 add_origin_remote(root, "git@github.com:org/repo.git");
2862
2863 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2864 http_response("404 Not Found", NO_REMOTE),
2865 http_response("403 Forbidden", ""),
2866 ]);
2867
2868 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2869 _guard.set("XDG_CONFIG_HOME", tmp.path());
2870 _guard.set("TRACEVAULT_API_KEY", "tok");
2871 _guard.remove("TRACEVAULT_SERVER_URL");
2872
2873 let entry = init_in_directory(
2874 root,
2875 Some(&base),
2876 None,
2877 true,
2878 Some(crate::config::UserContext::Toggle(false)),
2879 crate::agent::Agent::Codex,
2880 )
2881 .await
2882 .expect("a registration failure (403) must not abort init itself");
2883 assert_eq!(entry, ".codex/hooks.json");
2884
2885 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2886 assert!(
2887 cfg.repo_id.is_none(),
2888 "a 403 registration failure must not persist a repo_id"
2889 );
2890 }
2891
2892 #[tokio::test]
2897 async fn registration_failure_message_flags_403_as_not_authorized() {
2898 let base = spawn_once(http_response("403 Forbidden", ""));
2899 let client = ApiClient::new(&base, Some("tok"));
2900 let err = client
2901 .register_repo(crate::api_client::RegisterRepoRequest {
2902 repo_name: "repo".into(),
2903 github_url: Some("git@github.com:org/repo.git".into()),
2904 })
2905 .await
2906 .unwrap_err();
2907 let msg = registration_failure_message(err.as_ref());
2908 assert!(
2909 msg.contains("not authorized"),
2910 "403 registration failure must surface a not-authorized message; got: {msg}"
2911 );
2912 }
2913
2914 #[tokio::test]
2917 async fn registration_failure_message_generic_for_non_403() {
2918 let base = spawn_once(http_response("500 Internal Server Error", ""));
2919 let client = ApiClient::new(&base, Some("tok"));
2920 let err = client
2921 .register_repo(crate::api_client::RegisterRepoRequest {
2922 repo_name: "repo".into(),
2923 github_url: Some("git@github.com:org/repo.git".into()),
2924 })
2925 .await
2926 .unwrap_err();
2927 let msg = registration_failure_message(err.as_ref());
2928 assert!(
2929 msg.contains("could not register repo on server"),
2930 "got: {msg}"
2931 );
2932 assert!(!msg.contains("not authorized"), "got: {msg}");
2933 }
2934
2935 #[tokio::test]
2940 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2941 let base = spawn_once(http_response(
2942 "500 Internal Server Error",
2943 "upstream error 403 from proxy",
2944 ));
2945 let client = ApiClient::new(&base, Some("tok"));
2946 let err = client
2947 .register_repo(crate::api_client::RegisterRepoRequest {
2948 repo_name: "repo".into(),
2949 github_url: Some("git@github.com:org/repo.git".into()),
2950 })
2951 .await
2952 .unwrap_err();
2953 let msg = registration_failure_message(err.as_ref());
2954 assert!(
2955 !msg.contains("not authorized"),
2956 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2957 );
2958 assert!(
2959 msg.contains("could not register repo on server"),
2960 "got: {msg}"
2961 );
2962 }
2963
2964 #[tokio::test]
2968 async fn registration_failure_message_flags_404_as_version_mismatch() {
2969 let base = spawn_once(http_response("404 Not Found", ""));
2970 let client = ApiClient::new(&base, Some("tok"));
2971 let err = client
2972 .register_repo(crate::api_client::RegisterRepoRequest {
2973 repo_name: "repo".into(),
2974 github_url: Some("git@github.com:org/repo.git".into()),
2975 })
2976 .await
2977 .unwrap_err();
2978 let msg = registration_failure_message(err.as_ref());
2979 assert!(
2980 msg.to_lowercase().contains("version mismatch"),
2981 "a 404 registration failure should hint at a version mismatch; got: {msg}"
2982 );
2983 }
2984
2985 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
2989 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
2990 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
2991 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
2992
2993 fn resolve_remote_ok() -> String {
2994 http_response(
2995 "200 OK",
2996 &format!(
2997 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
2998 ),
2999 )
3000 }
3001
3002 fn remote_detail(repos: &[(&str, &str)]) -> String {
3003 let repos: Vec<String> = repos
3004 .iter()
3005 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
3006 .collect();
3007 http_response(
3008 "200 OK",
3009 &format!(
3010 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
3011 repos.join(",")
3012 ),
3013 )
3014 }
3015
3016 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
3019 let (base, rx) = crate::test_helpers::spawn_seq(responses);
3020 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3021 _guard.set("XDG_CONFIG_HOME", root);
3022 _guard.set("TRACEVAULT_API_KEY", "tok");
3023 _guard.remove("TRACEVAULT_SERVER_URL");
3024
3025 init_in_directory(
3026 root,
3027 Some(&base),
3028 None,
3029 true,
3030 Some(crate::config::UserContext::Toggle(false)),
3031 crate::agent::Agent::Codex,
3032 )
3033 .await
3034 .expect("init succeeds");
3035
3036 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
3037 (cfg.repo_id, rx.try_iter().collect())
3038 }
3039
3040 fn registered(requests: &[String]) -> bool {
3041 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
3042 }
3043
3044 #[tokio::test]
3047 async fn init_binds_the_existing_repo_of_a_known_remote() {
3048 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3049 let tmp = tempfile::tempdir().unwrap();
3050 crate::test_helpers::init_git_repo(tmp.path());
3051 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3052
3053 let (repo_id, requests) = init_against(
3054 tmp.path(),
3055 vec![
3056 resolve_remote_ok(),
3057 remote_detail(&[(CANONICAL, "tracevault")]),
3058 ],
3059 )
3060 .await;
3061
3062 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3063 assert!(!registered(&requests), "requests: {requests:?}");
3064 }
3065
3066 #[tokio::test]
3069 async fn init_binds_the_record_named_like_the_checkout() {
3070 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3071 let tmp = tempfile::tempdir().unwrap();
3072 crate::test_helpers::init_git_repo(tmp.path());
3073 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3074 let dir_name = crate::resolution::git_repo_name(tmp.path());
3075
3076 let (repo_id, requests) = init_against(
3077 tmp.path(),
3078 vec![
3079 resolve_remote_ok(),
3080 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
3081 ],
3082 )
3083 .await;
3084
3085 assert_eq!(repo_id.as_deref(), Some(STRAY));
3086 assert!(!registered(&requests));
3087 }
3088
3089 #[tokio::test]
3091 async fn init_rerun_keeps_the_previously_bound_repo() {
3092 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3093 let tmp = tempfile::tempdir().unwrap();
3094 crate::test_helpers::init_git_repo(tmp.path());
3095 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3096 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3097 fs::write(
3098 tmp.path().join(".tracevault/config.toml"),
3099 format!("repo_id = \"{STRAY}\"\n"),
3100 )
3101 .unwrap();
3102
3103 let (repo_id, requests) = init_against(
3104 tmp.path(),
3105 vec![
3106 resolve_remote_ok(),
3107 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3108 ],
3109 )
3110 .await;
3111
3112 assert_eq!(repo_id.as_deref(), Some(STRAY));
3113 assert!(!registered(&requests));
3114 }
3115
3116 #[tokio::test]
3119 async fn init_binding_keeps_the_rest_of_the_config() {
3120 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3121 let tmp = tempfile::tempdir().unwrap();
3122 crate::test_helpers::init_git_repo(tmp.path());
3123 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3124 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3125 fs::write(
3126 tmp.path().join(".tracevault/config.toml"),
3127 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
3128 )
3129 .unwrap();
3130
3131 let (repo_id, requests) = init_against(
3132 tmp.path(),
3133 vec![
3134 http_response(
3136 "200 OK",
3137 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3138 ),
3139 resolve_remote_ok(),
3140 remote_detail(&[(CANONICAL, "tracevault")]),
3141 ],
3142 )
3143 .await;
3144
3145 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3146 assert!(
3147 requests[0].starts_with("GET /api/v1/projects"),
3148 "{requests:?}"
3149 );
3150 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
3151 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
3152 assert_eq!(cfg.default_project, None);
3153 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3154 assert_eq!(cfg.project_name.as_deref(), Some("payments"));
3155 }
3156
3157 const PROJECT: &str = "00000000-0000-4000-8000-0000000000aa";
3158
3159 #[tokio::test]
3162 async fn init_unknown_default_project_errors_and_writes_nothing() {
3163 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3164 let tmp = tempfile::tempdir().unwrap();
3165 crate::test_helpers::init_git_repo(tmp.path());
3166 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3167 let content = "default_project = \"typo\"\n";
3168 fs::write(tmp.path().join(".tracevault/config.toml"), content).unwrap();
3169 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3170 "200 OK",
3171 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3172 )]);
3173 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3174 _guard.set("XDG_CONFIG_HOME", tmp.path());
3175 _guard.set("TRACEVAULT_API_KEY", "tok");
3176 _guard.remove("TRACEVAULT_SERVER_URL");
3177
3178 let err = init_in_directory(
3179 tmp.path(),
3180 Some(&base),
3181 None,
3182 true,
3183 None,
3184 crate::agent::Agent::Codex,
3185 )
3186 .await
3187 .unwrap_err();
3188
3189 assert!(err.to_string().contains("'typo'"), "{err}");
3190 assert_eq!(
3191 fs::read_to_string(tmp.path().join(".tracevault/config.toml")).unwrap(),
3192 content
3193 );
3194 assert!(!tmp.path().join(".codex/hooks.json").exists());
3195 }
3196
3197 #[tokio::test]
3201 async fn init_workspace_binds_a_non_git_dir_to_a_project() {
3202 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3203 let tmp = tempfile::tempdir().unwrap();
3204 let dir = tmp.path().join("umbrella");
3205 fs::create_dir_all(&dir).unwrap();
3206 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response(
3207 "200 OK",
3208 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3209 )]);
3210 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3211 _guard.set("XDG_CONFIG_HOME", tmp.path());
3212 _guard.set("TRACEVAULT_API_KEY", "tok");
3213 _guard.remove("TRACEVAULT_SERVER_URL");
3214
3215 let bound = init_workspace(&dir, "visdom", Some(&base)).await.unwrap();
3216
3217 assert_eq!(bound.project_id.to_string(), PROJECT);
3218 assert_eq!(bound.project_name, "visdom");
3219 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3220 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3221 assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
3222 assert_eq!(cfg.repo_id, None);
3223 assert_eq!(cfg.server_url.as_deref(), Some(base.as_str()));
3224 assert!(dir.join(".tracevault/.gitignore").exists());
3225 let requests: Vec<String> = rx.try_iter().collect();
3226 assert_eq!(requests.len(), 1, "{requests:?}");
3227 let sub = dir.join("notes");
3229 fs::create_dir_all(&sub).unwrap();
3230 assert_eq!(
3231 crate::paths::resolve_project_root(&sub)
3232 .root
3233 .canonicalize()
3234 .unwrap(),
3235 dir.canonicalize().unwrap()
3236 );
3237 }
3238
3239 #[tokio::test]
3242 async fn init_workspace_rebinds_and_keeps_other_keys() {
3243 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3244 let tmp = tempfile::tempdir().unwrap();
3245 let dir = tmp.path();
3246 fs::create_dir_all(dir.join(".tracevault")).unwrap();
3247 fs::write(
3248 dir.join(".tracevault/config.toml"),
3249 "default_project = \"old\"\nproject_id = \"00000000-0000-4000-8000-000000000001\"\nuser_context = false\n",
3250 )
3251 .unwrap();
3252 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3253 "200 OK",
3254 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3255 )]);
3256 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3257 _guard.set("XDG_CONFIG_HOME", dir);
3258 _guard.set("TRACEVAULT_API_KEY", "tok");
3259 _guard.remove("TRACEVAULT_SERVER_URL");
3260
3261 init_workspace(dir, "visdom", Some(&base)).await.unwrap();
3262
3263 let cfg = crate::config::TracevaultConfig::load(dir).unwrap();
3264 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3265 assert_eq!(cfg.default_project, None);
3266 assert!(matches!(
3267 cfg.user_context,
3268 Some(crate::config::UserContext::Toggle(false))
3269 ));
3270 }
3271
3272 #[test]
3276 fn append_workspace_md_upgrades_an_older_block_in_place() {
3277 let tmp = tempfile::tempdir().unwrap();
3278 let md = tmp.path().join("CLAUDE.md");
3279 for old in PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS {
3280 fs::write(
3282 &md,
3283 format!("# Mine\nkeep me\n\n{old}## After\nalso keep\n"),
3284 )
3285 .unwrap();
3286
3287 append_workspace_md(&md).unwrap();
3288 let got = fs::read_to_string(&md).unwrap();
3289 assert_eq!(
3290 got,
3291 format!("# Mine\nkeep me\n\n{GLOBAL_CLAUDE_MD_BLOCK}## After\nalso keep\n")
3292 );
3293 append_workspace_md(&md).unwrap();
3294 assert_eq!(fs::read_to_string(&md).unwrap(), got);
3295 }
3296
3297 let edited = "x\n\n<!-- tracevault:workspace-mode -->\n## T\nmy own words\n";
3299 fs::write(&md, edited).unwrap();
3300 append_workspace_md(&md).unwrap();
3301 assert_eq!(fs::read_to_string(&md).unwrap(), edited);
3302 }
3303
3304 #[tokio::test]
3307 async fn init_workspace_refuses_a_server_url_the_credential_is_not_for() {
3308 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3309 let tmp = tempfile::tempdir().unwrap();
3310 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response("200 OK", "[]")]);
3311 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3312 fs::write(
3313 tmp.path().join(".tracevault/config.toml"),
3314 "server_url = \"http://other.example.invalid\"\napi_key = \"tvk_x\"\n",
3315 )
3316 .unwrap();
3317 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3318 _guard.set("XDG_CONFIG_HOME", tmp.path());
3319 _guard.remove("TRACEVAULT_API_KEY");
3320 _guard.remove("TRACEVAULT_SERVER_URL");
3321
3322 let err = init_workspace(tmp.path(), "visdom", Some(&base))
3323 .await
3324 .unwrap_err();
3325 assert!(err.to_string().contains("not --server-url"), "{err}");
3326 assert_eq!(rx.try_iter().count(), 0, "no request may be sent");
3327 }
3328
3329 #[tokio::test]
3330 async fn credential_url_mismatch_only_for_a_different_explicit_server() {
3331 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3332 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3333 _guard.remove("TRACEVAULT_API_KEY");
3334 assert!(credential_url_mismatch(Some("https://a/"), Some("https://a")).is_none());
3335 assert!(credential_url_mismatch(None, Some("https://b")).is_none());
3336 assert!(credential_url_mismatch(Some("https://a"), None).is_none());
3337 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_some());
3338 _guard.set("TRACEVAULT_API_KEY", "tvk_for_b");
3340 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_none());
3341 }
3342
3343 #[tokio::test]
3346 async fn migrate_cwd_config_migrates_the_dirs_config() {
3347 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3348 let tmp = tempfile::tempdir().unwrap();
3349 let dir = tmp.path().join("umbrella");
3350 fs::create_dir_all(dir.join(".tracevault")).unwrap();
3351 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3352 "200 OK",
3353 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3354 )]);
3355 fs::write(
3356 dir.join(".tracevault/config.toml"),
3357 format!("server_url = \"{base}\"\napi_key = \"tvk_x\"\ndefault_project = \"visdom\"\n"),
3358 )
3359 .unwrap();
3360 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3361 _guard.set("XDG_CONFIG_HOME", tmp.path());
3362 _guard.remove("TRACEVAULT_API_KEY");
3363 _guard.remove("TRACEVAULT_SERVER_URL");
3364
3365 migrate_cwd_config(&dir).await.unwrap();
3366
3367 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3368 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3369 assert_eq!(cfg.default_project, None);
3370 }
3371
3372 #[tokio::test]
3374 async fn init_workspace_unknown_or_ambiguous_name_writes_nothing() {
3375 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3376 for name in ["nope", "dup"] {
3377 let tmp = tempfile::tempdir().unwrap();
3378 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3379 "200 OK",
3380 r#"[{"id":"00000000-0000-4000-8000-000000000001","name":"dup"},{"id":"00000000-0000-4000-8000-000000000002","name":"dup"}]"#,
3381 )]);
3382 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3383 _guard.set("XDG_CONFIG_HOME", tmp.path());
3384 _guard.set("TRACEVAULT_API_KEY", "tok");
3385 _guard.remove("TRACEVAULT_SERVER_URL");
3386
3387 let err = init_workspace(tmp.path(), name, Some(&base))
3388 .await
3389 .unwrap_err();
3390 assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
3391 assert!(!tmp.path().join(".tracevault").exists(), "{name}");
3392 }
3393 }
3394
3395 #[tokio::test]
3398 async fn init_workspace_refuses_a_git_subdirectory() {
3399 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3400 let tmp = tempfile::tempdir().unwrap();
3401 crate::test_helpers::init_git_repo(tmp.path());
3402 let sub = tmp.path().join("pkg");
3403 fs::create_dir_all(&sub).unwrap();
3404 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3405 _guard.set("XDG_CONFIG_HOME", tmp.path());
3406 _guard.set("TRACEVAULT_API_KEY", "tok");
3407 _guard.remove("TRACEVAULT_SERVER_URL");
3408
3409 let err = init_workspace(&sub, "visdom", Some("http://127.0.0.1:9"))
3410 .await
3411 .unwrap_err();
3412 assert!(err.to_string().contains("inside the git repo"), "{err}");
3413 assert!(!sub.join(".tracevault").exists());
3414 }
3415
3416 #[tokio::test]
3419 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
3420 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3421 let tmp = tempfile::tempdir().unwrap();
3422 crate::test_helpers::init_git_repo(tmp.path());
3423 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3424 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3425 fs::write(
3426 tmp.path().join(".tracevault/config.toml"),
3427 format!("repo_id = \"{STRAY}\"\n"),
3428 )
3429 .unwrap();
3430
3431 let (repo_id, requests) = init_against(
3432 tmp.path(),
3433 vec![http_response("500 Internal Server Error", "{}")],
3434 )
3435 .await;
3436
3437 assert_eq!(repo_id.as_deref(), Some(STRAY));
3438 assert!(!registered(&requests));
3439 }
3440
3441 #[tokio::test]
3443 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
3444 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3445 let tmp = tempfile::tempdir().unwrap();
3446 crate::test_helpers::init_git_repo(tmp.path());
3447 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3448
3449 let (repo_id, requests) = init_against(
3450 tmp.path(),
3451 vec![
3452 resolve_remote_ok(),
3453 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3454 ],
3455 )
3456 .await;
3457
3458 assert_eq!(repo_id, None);
3459 assert!(!registered(&requests));
3460 }
3461
3462 #[tokio::test]
3465 async fn init_registers_for_a_codebase_without_live_repos() {
3466 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3467 let tmp = tempfile::tempdir().unwrap();
3468 crate::test_helpers::init_git_repo(tmp.path());
3469 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3470
3471 let (repo_id, requests) = init_against(
3472 tmp.path(),
3473 vec![
3474 resolve_remote_ok(),
3475 remote_detail(&[]),
3476 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
3477 ],
3478 )
3479 .await;
3480
3481 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3482 assert!(registered(&requests));
3483 }
3484
3485 #[tokio::test]
3487 async fn init_does_not_register_when_the_remote_check_fails() {
3488 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3489 let tmp = tempfile::tempdir().unwrap();
3490 crate::test_helpers::init_git_repo(tmp.path());
3491 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3492
3493 let (repo_id, requests) = init_against(
3494 tmp.path(),
3495 vec![http_response("500 Internal Server Error", "{}")],
3496 )
3497 .await;
3498
3499 assert_eq!(repo_id, None);
3500 assert!(!registered(&requests));
3501 }
3502}