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
721pub const PRE_PUSH_MARKER: &str = "# tracevault:enforce";
723const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
724
725fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
726 let hooks_dir = project_root.join(".git/hooks");
727 fs::create_dir_all(&hooks_dir)?;
728
729 let hook_path = hooks_dir.join("pre-push");
730 let tracevault_block = format!(
737 "{PRE_PUSH_MARKER}\n\
738 # Capture git's pre-push ref list once; `check` uses it to determine\n\
739 # which files are being pushed.\n\
740 tracevault_prepush_stdin=$(cat)\n\
741 tracevault sync 2>/dev/null || true\n\
742 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
743 );
744
745 if hook_path.exists() {
746 let existing = fs::read_to_string(&hook_path)?;
747
748 if existing.contains(PRE_PUSH_MARKER) {
750 return Ok(());
751 }
752
753 if existing.contains(OLD_HOOK_MARKER) {
755 let mut new_content = String::new();
756 let mut skip = false;
757 for line in existing.lines() {
758 if line.contains(OLD_HOOK_MARKER) {
759 skip = true;
760 continue;
761 }
762 if skip {
763 if line.starts_with("tracevault ") {
765 continue;
766 }
767 skip = false;
768 }
769 new_content.push_str(line);
770 new_content.push('\n');
771 }
772 if !new_content.ends_with('\n') {
773 new_content.push('\n');
774 }
775 new_content.push_str(&tracevault_block);
776 fs::write(&hook_path, new_content)?;
777 } else {
778 let mut content = existing;
780 if !content.ends_with('\n') {
781 content.push('\n');
782 }
783 content.push_str(&tracevault_block);
784 fs::write(&hook_path, content)?;
785 }
786 } else {
787 let content = format!("#!/bin/sh\n{tracevault_block}");
788 fs::write(&hook_path, content)?;
789 }
790
791 #[cfg(unix)]
793 {
794 use std::os::unix::fs::PermissionsExt;
795 let mut perms = fs::metadata(&hook_path)?.permissions();
796 perms.set_mode(0o755);
797 fs::set_permissions(&hook_path, perms)?;
798 }
799
800 Ok(())
801}
802
803pub const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
805
806fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
807 let hooks_dir = project_root.join(".git/hooks");
808 fs::create_dir_all(&hooks_dir)?;
809
810 let hook_path = hooks_dir.join("post-commit");
811 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
812
813 if hook_path.exists() {
814 let existing = fs::read_to_string(&hook_path)?;
815
816 if existing.contains(POST_COMMIT_MARKER) {
817 return Ok(());
818 }
819
820 let mut content = existing;
821 if !content.ends_with('\n') {
822 content.push('\n');
823 }
824 content.push_str(&tracevault_block);
825 fs::write(&hook_path, content)?;
826 } else {
827 let content = format!("#!/bin/sh\n{tracevault_block}");
828 fs::write(&hook_path, content)?;
829 }
830
831 #[cfg(unix)]
832 {
833 use std::os::unix::fs::PermissionsExt;
834 let mut perms = fs::metadata(&hook_path)?.permissions();
835 perms.set_mode(0o755);
836 fs::set_permissions(&hook_path, perms)?;
837 }
838
839 Ok(())
840}
841
842fn install_claude_hooks(
843 project_root: &Path,
844 target: ClaudeSettingsTarget,
845) -> Result<(), io::Error> {
846 let claude_dir = project_root.join(".claude");
847 fs::create_dir_all(&claude_dir)?;
848 merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())
849}
850
851pub fn tracevault_hooks() -> serde_json::Value {
852 serde_json::json!({
853 "PreToolUse": [{
854 "matcher": "Write|Edit|Bash",
855 "hooks": [{
856 "type": "command",
857 "command": "tracevault stream --event pre-tool-use",
858 "timeout": 10,
859 "statusMessage": "TraceVault: streaming pre-tool event"
860 }]
861 }],
862 "PostToolUse": [{
863 "matcher": "",
864 "hooks": [{
865 "type": "command",
866 "command": "tracevault stream --event post-tool-use",
867 "timeout": 10,
868 "statusMessage": "TraceVault: streaming post-tool event"
869 }]
870 }],
871 "Notification": [{
872 "matcher": "",
873 "hooks": [{
874 "type": "command",
875 "command": "tracevault stream --event notification",
876 "timeout": 10,
877 "statusMessage": "TraceVault: streaming notification"
878 }]
879 }],
880 "Stop": [{
881 "matcher": "",
882 "hooks": [{
883 "type": "command",
884 "command": "tracevault stream --event stop",
885 "timeout": 10,
886 "statusMessage": "TraceVault: finalizing session"
887 }]
888 }],
889 "SessionEnd": [{
892 "matcher": "",
893 "hooks": [{
894 "type": "command",
895 "command": "tracevault stream --event session-end",
896 "timeout": 10,
897 "statusMessage": "TraceVault: sending session cost"
898 }]
899 }],
900 "SubagentStop": [{
903 "matcher": "",
904 "hooks": [{
905 "type": "command",
906 "command": "tracevault stream --event subagent-stop",
907 "timeout": 10,
908 "statusMessage": "TraceVault: streaming subagent transcript"
909 }]
910 }],
911 "SessionStart": [{
912 "matcher": "",
913 "hooks": [{
914 "type": "command",
915 "command": "tracevault session-start",
916 "timeout": 10,
917 "statusMessage": "TraceVault: session start"
918 }]
919 }],
920 "UserPromptSubmit": [{
921 "matcher": "",
922 "hooks": [{
923 "type": "command",
924 "command": "tracevault user-prompt",
925 "timeout": 10,
926 "statusMessage": "TraceVault: policy reinforcement"
927 }]
928 }]
929 })
930}
931
932pub fn codex_hook_trust_notice() -> &'static str {
942 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
943 silently and no session is captured. Run `codex` once interactively in a repo and \
944 approve the hook-trust prompt; unattended runs (CI) can pass \
945 `--dangerously-bypass-hook-trust` instead."
946}
947
948pub fn codex_hooks() -> serde_json::Value {
958 serde_json::json!({
959 "SessionStart": [{
960 "matcher": "",
961 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
962 }],
963 "UserPromptSubmit": [{
964 "matcher": "",
965 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
966 }],
967 "PostToolUse": [{
968 "matcher": "",
969 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
970 }],
971 "Stop": [{
972 "matcher": "",
973 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
974 }]
975 })
976}
977
978const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
982const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
983const GSD_EXT_MANIFEST_JSON: &str =
984 include_str!("../../assets/gsd-extension/extension-manifest.json");
985
986fn gsd_extension_source_dir() -> io::Result<PathBuf> {
990 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
991 let config_dir = config_dir
992 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
993 Ok(config_dir.join("tracevault").join("gsd-extension"))
994}
995
996pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
1020 let home =
1021 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
1022 let gsd_home = home.join(".gsd");
1023
1024 let source_dir = gsd_extension_source_dir()?;
1025 fs::create_dir_all(&source_dir)?;
1026 fs::write(source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
1027 fs::write(source_dir.join("package.json"), GSD_EXT_PACKAGE_JSON)?;
1028 fs::write(
1029 source_dir.join("extension-manifest.json"),
1030 GSD_EXT_MANIFEST_JSON,
1031 )?;
1032
1033 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
1037 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
1038 }
1039
1040 let local_flag = project_root.is_some();
1044 let mut cmd = std::process::Command::new("gsd");
1045 cmd.arg("install").arg(&source_dir);
1046 if let Some(root) = project_root {
1047 cmd.arg("-l");
1048 cmd.current_dir(root);
1049 }
1050
1051 let retry_hint = format!(
1052 "gsd install {}{}",
1053 source_dir.display(),
1054 if local_flag { " -l" } else { "" }
1055 );
1056
1057 match cmd.output() {
1058 Ok(output) if output.status.success() => {
1059 println!(
1060 "TraceVault: installed and registered the GSD extension ({}).",
1061 source_dir.display()
1062 );
1063 }
1064 Ok(output) => {
1065 eprintln!(
1066 "TraceVault: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
1067 source_dir.display(),
1068 String::from_utf8_lossy(&output.stderr),
1069 );
1070 }
1071 Err(e) => {
1072 eprintln!(
1073 "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.",
1074 source_dir.display(),
1075 );
1076 }
1077 }
1078
1079 Ok(())
1080}
1081
1082const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
1085
1086pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
1102 let plugins_dir = match project_root {
1103 Some(root) => root.join(".opencode").join("plugins"),
1104 None => {
1105 let config_dir =
1106 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
1107 config_dir
1108 .ok_or_else(|| {
1109 io::Error::new(
1110 io::ErrorKind::NotFound,
1111 "could not determine the config directory for the OpenCode plugin install",
1112 )
1113 })?
1114 .join("opencode")
1115 .join("plugins")
1116 }
1117 };
1118
1119 write_opencode_plugin_files(&plugins_dir)
1120}
1121
1122fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
1123 fs::create_dir_all(plugins_dir)?;
1124 fs::write(plugins_dir.join("tracevault.ts"), OPENCODE_PLUGIN_INDEX)?;
1125 Ok(())
1126}
1127
1128pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");
1131
1132const AMP_PLUGIN_GITIGNORE_ENTRY: &str = ".amp/plugins/tracevault/";
1134
1135pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
1144 let plugins_dir = match project_root {
1145 Some(root) => root.join(".amp").join("plugins"),
1146 None => amp_user_config_dir()
1147 .ok_or_else(|| {
1148 io::Error::new(
1149 io::ErrorKind::NotFound,
1150 "could not determine the config directory for the Amp plugin install",
1151 )
1152 })?
1153 .join("plugins"),
1154 };
1155 let plugin_dir = plugins_dir.join("tracevault");
1156 fs::create_dir_all(&plugin_dir)?;
1157 let path = plugin_dir.join("index.ts");
1158 fs::write(&path, AMP_PLUGIN_INDEX)?;
1159 Ok(path)
1160}
1161
1162fn amp_user_config_dir() -> Option<PathBuf> {
1166 let xdg = std::env::var_os("XDG_CONFIG_HOME")
1167 .map(PathBuf::from)
1168 .filter(|p| p.is_absolute());
1169 xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
1170 .map(|c| c.join("amp"))
1171}
1172
1173pub fn amp_headless_notice() -> &'static str {
1178 "Amp loads the plugin in interactive sessions. For headless runs use \
1179`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
1180starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
1181path), so allow what it needs up front.\n\
1182The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
1183unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
1184ampcode.com, or exports it, can read them."
1185}
1186
1187pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
1199 let ext_root = gsd_home.join("extensions");
1200 let reg_path = ext_root.join("registry.json");
1201
1202 let reg: Option<serde_json::Value> = if reg_path.exists() {
1207 let content = fs::read_to_string(®_path)?;
1208 let parsed: serde_json::Value = match serde_json::from_str(&content) {
1209 Ok(v) => v,
1210 Err(_) => return Ok(()), };
1212 let corrupt = match parsed.as_object() {
1213 None => true,
1214 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
1215 };
1216 if corrupt {
1217 return Ok(()); }
1219 Some(parsed)
1220 } else {
1221 None
1222 };
1223
1224 let stale = ext_root.join("tracevault-tracker");
1226 if stale.exists() {
1227 fs::remove_dir_all(&stale)?;
1228 }
1229
1230 if let Some(mut reg) = reg {
1232 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
1233 let removed_tracker = entries.remove("tracevault-tracker").is_some();
1234 let removed_inert = entries.remove("tracevault").is_some();
1235 if removed_tracker || removed_inert {
1236 let tmp = reg_path.with_extension("json.tmp");
1238 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
1239 fs::rename(&tmp, ®_path)?;
1240 }
1241 }
1242 }
1243 Ok(())
1244}
1245
1246fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
1256 update_json_file(hooks_path, "its hooks", |root| {
1257 merge_hooks(root, ours, hooks_path)
1258 })
1259}
1260
1261pub(crate) fn update_json_file(
1269 path: &Path,
1270 what: &str,
1271 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
1272) -> io::Result<()> {
1273 if path
1278 .components()
1279 .any(|c| c == std::path::Component::ParentDir)
1280 {
1281 return Err(io::Error::new(
1282 io::ErrorKind::InvalidInput,
1283 format!("refusing to use path with '..': {}", path.display()),
1284 ));
1285 }
1286 let target = match fs::symlink_metadata(path) {
1290 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
1291 _ => path.to_path_buf(),
1292 };
1293 for _ in 0..3 {
1299 let existing = read_existing(&target)?;
1300 let mut root: serde_json::Value = match &existing {
1301 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1302 io::Error::new(
1303 io::ErrorKind::InvalidData,
1304 format!("Failed to parse {}: {e}", path.display()),
1305 )
1306 })?,
1307 None => serde_json::json!({}),
1308 };
1309
1310 let before = existing.is_some().then(|| root.to_string());
1311 mutate(&mut root)?;
1312 if before.as_deref() == Some(root.to_string().as_str())
1313 || (existing.is_none() && root == serde_json::json!({}))
1314 {
1315 return Ok(());
1316 }
1317
1318 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1319 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1320 })?;
1321 let tmp = unique_temp_sibling(&target);
1322 let published = write_owner_only(&tmp, formatted.as_bytes())
1323 .and_then(|()| {
1324 match &existing {
1327 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1328 None => Ok(()),
1329 }
1330 })
1331 .and_then(|()| {
1332 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1333 == existing.as_ref().map(|(_, c)| c.clone());
1334 if unchanged {
1335 fs::rename(&tmp, &target).map(|()| true)
1336 } else {
1337 Ok(false)
1338 }
1339 });
1340 match published {
1341 Ok(true) => return Ok(()),
1342 Ok(false) => {
1343 let _ = fs::remove_file(&tmp);
1344 }
1345 Err(e) => {
1346 let _ = fs::remove_file(&tmp);
1347 return Err(e);
1348 }
1349 }
1350 }
1351 Err(io::Error::other(format!(
1352 "{} kept changing while TraceVault updated {what}; re-run `tracevault init`",
1353 path.display()
1354 )))
1355}
1356
1357fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1359 let permissions = match fs::metadata(path) {
1360 Ok(meta) => meta.permissions(),
1361 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1362 Err(e) => return Err(e),
1363 };
1364 Ok(Some((permissions, fs::read_to_string(path)?)))
1365}
1366
1367fn unique_temp_sibling(target: &Path) -> PathBuf {
1371 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1372 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1373 let nanos = std::time::SystemTime::now()
1374 .duration_since(std::time::UNIX_EPOCH)
1375 .map(|d| d.subsec_nanos())
1376 .unwrap_or_default();
1377 let mut name = target.file_name().unwrap_or_default().to_os_string();
1378 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1379 target.with_file_name(name)
1380}
1381
1382fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1386 let mut options = fs::OpenOptions::new();
1387 options.write(true).create_new(true);
1388 #[cfg(unix)]
1389 {
1390 use std::os::unix::fs::OpenOptionsExt;
1391 options.mode(0o600);
1392 }
1393 options.open(path)?.write_all(contents)
1394}
1395
1396pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1400 let codex_dir = project_root.join(".codex");
1401 fs::create_dir_all(&codex_dir)?;
1402 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1403}
1404
1405pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1412 fs::create_dir_all(codex_dir)?;
1413 let base = codex_dir.canonicalize()?;
1415 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1416 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1417}
1418
1419const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1423
1424const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1425<!-- tracevault:workspace-mode -->
1426## TraceVault (workspace mode)
1427A session started in a registered repo's checkout is bound to that repo automatically. To work
1428on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1429policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1430one-off. Repos must already be registered with TraceVault. In a directory bound to a project
1431with `tracevault init --workspace`, sessions are recorded to that project without it, so
1432`repo switch` there is optional: it only adds the repo and its policies.
1433";
1434
1435const PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS: &[&str] = &[
1439 "\
1440<!-- tracevault:workspace-mode -->
1441## TraceVault (workspace mode)
1442You may be running detached from any single repository. Before working on a repo, run
1443`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
1444output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
1445already be registered with TraceVault.
1446",
1447 "\
1448<!-- tracevault:workspace-mode -->
1449## TraceVault (workspace mode)
1450A session started in a registered repo's checkout is bound to that repo automatically. To work
1451on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1452policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1453one-off. Repos must already be registered with TraceVault.
1454",
1455];
1456
1457fn replace_managed_block(content: &str) -> String {
1462 if content.contains(GLOBAL_CLAUDE_MD_BLOCK) {
1463 return content.to_string();
1464 }
1465 PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS
1466 .iter()
1467 .find(|old| content.contains(*old))
1468 .map_or_else(
1469 || content.to_string(),
1470 |old| content.replacen(old, GLOBAL_CLAUDE_MD_BLOCK, 1),
1471 )
1472}
1473
1474fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1481 if md_path
1483 .components()
1484 .any(|c| c == std::path::Component::ParentDir)
1485 {
1486 return Err(io::Error::new(
1487 io::ErrorKind::InvalidInput,
1488 format!("refusing to use path with '..': {}", md_path.display()),
1489 ));
1490 }
1491 let existing = if md_path.exists() {
1492 fs::read_to_string(md_path)?
1493 } else {
1494 String::new()
1495 };
1496 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
1497 let replaced = replace_managed_block(&existing);
1500 if replaced != existing {
1501 fs::write(md_path, replaced)?;
1502 }
1503 return Ok(());
1504 }
1505 let mut content = existing;
1506 if !content.is_empty() && !content.ends_with('\n') {
1507 content.push('\n');
1508 }
1509 if !content.is_empty() {
1510 content.push('\n');
1511 }
1512 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
1513 fs::write(md_path, content)
1514}
1515
1516pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1520 let joined = base.join(name);
1521 if joined.parent() != Some(base) {
1522 return Err(io::Error::new(
1523 io::ErrorKind::InvalidInput,
1524 format!(
1525 "refusing to access path outside {}: {}",
1526 base.display(),
1527 joined.display()
1528 ),
1529 ));
1530 }
1531 Ok(joined)
1532}
1533
1534const TRACEVAULT_COMMAND_PREFIX: &str = "tracevault ";
1540
1541fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1542 hook.get("command")
1543 .and_then(|c| c.as_str())
1544 .is_some_and(|c| c.starts_with(TRACEVAULT_COMMAND_PREFIX))
1545}
1546
1547fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1554 let mut slot = None;
1555 let mut kept = Vec::with_capacity(entries.len());
1556 for mut entry in entries.drain(..) {
1557 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1558 let before = inner.len();
1559 inner.retain(|hook| !is_tracevault_hook(hook));
1560 if inner.is_empty() && before > 0 {
1561 slot.get_or_insert(kept.len());
1562 continue;
1563 }
1564 }
1565 kept.push(entry);
1566 }
1567 *entries = kept;
1568 slot
1569}
1570
1571fn merge_hooks(
1585 settings: &mut serde_json::Value,
1586 ours: &serde_json::Value,
1587 path: &Path,
1588) -> io::Result<()> {
1589 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1590 io::Error::new(
1591 io::ErrorKind::InvalidData,
1592 format!("{} is not a JSON object", path.display()),
1593 )
1594 })?;
1595
1596 let hooks_value = settings_obj
1597 .entry("hooks")
1598 .or_insert_with(|| serde_json::json!({}));
1599 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
1600 io::Error::new(
1601 io::ErrorKind::InvalidData,
1602 format!("{} \"hooks\" key is not a JSON object", path.display()),
1603 )
1604 })?;
1605
1606 let empty = serde_json::Map::new();
1607 let ours_obj = ours.as_object().unwrap_or(&empty);
1608
1609 for event in ours_obj.keys() {
1611 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
1612 return Err(io::Error::new(
1613 io::ErrorKind::InvalidData,
1614 format!(
1615 "{} \"hooks\".\"{event}\" is not a JSON array",
1616 path.display()
1617 ),
1618 ));
1619 }
1620 }
1621
1622 let mut emptied = Vec::new();
1623 for (event, value) in hooks_obj.iter_mut() {
1624 let Some(existing) = value.as_array_mut() else {
1625 continue;
1626 };
1627 let had_entries = !existing.is_empty();
1628 let slot = strip_tracevault_hooks(existing);
1629 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
1630 match our_entries {
1631 Some(our_entries) => {
1632 let at = slot.unwrap_or(existing.len());
1633 existing.splice(at..at, our_entries.iter().cloned());
1634 }
1635 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
1636 None => {}
1637 }
1638 }
1639 hooks_obj.retain(|event, _| !emptied.contains(event));
1641
1642 for (event, our_array) in ours_obj {
1643 if !hooks_obj.contains_key(event) {
1644 hooks_obj.insert(event.clone(), our_array.clone());
1645 }
1646 }
1647
1648 Ok(())
1649}
1650
1651pub fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
1656 let text = match fs::read_to_string(path) {
1657 Ok(text) => text,
1658 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
1659 Err(e) => return Err(e),
1660 };
1661 let settings: serde_json::Value =
1662 serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
1663 Ok(settings
1664 .get("hooks")
1665 .and_then(|h| h.as_object())
1666 .into_iter()
1667 .flat_map(|events| events.values())
1668 .filter_map(|groups| groups.as_array())
1669 .flatten()
1670 .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
1671 .flatten()
1672 .any(is_tracevault_hook))
1673}
1674
1675pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
1679 merge_hooks_into_file(path, &tracevault_hooks())
1680}
1681
1682pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
1688 fs::create_dir_all(claude_dir)?;
1689
1690 let base = claude_dir.canonicalize()?;
1693
1694 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
1696
1697 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
1699}
1700
1701pub fn write_global_user_config_in(
1711 config_root: &Path,
1712 requested: Option<UserContext>,
1713) -> io::Result<Option<PathBuf>> {
1714 fs::create_dir_all(config_root)?;
1715 let mut config = crate::config::try_load_user_config_in(config_root)
1717 .ok()
1718 .flatten()
1719 .unwrap_or_default();
1720 let user_context = requested
1722 .or_else(|| config.user_context.clone())
1723 .unwrap_or(UserContext::Toggle(true));
1724 let active = user_context
1725 .resolve()
1726 .map(|_| user_context.path_in(config_root));
1727 config.user_context = Some(user_context);
1728 fs::write(user_config_path_in(config_root), config.to_toml())?;
1729 if let Some(ref ctx_path) = active {
1730 if !ctx_path.exists() {
1731 Context::default().save_to(ctx_path)?;
1732 }
1733 }
1734 Ok(active)
1735}
1736
1737#[cfg(test)]
1738mod tests {
1739 use super::*;
1740 use std::io::{BufRead, BufReader, Write};
1741 use std::net::TcpListener;
1742 use std::thread;
1743
1744 #[test]
1750 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
1751 let notice = codex_hook_trust_notice();
1752 assert!(
1753 notice.contains("hook trust"),
1754 "notice must name what is missing: {notice}"
1755 );
1756 assert!(
1757 notice.contains("codex") && notice.contains("approve"),
1758 "notice must tell the user to run codex and approve the prompt: {notice}"
1759 );
1760 assert!(
1761 notice.contains("--dangerously-bypass-hook-trust"),
1762 "notice must name the flag for unattended/CI runs: {notice}"
1763 );
1764 assert!(
1765 notice.contains("silently"),
1766 "notice must say the failure is silent, which is why it needs saying: {notice}"
1767 );
1768 }
1769
1770 fn spawn_once(response: String) -> String {
1773 let response: &'static str = Box::leak(response.into_boxed_str());
1774 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
1775 let addr = listener.local_addr().unwrap();
1776 thread::spawn(move || {
1777 if let Ok((stream, _)) = listener.accept() {
1778 let mut reader = BufReader::new(stream);
1779 let mut request_line = String::new();
1780 let _ = reader.read_line(&mut request_line);
1781 let mut stream = reader.into_inner();
1782 let _ = stream.write_all(response.as_bytes());
1783 let _ = stream.flush();
1784 }
1785 });
1786 format!("http://{addr}")
1787 }
1788
1789 fn http_response(status: &str, body: &str) -> String {
1792 format!(
1793 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
1794 status,
1795 body.len(),
1796 body
1797 )
1798 }
1799
1800 fn add_origin_remote(dir: &Path, url: &str) {
1801 let ok = std::process::Command::new("git")
1802 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
1803 .status()
1804 .expect("git remote add failed")
1805 .success();
1806 assert!(ok, "git remote add must succeed");
1807 }
1808
1809 #[test]
1810 fn linked_worktree_primary_detects_linked_and_primary() {
1811 let tmp = tempfile::tempdir().unwrap();
1812 let repo = tmp.path().join("repo");
1813 let wt = tmp.path().join("linked-wt");
1814 std::fs::create_dir_all(&repo).unwrap();
1815 crate::test_helpers::init_git_repo(&repo);
1816 crate::test_helpers::add_worktree(&repo, &wt);
1817
1818 assert!(
1820 linked_worktree_primary(&repo).is_none(),
1821 "primary checkout must not be flagged as a linked worktree"
1822 );
1823 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
1825 assert_eq!(
1826 primary.canonicalize().unwrap(),
1827 repo.canonicalize().unwrap(),
1828 "must resolve to the primary repo root"
1829 );
1830 }
1831
1832 #[test]
1833 fn linked_worktree_primary_none_for_non_git() {
1834 let tmp = tempfile::tempdir().unwrap();
1835 assert!(
1836 linked_worktree_primary(tmp.path()).is_none(),
1837 "a non-git directory is not a linked worktree"
1838 );
1839 }
1840
1841 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
1843 entry.get("hooks")?.get(0)?.get("command")?.as_str()
1844 }
1845
1846 #[test]
1847 fn merge_hooks_into_empty_settings_adds_all_our_events() {
1848 let mut settings = serde_json::json!({});
1849 let ours = tracevault_hooks();
1850 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1851
1852 let hooks = settings.get("hooks").unwrap();
1853 for event in [
1854 "PreToolUse",
1855 "PostToolUse",
1856 "Notification",
1857 "Stop",
1858 "SessionEnd",
1859 "SubagentStop",
1860 "SessionStart",
1861 "UserPromptSubmit",
1862 ] {
1863 assert!(hooks.get(event).is_some(), "missing event {event}");
1864 }
1865 }
1866
1867 #[test]
1868 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
1869 let mut settings = serde_json::json!({
1870 "model": "opus",
1871 "hooks": {
1872 "PreToolUse": [{
1873 "matcher": "",
1874 "hooks": [{ "type": "command", "command": "my-own-hook" }]
1875 }]
1876 }
1877 });
1878 let ours = tracevault_hooks();
1879 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1880
1881 assert_eq!(settings.get("model").unwrap(), "opus");
1883
1884 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1885 assert_eq!(pre_tool_use.len(), 2);
1887 let commands: Vec<&str> = pre_tool_use
1888 .iter()
1889 .map(|e| entry_command(e).unwrap())
1890 .collect();
1891 assert!(commands.contains(&"my-own-hook"));
1892 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
1893
1894 assert!(settings["hooks"]["SessionStart"].is_array());
1896 }
1897
1898 #[test]
1899 fn merge_hooks_is_idempotent() {
1900 let mut settings = serde_json::json!({});
1901 let ours = tracevault_hooks();
1902 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1903 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1904
1905 for event in [
1906 "PreToolUse",
1907 "PostToolUse",
1908 "Notification",
1909 "Stop",
1910 "SessionEnd",
1911 "SubagentStop",
1912 "SessionStart",
1913 "UserPromptSubmit",
1914 ] {
1915 let arr = settings["hooks"][event].as_array().unwrap();
1916 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1917 }
1918 }
1919
1920 #[test]
1921 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
1922 let mut settings = serde_json::json!({
1926 "hooks": {
1927 "PreToolUse": [{
1928 "matcher": "Write|Edit|Bash",
1929 "hooks": [
1930 { "type": "command", "command": "other", "timeout": 3 },
1931 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
1932 ]
1933 }]
1934 }
1935 });
1936 merge_hooks(
1937 &mut settings,
1938 &tracevault_hooks(),
1939 Path::new("settings.json"),
1940 )
1941 .unwrap();
1942
1943 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1944 assert_eq!(
1945 pre_tool_use[0],
1946 serde_json::json!({
1947 "matcher": "Write|Edit|Bash",
1948 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
1949 })
1950 );
1951 assert_eq!(
1952 &pre_tool_use[1..],
1953 tracevault_hooks()["PreToolUse"].as_array().unwrap()
1954 );
1955 }
1956
1957 fn stale_tracevault_hooks() -> serde_json::Value {
1960 let entry = |matcher: &str, event: &str| {
1961 serde_json::json!([{
1962 "matcher": matcher,
1963 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
1964 }])
1965 };
1966 serde_json::json!({
1967 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
1968 "PostToolUse": entry("", "post-tool-use"),
1969 "Notification": entry("", "notification"),
1970 "Stop": entry("", "stop"),
1971 })
1972 }
1973
1974 #[test]
1975 fn merge_hooks_upgrades_stale_tracevault_entries() {
1976 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
1977 merge_hooks(
1978 &mut settings,
1979 &tracevault_hooks(),
1980 Path::new("settings.json"),
1981 )
1982 .unwrap();
1983 assert_eq!(settings["hooks"], tracevault_hooks());
1984 }
1985
1986 #[test]
1987 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
1988 let mut settings = serde_json::json!({
1991 "hooks": {
1992 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
1993 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
1994 "Custom": "left alone"
1995 }
1996 });
1997 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
1998
1999 let hooks = settings["hooks"].as_object().unwrap();
2000 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
2001 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
2002 assert_eq!(hooks["Custom"], "left alone");
2003 for (event, entries) in codex_hooks().as_object().unwrap() {
2004 assert_eq!(&hooks[event], entries, "{event}");
2005 }
2006 }
2007
2008 #[test]
2009 fn merge_hooks_rerun_keeps_our_entry_in_place() {
2010 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
2013 settings["hooks"]["Stop"]
2014 .as_array_mut()
2015 .unwrap()
2016 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
2017 let before = settings.clone();
2018 merge_hooks(
2019 &mut settings,
2020 &tracevault_hooks(),
2021 Path::new("settings.json"),
2022 )
2023 .unwrap();
2024 assert_eq!(settings.to_string(), before.to_string());
2025 }
2026
2027 #[test]
2028 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
2029 let foreign = serde_json::json!({
2030 "matcher": "",
2031 "hooks": [
2032 { "type": "command", "command": "tracevault-wrapper stream" },
2033 { "type": "command", "command": "echo tracevault stream" },
2034 { "type": "command", "command": " tracevault check" }
2035 ]
2036 });
2037 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
2038 merge_hooks(
2039 &mut settings,
2040 &tracevault_hooks(),
2041 Path::new("settings.json"),
2042 )
2043 .unwrap();
2044 assert_eq!(settings["hooks"]["Stop"][0], foreign);
2045 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
2046 }
2047
2048 #[test]
2049 fn merge_hooks_errors_on_non_object_top_level() {
2050 let mut settings = serde_json::json!([1, 2, 3]);
2051 let ours = tracevault_hooks();
2052 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2053 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2054 assert!(err.to_string().contains("settings.json"));
2055 }
2056
2057 #[test]
2058 fn merge_hooks_errors_on_non_object_top_level_number() {
2059 let mut settings = serde_json::json!(42);
2060 let ours = tracevault_hooks();
2061 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2062 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2063 }
2064
2065 #[test]
2066 fn merge_hooks_errors_on_non_object_hooks() {
2067 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
2068 let ours = tracevault_hooks();
2069 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2070 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2071 assert!(err.to_string().contains("hooks"));
2072 }
2073
2074 #[test]
2075 fn merge_hooks_errors_on_non_array_event_value() {
2076 let mut settings = serde_json::json!({
2077 "hooks": {
2078 "PreToolUse": "not-an-array"
2079 }
2080 });
2081 let ours = tracevault_hooks();
2082 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2083 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2084 assert!(err.to_string().contains("PreToolUse"));
2085 }
2086
2087 #[test]
2088 fn install_global_hooks_writes_settings_and_claude_md() {
2089 let tmp = tempfile::tempdir().unwrap();
2090 let claude_dir = tmp.path().join(".claude");
2091
2092 install_global_hooks(&claude_dir).unwrap();
2093
2094 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2095 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2096 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
2097 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
2098 }
2099
2100 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2101 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2102 }
2103
2104 #[test]
2105 fn install_global_hooks_is_idempotent() {
2106 let tmp = tempfile::tempdir().unwrap();
2107 let claude_dir = tmp.path().join(".claude");
2108
2109 install_global_hooks(&claude_dir).unwrap();
2110 install_global_hooks(&claude_dir).unwrap();
2111
2112 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2113 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2114 for event in [
2115 "PreToolUse",
2116 "PostToolUse",
2117 "Notification",
2118 "Stop",
2119 "SessionEnd",
2120 "SubagentStop",
2121 "SessionStart",
2122 "UserPromptSubmit",
2123 ] {
2124 let arr = settings["hooks"][event].as_array().unwrap();
2125 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
2126 }
2127
2128 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2129 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
2130 assert_eq!(
2131 marker_count, 1,
2132 "CLAUDE.md marker should appear exactly once"
2133 );
2134 }
2135
2136 #[test]
2137 fn install_global_hooks_preserves_existing_claude_md_content() {
2138 let tmp = tempfile::tempdir().unwrap();
2139 let claude_dir = tmp.path().join(".claude");
2140 fs::create_dir_all(&claude_dir).unwrap();
2141 fs::write(
2142 claude_dir.join("CLAUDE.md"),
2143 "# My existing notes\nSome content.\n",
2144 )
2145 .unwrap();
2146
2147 install_global_hooks(&claude_dir).unwrap();
2148
2149 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2150 assert!(claude_md.contains("# My existing notes"));
2151 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2152 }
2153
2154 #[test]
2155 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
2156 let tmp = tempfile::tempdir().unwrap();
2157 let claude_dir = tmp.path().join(".claude");
2158
2159 install_global_hooks(&claude_dir).unwrap();
2160
2161 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2162 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2163 assert!(settings["hooks"].get("SessionStart").is_some());
2164
2165 let leftover = fs::read_dir(&claude_dir)
2166 .unwrap()
2167 .filter_map(|e| e.ok())
2168 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2169 assert!(
2170 !leftover,
2171 "no settings.json.tmp should remain after install"
2172 );
2173 }
2174
2175 #[test]
2176 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
2177 let tmp = tempfile::tempdir().unwrap();
2178 let claude_dir = tmp.path().join(".claude");
2179 fs::create_dir_all(&claude_dir).unwrap();
2180 let settings_path = claude_dir.join("settings.json");
2181 let original = "[1, 2, 3]";
2182 fs::write(&settings_path, original).unwrap();
2183
2184 let err = install_global_hooks(&claude_dir).unwrap_err();
2185 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2186
2187 let after = fs::read_to_string(&settings_path).unwrap();
2190 assert_eq!(after, original);
2191 let leftover = fs::read_dir(&claude_dir)
2192 .unwrap()
2193 .filter_map(|e| e.ok())
2194 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2195 assert!(!leftover, "no tmp file should be left behind on error");
2196 }
2197
2198 #[test]
2199 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
2200 let tmp = tempfile::tempdir().unwrap();
2201 let claude_dir = tmp.path().join(".claude");
2202 fs::create_dir_all(&claude_dir).unwrap();
2203 let settings_path = claude_dir.join("settings.json");
2204 let original = r#"{"hooks": "oops"}"#;
2205 fs::write(&settings_path, original).unwrap();
2206
2207 let err = install_global_hooks(&claude_dir).unwrap_err();
2208 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2209
2210 let after = fs::read_to_string(&settings_path).unwrap();
2211 assert_eq!(after, original);
2212 }
2213
2214 #[test]
2215 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
2216 let tmp = tempfile::tempdir().unwrap();
2217 let claude_dir = tmp.path().join(".claude");
2218 fs::create_dir_all(&claude_dir).unwrap();
2219 let settings_path = claude_dir.join("settings.json");
2220 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
2221 fs::write(&settings_path, original).unwrap();
2222
2223 let err = install_global_hooks(&claude_dir).unwrap_err();
2224 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2225
2226 let after = fs::read_to_string(&settings_path).unwrap();
2227 assert_eq!(after, original);
2228 }
2229
2230 #[test]
2231 fn safe_join_allows_direct_child_file() {
2232 let tmp = tempfile::tempdir().unwrap();
2233 let base = tmp.path();
2234 let result = safe_join(base, "settings.json").unwrap();
2235 assert_eq!(result.parent(), Some(base));
2236 assert_eq!(result.file_name().unwrap(), "settings.json");
2237 }
2238
2239 #[test]
2240 fn safe_join_rejects_path_traversal() {
2241 let tmp = tempfile::tempdir().unwrap();
2242 let base = tmp.path();
2243 let result = safe_join(base, "../evil");
2244 assert!(result.is_err());
2245 let err = result.unwrap_err();
2246 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2247 assert!(err.to_string().contains("refusing to access path outside"));
2248 }
2249
2250 #[test]
2251 fn safe_join_rejects_absolute_path() {
2252 let tmp = tempfile::tempdir().unwrap();
2253 let base = tmp.path();
2254 let result = safe_join(base, "/etc/passwd");
2255 assert!(result.is_err());
2258 }
2259
2260 #[test]
2261 fn write_global_user_config_enables_and_creates_context() {
2262 let root = tempfile::tempdir().unwrap();
2263 let active = write_global_user_config_in(root.path(), None).unwrap();
2264 let cfg = crate::config::try_load_user_config_in(root.path())
2265 .unwrap()
2266 .unwrap();
2267 assert_eq!(
2270 cfg.user_context.unwrap().resolve_in(root.path()),
2271 Some(crate::config::default_user_context_path_in(root.path()))
2272 );
2273 let ctx = crate::config::default_user_context_path_in(root.path());
2274 assert_eq!(active, Some(ctx.clone()));
2275 assert!(ctx.exists());
2276 }
2277
2278 #[test]
2279 fn write_global_user_config_can_disable() {
2280 let root = tempfile::tempdir().unwrap();
2281 let active = write_global_user_config_in(
2282 root.path(),
2283 Some(crate::config::UserContext::Toggle(false)),
2284 )
2285 .unwrap();
2286 let cfg = crate::config::try_load_user_config_in(root.path())
2287 .unwrap()
2288 .unwrap();
2289 assert!(matches!(
2290 cfg.user_context,
2291 Some(crate::config::UserContext::Toggle(false))
2292 ));
2293 assert_eq!(active, None, "disabled → no active context path");
2294 assert!(
2296 !crate::config::default_user_context_path_in(root.path()).exists(),
2297 "disabled user context must not create a context.json"
2298 );
2299 }
2300
2301 #[test]
2302 fn write_global_user_config_custom_path_seeds_that_file_only() {
2303 let root = tempfile::tempdir().unwrap();
2304 let custom = root.path().join("custom-ctx.json");
2305 let active = write_global_user_config_in(
2306 root.path(),
2307 Some(crate::config::UserContext::Path(
2308 custom.to_string_lossy().into_owned(),
2309 )),
2310 )
2311 .unwrap();
2312 assert_eq!(active, Some(custom.clone()));
2313 assert!(custom.exists(), "the configured custom path must be seeded");
2314 assert!(
2315 !crate::config::default_user_context_path_in(root.path()).exists(),
2316 "the default context.json must NOT be created when a custom path is configured"
2317 );
2318 }
2319
2320 #[test]
2321 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
2322 let root = tempfile::tempdir().unwrap();
2323 let custom = root.path().join("custom-ctx.json");
2324 write_global_user_config_in(
2326 root.path(),
2327 Some(crate::config::UserContext::Path(
2328 custom.to_string_lossy().into_owned(),
2329 )),
2330 )
2331 .unwrap();
2332 let active = write_global_user_config_in(root.path(), None).unwrap();
2334 assert_eq!(
2335 active,
2336 Some(custom.clone()),
2337 "re-run without flags must preserve the custom path"
2338 );
2339 let cfg = crate::config::try_load_user_config_in(root.path())
2340 .unwrap()
2341 .unwrap();
2342 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
2343 }
2344
2345 #[test]
2346 fn install_global_codex_hooks_writes_and_is_idempotent() {
2347 let tmp = tempfile::tempdir().unwrap();
2348 let codex_dir = tmp.path().join(".codex");
2349
2350 install_global_codex_hooks(&codex_dir).unwrap();
2351 install_global_codex_hooks(&codex_dir).unwrap();
2352
2353 let v: serde_json::Value =
2354 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2355 .unwrap();
2356 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2357 let arr = v["hooks"][event].as_array().unwrap();
2358 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
2359 }
2360 assert!(v["hooks"].get("PreToolUse").is_none());
2361 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
2363 assert_eq!(
2364 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
2365 1,
2366 "AGENTS.md workspace-mode block must appear exactly once"
2367 );
2368 let leftover = fs::read_dir(&codex_dir)
2370 .unwrap()
2371 .filter_map(|e| e.ok())
2372 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2373 assert!(!leftover);
2374 }
2375
2376 #[test]
2379 fn has_tracevault_hooks_reads_codex_hooks_json() {
2380 let tmp = tempfile::tempdir().unwrap();
2381 let codex_dir = tmp.path().join(".codex");
2382 install_global_codex_hooks(&codex_dir).unwrap();
2383 assert!(has_tracevault_hooks(&codex_dir.join("hooks.json")).unwrap());
2384
2385 let foreign = tmp.path().join("foreign.json");
2386 fs::write(
2387 &foreign,
2388 r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"other-tool stop"}]}]}}"#,
2389 )
2390 .unwrap();
2391 assert!(!has_tracevault_hooks(&foreign).unwrap());
2392 }
2393
2394 #[test]
2395 fn codex_hooks_has_expected_events_and_commands() {
2396 let h = codex_hooks();
2397 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2398 assert!(h.get(event).is_some(), "missing codex event {event}");
2399 }
2400 assert!(h.get("PreToolUse").is_none());
2404 assert!(h.get("Notification").is_none());
2405 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2407 assert_eq!(
2408 cmd("PostToolUse"),
2409 "tracevault stream --event post-tool-use --agent codex"
2410 );
2411 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2412 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2413 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2414 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2416 }
2417
2418 #[test]
2419 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2420 let tmp = tempfile::tempdir().unwrap();
2421 install_codex_hooks(tmp.path()).unwrap();
2422 install_codex_hooks(tmp.path()).unwrap();
2423
2424 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2425 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2426 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2427 let arr = v["hooks"][event].as_array().unwrap();
2428 assert_eq!(
2429 arr.len(),
2430 1,
2431 "event {event} must not be duplicated on re-run"
2432 );
2433 }
2434 assert!(v["hooks"].get("PreToolUse").is_none());
2435 }
2436
2437 #[test]
2438 fn install_codex_hooks_preserves_existing_user_hook() {
2439 let tmp = tempfile::tempdir().unwrap();
2440 let codex_dir = tmp.path().join(".codex");
2441 fs::create_dir_all(&codex_dir).unwrap();
2442 fs::write(
2445 codex_dir.join("hooks.json"),
2446 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2447 )
2448 .unwrap();
2449
2450 install_codex_hooks(tmp.path()).unwrap();
2451
2452 let v: serde_json::Value =
2453 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2454 .unwrap();
2455 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2457 .as_array()
2458 .unwrap()
2459 .iter()
2460 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2461 .collect();
2462 assert!(
2463 post_cmds.contains(&"my-own"),
2464 "user PostToolUse hook preserved"
2465 );
2466 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2467 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2469 .as_array()
2470 .unwrap()
2471 .iter()
2472 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2473 .collect();
2474 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2475 }
2476
2477 const FOREIGN_SETTINGS: &str = r#"{
2481 "permissions": { "allow": ["Bash(ls)"] },
2482 "hooks": {
2483 "PreToolUse": [
2484 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2485 { "matcher": "Write|Edit", "hooks": [
2486 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2487 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2488 ] }
2489 ],
2490 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2491 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2492 },
2493 "model": "opus"
2494}"#;
2495
2496 fn expected_foreign_entries() -> Vec<String> {
2500 [
2501 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2502 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2503 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2504 ]
2505 .map(String::from)
2506 .to_vec()
2507 }
2508
2509 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2510 entry["hooks"]
2511 .as_array()
2512 .unwrap()
2513 .iter()
2514 .any(is_tracevault_hook)
2515 }
2516
2517 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2518 let v: serde_json::Value =
2519 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2520 assert_eq!(
2521 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2522 ["permissions", "hooks", "model"],
2523 "top-level keys kept, in their order"
2524 );
2525 assert_eq!(
2526 v["permissions"],
2527 serde_json::json!({ "allow": ["Bash(ls)"] })
2528 );
2529 let hooks = v["hooks"].as_object().unwrap();
2530 let foreign: Vec<String> = hooks
2531 .values()
2532 .flat_map(|entries| entries.as_array().unwrap())
2533 .filter(|e| !holds_tracevault_hook(e))
2534 .map(|e| e.to_string())
2535 .collect();
2536 assert_eq!(foreign, expected_foreign_entries());
2537 let ours = ours.as_object().unwrap();
2538 for (event, entries) in hooks {
2539 let mine: Vec<&serde_json::Value> = entries
2540 .as_array()
2541 .unwrap()
2542 .iter()
2543 .filter(|e| holds_tracevault_hook(e))
2544 .collect();
2545 let want: Vec<&serde_json::Value> = ours
2546 .get(event)
2547 .map(|o| o.as_array().unwrap().iter().collect())
2548 .unwrap_or_default();
2549 assert_eq!(mine, want, "TraceVault entries under {event}");
2550 }
2551 for event in ours.keys() {
2552 assert!(hooks.contains_key(event), "missing {event}");
2553 }
2554 }
2555
2556 #[test]
2557 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2558 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2559 let tmp = tempfile::tempdir().unwrap();
2560 let path = tmp.path().join(".claude").join(target.filename());
2561 fs::create_dir_all(path.parent().unwrap()).unwrap();
2562 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2563
2564 install_claude_hooks(tmp.path(), target).unwrap();
2565 assert_installed_over_foreign(&path, &tracevault_hooks());
2566
2567 let after_first = fs::read(&path).unwrap();
2569 install_claude_hooks(tmp.path(), target).unwrap();
2570 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2571 }
2572 }
2573
2574 #[test]
2575 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2576 let tmp = tempfile::tempdir().unwrap();
2577 let claude_dir = tmp.path().join(".claude");
2578 fs::create_dir_all(&claude_dir).unwrap();
2579 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2580
2581 install_global_hooks(&claude_dir).unwrap();
2582 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2583 }
2584
2585 #[test]
2586 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2587 for global in [false, true] {
2588 let tmp = tempfile::tempdir().unwrap();
2589 let codex_dir = tmp.path().join(".codex");
2590 fs::create_dir_all(&codex_dir).unwrap();
2591 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2592
2593 if global {
2594 install_global_codex_hooks(&codex_dir).unwrap();
2595 } else {
2596 install_codex_hooks(tmp.path()).unwrap();
2597 }
2598 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2599 }
2600 }
2601
2602 #[test]
2603 fn up_to_date_hook_file_is_not_rewritten() {
2604 let tmp = tempfile::tempdir().unwrap();
2606 let path = tmp.path().join(".claude/settings.json");
2607 fs::create_dir_all(path.parent().unwrap()).unwrap();
2608 let mut body = Vec::new();
2609 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
2610 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
2611 serde::Serialize::serialize(
2612 &serde_json::json!({ "hooks": tracevault_hooks() }),
2613 &mut ser,
2614 )
2615 .unwrap();
2616 fs::write(&path, &body).unwrap();
2617
2618 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
2619 assert_eq!(fs::read(&path).unwrap(), body);
2620 }
2621
2622 #[test]
2623 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
2624 for (target, body) in [
2625 (ClaudeSettingsTarget::Shared, "{ not json"),
2626 (ClaudeSettingsTarget::Local, "[1, 2]"),
2627 (ClaudeSettingsTarget::Shared, "null"),
2628 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
2629 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
2630 ] {
2631 let tmp = tempfile::tempdir().unwrap();
2632 let path = tmp.path().join(".claude").join(target.filename());
2633 fs::create_dir_all(path.parent().unwrap()).unwrap();
2634 fs::write(&path, body).unwrap();
2635
2636 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
2637 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
2638 assert_eq!(
2639 fs::read_to_string(&path).unwrap(),
2640 body,
2641 "file must be untouched"
2642 );
2643 assert_eq!(
2644 fs::read_dir(path.parent().unwrap()).unwrap().count(),
2645 1,
2646 "no temp file left behind"
2647 );
2648 }
2649 }
2650
2651 #[test]
2652 fn concurrent_installs_never_publish_a_partial_file() {
2653 let tmp = tempfile::tempdir().unwrap();
2659 let path = tmp.path().join("settings.json");
2660 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2661 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
2662 let reader = {
2663 let (path, done) = (path.clone(), done.clone());
2664 std::thread::spawn(move || {
2665 while !done.load(std::sync::atomic::Ordering::Relaxed) {
2666 let body = fs::read_to_string(&path).unwrap();
2667 serde_json::from_str::<serde_json::Value>(&body).unwrap();
2668 }
2669 })
2670 };
2671 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
2672 .into_iter()
2673 .map(|ours| {
2674 let path = path.clone();
2675 std::thread::spawn(move || {
2676 for _ in 0..200 {
2677 if let Err(e) = merge_hooks_into_file(&path, &ours) {
2678 assert!(e.to_string().contains("kept changing"), "{e}");
2679 }
2680 }
2681 })
2682 })
2683 .collect();
2684 for writer in writers {
2685 writer.join().unwrap();
2686 }
2687 done.store(true, std::sync::atomic::Ordering::Relaxed);
2688 reader.join().unwrap();
2689 let v: serde_json::Value =
2690 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
2691 assert_eq!(v["model"], "opus");
2692 assert_eq!(
2693 fs::read_dir(tmp.path()).unwrap().count(),
2694 1,
2695 "no temp file left"
2696 );
2697 }
2698
2699 #[cfg(unix)]
2700 #[test]
2701 fn install_claude_hooks_keeps_file_permissions() {
2702 use std::os::unix::fs::PermissionsExt;
2703 let tmp = tempfile::tempdir().unwrap();
2704 let path = tmp.path().join(".claude/settings.local.json");
2705 fs::create_dir_all(path.parent().unwrap()).unwrap();
2706 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2707 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
2708
2709 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
2710
2711 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
2712 assert_eq!(mode, 0o600);
2713 assert_installed_over_foreign(&path, &tracevault_hooks());
2714 }
2715
2716 #[cfg(unix)]
2717 #[test]
2718 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
2719 let tmp = tempfile::tempdir().unwrap();
2720 let central = tmp.path().join("central/claude-settings.json");
2721 fs::create_dir_all(central.parent().unwrap()).unwrap();
2722 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
2723 let link = tmp.path().join("repo/.claude/settings.json");
2724 fs::create_dir_all(link.parent().unwrap()).unwrap();
2725 std::os::unix::fs::symlink(¢ral, &link).unwrap();
2726
2727 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
2728
2729 assert!(fs::symlink_metadata(&link)
2730 .unwrap()
2731 .file_type()
2732 .is_symlink());
2733 assert_installed_over_foreign(¢ral, &tracevault_hooks());
2734 }
2735
2736 #[cfg(unix)]
2737 #[test]
2738 fn install_claude_hooks_refuses_dangling_symlink() {
2739 let tmp = tempfile::tempdir().unwrap();
2740 let link = tmp.path().join(".claude/settings.json");
2741 fs::create_dir_all(link.parent().unwrap()).unwrap();
2742 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
2743
2744 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
2745 assert!(fs::symlink_metadata(&link)
2746 .unwrap()
2747 .file_type()
2748 .is_symlink());
2749 assert!(!tmp.path().join("gone.json").exists());
2750 }
2751
2752 #[test]
2753 fn validate_init_flags_rejects_claude_settings_with_codex() {
2754 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
2755 }
2756
2757 #[test]
2758 fn validate_init_flags_allows_codex_without_claude_settings() {
2759 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
2760 }
2761
2762 #[test]
2763 fn validate_init_flags_allows_claude_with_claude_settings() {
2764 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
2765 }
2766
2767 #[test]
2768 fn merge_hooks_into_file_rejects_parent_dir() {
2769 let tmp = tempfile::tempdir().unwrap();
2770 let bad = tmp.path().join("..").join("hooks.json");
2771 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
2772 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2773 }
2774
2775 #[test]
2776 fn append_workspace_md_rejects_parent_dir() {
2777 let tmp = tempfile::tempdir().unwrap();
2778 let bad = tmp.path().join("..").join("AGENTS.md");
2779 let err = append_workspace_md(&bad).unwrap_err();
2780 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2781 }
2782
2783 #[tokio::test]
2784 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
2785 let tmp = tempfile::tempdir().unwrap();
2786 let root = tmp.path();
2787 crate::test_helpers::init_git_repo(root);
2788 fs::create_dir_all(root.join(".tracevault")).unwrap();
2791 fs::write(
2792 root.join(".tracevault/config.toml"),
2793 "api_key = \"tvk_test\"\n",
2794 )
2795 .unwrap();
2796
2797 let entry = init_in_directory(
2798 root,
2799 None,
2800 None,
2801 false,
2802 Some(crate::config::UserContext::Toggle(false)),
2803 crate::agent::Agent::Codex,
2804 )
2805 .await
2806 .unwrap();
2807
2808 assert!(root.join(".codex").join("hooks.json").exists());
2810 assert!(!root.join(".claude").join("settings.json").exists());
2811 assert_eq!(entry, ".codex/hooks.json");
2812
2813 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
2815 assert!(gi.contains(".codex/hooks.json"));
2816 assert!(gi.contains(".tracevault/"));
2817 }
2818
2819 #[tokio::test]
2831 async fn init_in_directory_registers_repo_and_persists_repo_id() {
2832 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2833 let tmp = tempfile::tempdir().unwrap();
2834 let root = tmp.path();
2835 crate::test_helpers::init_git_repo(root);
2836 add_origin_remote(root, "git@github.com:org/repo.git");
2837
2838 let repo_id = "11111111-1111-4111-8111-111111111111";
2839 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
2840 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2843 http_response("404 Not Found", NO_REMOTE),
2844 http_response("200 OK", &body),
2845 ]);
2846
2847 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2848 _guard.set("XDG_CONFIG_HOME", tmp.path());
2849 _guard.set("TRACEVAULT_API_KEY", "tok");
2850 _guard.remove("TRACEVAULT_SERVER_URL");
2851
2852 init_in_directory(
2853 root,
2854 Some(&base),
2855 None,
2856 true,
2857 Some(crate::config::UserContext::Toggle(false)),
2858 crate::agent::Agent::Codex,
2859 )
2860 .await
2861 .unwrap();
2862
2863 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2864 assert_eq!(
2865 cfg.repo_id,
2866 Some(repo_id.to_string()),
2867 "successful registration must persist repo_id to config.toml"
2868 );
2869 }
2870
2871 #[tokio::test]
2877 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
2878 let _env_lock = crate::test_helpers::lock_env_mutation().await;
2879 let tmp = tempfile::tempdir().unwrap();
2880 let root = tmp.path();
2881 crate::test_helpers::init_git_repo(root);
2882 add_origin_remote(root, "git@github.com:org/repo.git");
2883
2884 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
2885 http_response("404 Not Found", NO_REMOTE),
2886 http_response("403 Forbidden", ""),
2887 ]);
2888
2889 let mut _guard = crate::test_helpers::EnvVarGuard::new();
2890 _guard.set("XDG_CONFIG_HOME", tmp.path());
2891 _guard.set("TRACEVAULT_API_KEY", "tok");
2892 _guard.remove("TRACEVAULT_SERVER_URL");
2893
2894 let entry = init_in_directory(
2895 root,
2896 Some(&base),
2897 None,
2898 true,
2899 Some(crate::config::UserContext::Toggle(false)),
2900 crate::agent::Agent::Codex,
2901 )
2902 .await
2903 .expect("a registration failure (403) must not abort init itself");
2904 assert_eq!(entry, ".codex/hooks.json");
2905
2906 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
2907 assert!(
2908 cfg.repo_id.is_none(),
2909 "a 403 registration failure must not persist a repo_id"
2910 );
2911 }
2912
2913 #[tokio::test]
2918 async fn registration_failure_message_flags_403_as_not_authorized() {
2919 let base = spawn_once(http_response("403 Forbidden", ""));
2920 let client = ApiClient::new(&base, Some("tok"));
2921 let err = client
2922 .register_repo(crate::api_client::RegisterRepoRequest {
2923 repo_name: "repo".into(),
2924 github_url: Some("git@github.com:org/repo.git".into()),
2925 })
2926 .await
2927 .unwrap_err();
2928 let msg = registration_failure_message(err.as_ref());
2929 assert!(
2930 msg.contains("not authorized"),
2931 "403 registration failure must surface a not-authorized message; got: {msg}"
2932 );
2933 }
2934
2935 #[tokio::test]
2938 async fn registration_failure_message_generic_for_non_403() {
2939 let base = spawn_once(http_response("500 Internal Server Error", ""));
2940 let client = ApiClient::new(&base, Some("tok"));
2941 let err = client
2942 .register_repo(crate::api_client::RegisterRepoRequest {
2943 repo_name: "repo".into(),
2944 github_url: Some("git@github.com:org/repo.git".into()),
2945 })
2946 .await
2947 .unwrap_err();
2948 let msg = registration_failure_message(err.as_ref());
2949 assert!(
2950 msg.contains("could not register repo on server"),
2951 "got: {msg}"
2952 );
2953 assert!(!msg.contains("not authorized"), "got: {msg}");
2954 }
2955
2956 #[tokio::test]
2961 async fn registration_failure_message_does_not_misclassify_403_in_body() {
2962 let base = spawn_once(http_response(
2963 "500 Internal Server Error",
2964 "upstream error 403 from proxy",
2965 ));
2966 let client = ApiClient::new(&base, Some("tok"));
2967 let err = client
2968 .register_repo(crate::api_client::RegisterRepoRequest {
2969 repo_name: "repo".into(),
2970 github_url: Some("git@github.com:org/repo.git".into()),
2971 })
2972 .await
2973 .unwrap_err();
2974 let msg = registration_failure_message(err.as_ref());
2975 assert!(
2976 !msg.contains("not authorized"),
2977 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
2978 );
2979 assert!(
2980 msg.contains("could not register repo on server"),
2981 "got: {msg}"
2982 );
2983 }
2984
2985 #[tokio::test]
2989 async fn registration_failure_message_flags_404_as_version_mismatch() {
2990 let base = spawn_once(http_response("404 Not Found", ""));
2991 let client = ApiClient::new(&base, Some("tok"));
2992 let err = client
2993 .register_repo(crate::api_client::RegisterRepoRequest {
2994 repo_name: "repo".into(),
2995 github_url: Some("git@github.com:org/repo.git".into()),
2996 })
2997 .await
2998 .unwrap_err();
2999 let msg = registration_failure_message(err.as_ref());
3000 assert!(
3001 msg.to_lowercase().contains("version mismatch"),
3002 "a 404 registration failure should hint at a version mismatch; got: {msg}"
3003 );
3004 }
3005
3006 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
3010 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
3011 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
3012 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
3013
3014 fn resolve_remote_ok() -> String {
3015 http_response(
3016 "200 OK",
3017 &format!(
3018 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
3019 ),
3020 )
3021 }
3022
3023 fn remote_detail(repos: &[(&str, &str)]) -> String {
3024 let repos: Vec<String> = repos
3025 .iter()
3026 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
3027 .collect();
3028 http_response(
3029 "200 OK",
3030 &format!(
3031 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
3032 repos.join(",")
3033 ),
3034 )
3035 }
3036
3037 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
3040 let (base, rx) = crate::test_helpers::spawn_seq(responses);
3041 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3042 _guard.set("XDG_CONFIG_HOME", root);
3043 _guard.set("TRACEVAULT_API_KEY", "tok");
3044 _guard.remove("TRACEVAULT_SERVER_URL");
3045
3046 init_in_directory(
3047 root,
3048 Some(&base),
3049 None,
3050 true,
3051 Some(crate::config::UserContext::Toggle(false)),
3052 crate::agent::Agent::Codex,
3053 )
3054 .await
3055 .expect("init succeeds");
3056
3057 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
3058 (cfg.repo_id, rx.try_iter().collect())
3059 }
3060
3061 fn registered(requests: &[String]) -> bool {
3062 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
3063 }
3064
3065 #[tokio::test]
3068 async fn init_binds_the_existing_repo_of_a_known_remote() {
3069 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3070 let tmp = tempfile::tempdir().unwrap();
3071 crate::test_helpers::init_git_repo(tmp.path());
3072 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3073
3074 let (repo_id, requests) = init_against(
3075 tmp.path(),
3076 vec![
3077 resolve_remote_ok(),
3078 remote_detail(&[(CANONICAL, "tracevault")]),
3079 ],
3080 )
3081 .await;
3082
3083 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3084 assert!(!registered(&requests), "requests: {requests:?}");
3085 }
3086
3087 #[tokio::test]
3090 async fn init_binds_the_record_named_like_the_checkout() {
3091 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3092 let tmp = tempfile::tempdir().unwrap();
3093 crate::test_helpers::init_git_repo(tmp.path());
3094 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3095 let dir_name = crate::resolution::git_repo_name(tmp.path());
3096
3097 let (repo_id, requests) = init_against(
3098 tmp.path(),
3099 vec![
3100 resolve_remote_ok(),
3101 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
3102 ],
3103 )
3104 .await;
3105
3106 assert_eq!(repo_id.as_deref(), Some(STRAY));
3107 assert!(!registered(&requests));
3108 }
3109
3110 #[tokio::test]
3112 async fn init_rerun_keeps_the_previously_bound_repo() {
3113 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3114 let tmp = tempfile::tempdir().unwrap();
3115 crate::test_helpers::init_git_repo(tmp.path());
3116 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3117 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3118 fs::write(
3119 tmp.path().join(".tracevault/config.toml"),
3120 format!("repo_id = \"{STRAY}\"\n"),
3121 )
3122 .unwrap();
3123
3124 let (repo_id, requests) = init_against(
3125 tmp.path(),
3126 vec![
3127 resolve_remote_ok(),
3128 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3129 ],
3130 )
3131 .await;
3132
3133 assert_eq!(repo_id.as_deref(), Some(STRAY));
3134 assert!(!registered(&requests));
3135 }
3136
3137 #[tokio::test]
3140 async fn init_binding_keeps_the_rest_of_the_config() {
3141 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3142 let tmp = tempfile::tempdir().unwrap();
3143 crate::test_helpers::init_git_repo(tmp.path());
3144 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3145 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3146 fs::write(
3147 tmp.path().join(".tracevault/config.toml"),
3148 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
3149 )
3150 .unwrap();
3151
3152 let (repo_id, requests) = init_against(
3153 tmp.path(),
3154 vec![
3155 http_response(
3157 "200 OK",
3158 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3159 ),
3160 resolve_remote_ok(),
3161 remote_detail(&[(CANONICAL, "tracevault")]),
3162 ],
3163 )
3164 .await;
3165
3166 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3167 assert!(
3168 requests[0].starts_with("GET /api/v1/projects"),
3169 "{requests:?}"
3170 );
3171 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
3172 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
3173 assert_eq!(cfg.default_project, None);
3174 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3175 assert_eq!(cfg.project_name.as_deref(), Some("payments"));
3176 }
3177
3178 const PROJECT: &str = "00000000-0000-4000-8000-0000000000aa";
3179
3180 #[tokio::test]
3183 async fn init_unknown_default_project_errors_and_writes_nothing() {
3184 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3185 let tmp = tempfile::tempdir().unwrap();
3186 crate::test_helpers::init_git_repo(tmp.path());
3187 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3188 let content = "default_project = \"typo\"\n";
3189 fs::write(tmp.path().join(".tracevault/config.toml"), content).unwrap();
3190 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3191 "200 OK",
3192 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3193 )]);
3194 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3195 _guard.set("XDG_CONFIG_HOME", tmp.path());
3196 _guard.set("TRACEVAULT_API_KEY", "tok");
3197 _guard.remove("TRACEVAULT_SERVER_URL");
3198
3199 let err = init_in_directory(
3200 tmp.path(),
3201 Some(&base),
3202 None,
3203 true,
3204 None,
3205 crate::agent::Agent::Codex,
3206 )
3207 .await
3208 .unwrap_err();
3209
3210 assert!(err.to_string().contains("'typo'"), "{err}");
3211 assert_eq!(
3212 fs::read_to_string(tmp.path().join(".tracevault/config.toml")).unwrap(),
3213 content
3214 );
3215 assert!(!tmp.path().join(".codex/hooks.json").exists());
3216 }
3217
3218 #[tokio::test]
3222 async fn init_workspace_binds_a_non_git_dir_to_a_project() {
3223 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3224 let tmp = tempfile::tempdir().unwrap();
3225 let dir = tmp.path().join("umbrella");
3226 fs::create_dir_all(&dir).unwrap();
3227 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response(
3228 "200 OK",
3229 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3230 )]);
3231 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3232 _guard.set("XDG_CONFIG_HOME", tmp.path());
3233 _guard.set("TRACEVAULT_API_KEY", "tok");
3234 _guard.remove("TRACEVAULT_SERVER_URL");
3235
3236 let bound = init_workspace(&dir, "visdom", Some(&base)).await.unwrap();
3237
3238 assert_eq!(bound.project_id.to_string(), PROJECT);
3239 assert_eq!(bound.project_name, "visdom");
3240 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3241 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3242 assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
3243 assert_eq!(cfg.repo_id, None);
3244 assert_eq!(cfg.server_url.as_deref(), Some(base.as_str()));
3245 assert!(dir.join(".tracevault/.gitignore").exists());
3246 let requests: Vec<String> = rx.try_iter().collect();
3247 assert_eq!(requests.len(), 1, "{requests:?}");
3248 let sub = dir.join("notes");
3250 fs::create_dir_all(&sub).unwrap();
3251 assert_eq!(
3252 crate::paths::resolve_project_root(&sub)
3253 .root
3254 .canonicalize()
3255 .unwrap(),
3256 dir.canonicalize().unwrap()
3257 );
3258 }
3259
3260 #[tokio::test]
3263 async fn init_workspace_rebinds_and_keeps_other_keys() {
3264 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3265 let tmp = tempfile::tempdir().unwrap();
3266 let dir = tmp.path();
3267 fs::create_dir_all(dir.join(".tracevault")).unwrap();
3268 fs::write(
3269 dir.join(".tracevault/config.toml"),
3270 "default_project = \"old\"\nproject_id = \"00000000-0000-4000-8000-000000000001\"\nuser_context = false\n",
3271 )
3272 .unwrap();
3273 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3274 "200 OK",
3275 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3276 )]);
3277 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3278 _guard.set("XDG_CONFIG_HOME", dir);
3279 _guard.set("TRACEVAULT_API_KEY", "tok");
3280 _guard.remove("TRACEVAULT_SERVER_URL");
3281
3282 init_workspace(dir, "visdom", Some(&base)).await.unwrap();
3283
3284 let cfg = crate::config::TracevaultConfig::load(dir).unwrap();
3285 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3286 assert_eq!(cfg.default_project, None);
3287 assert!(matches!(
3288 cfg.user_context,
3289 Some(crate::config::UserContext::Toggle(false))
3290 ));
3291 }
3292
3293 #[test]
3297 fn append_workspace_md_upgrades_an_older_block_in_place() {
3298 let tmp = tempfile::tempdir().unwrap();
3299 let md = tmp.path().join("CLAUDE.md");
3300 for old in PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS {
3301 fs::write(
3303 &md,
3304 format!("# Mine\nkeep me\n\n{old}## After\nalso keep\n"),
3305 )
3306 .unwrap();
3307
3308 append_workspace_md(&md).unwrap();
3309 let got = fs::read_to_string(&md).unwrap();
3310 assert_eq!(
3311 got,
3312 format!("# Mine\nkeep me\n\n{GLOBAL_CLAUDE_MD_BLOCK}## After\nalso keep\n")
3313 );
3314 append_workspace_md(&md).unwrap();
3315 assert_eq!(fs::read_to_string(&md).unwrap(), got);
3316 }
3317
3318 let edited = "x\n\n<!-- tracevault:workspace-mode -->\n## T\nmy own words\n";
3320 fs::write(&md, edited).unwrap();
3321 append_workspace_md(&md).unwrap();
3322 assert_eq!(fs::read_to_string(&md).unwrap(), edited);
3323 }
3324
3325 #[tokio::test]
3328 async fn init_workspace_refuses_a_server_url_the_credential_is_not_for() {
3329 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3330 let tmp = tempfile::tempdir().unwrap();
3331 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response("200 OK", "[]")]);
3332 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3333 fs::write(
3334 tmp.path().join(".tracevault/config.toml"),
3335 "server_url = \"http://other.example.invalid\"\napi_key = \"tvk_x\"\n",
3336 )
3337 .unwrap();
3338 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3339 _guard.set("XDG_CONFIG_HOME", tmp.path());
3340 _guard.remove("TRACEVAULT_API_KEY");
3341 _guard.remove("TRACEVAULT_SERVER_URL");
3342
3343 let err = init_workspace(tmp.path(), "visdom", Some(&base))
3344 .await
3345 .unwrap_err();
3346 assert!(err.to_string().contains("not --server-url"), "{err}");
3347 assert_eq!(rx.try_iter().count(), 0, "no request may be sent");
3348 }
3349
3350 #[tokio::test]
3351 async fn credential_url_mismatch_only_for_a_different_explicit_server() {
3352 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3353 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3354 _guard.remove("TRACEVAULT_API_KEY");
3355 assert!(credential_url_mismatch(Some("https://a/"), Some("https://a")).is_none());
3356 assert!(credential_url_mismatch(None, Some("https://b")).is_none());
3357 assert!(credential_url_mismatch(Some("https://a"), None).is_none());
3358 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_some());
3359 _guard.set("TRACEVAULT_API_KEY", "tvk_for_b");
3361 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_none());
3362 }
3363
3364 #[tokio::test]
3367 async fn migrate_cwd_config_migrates_the_dirs_config() {
3368 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3369 let tmp = tempfile::tempdir().unwrap();
3370 let dir = tmp.path().join("umbrella");
3371 fs::create_dir_all(dir.join(".tracevault")).unwrap();
3372 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3373 "200 OK",
3374 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3375 )]);
3376 fs::write(
3377 dir.join(".tracevault/config.toml"),
3378 format!("server_url = \"{base}\"\napi_key = \"tvk_x\"\ndefault_project = \"visdom\"\n"),
3379 )
3380 .unwrap();
3381 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3382 _guard.set("XDG_CONFIG_HOME", tmp.path());
3383 _guard.remove("TRACEVAULT_API_KEY");
3384 _guard.remove("TRACEVAULT_SERVER_URL");
3385
3386 migrate_cwd_config(&dir).await.unwrap();
3387
3388 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3389 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3390 assert_eq!(cfg.default_project, None);
3391 }
3392
3393 #[tokio::test]
3395 async fn init_workspace_unknown_or_ambiguous_name_writes_nothing() {
3396 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3397 for name in ["nope", "dup"] {
3398 let tmp = tempfile::tempdir().unwrap();
3399 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3400 "200 OK",
3401 r#"[{"id":"00000000-0000-4000-8000-000000000001","name":"dup"},{"id":"00000000-0000-4000-8000-000000000002","name":"dup"}]"#,
3402 )]);
3403 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3404 _guard.set("XDG_CONFIG_HOME", tmp.path());
3405 _guard.set("TRACEVAULT_API_KEY", "tok");
3406 _guard.remove("TRACEVAULT_SERVER_URL");
3407
3408 let err = init_workspace(tmp.path(), name, Some(&base))
3409 .await
3410 .unwrap_err();
3411 assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
3412 assert!(!tmp.path().join(".tracevault").exists(), "{name}");
3413 }
3414 }
3415
3416 #[tokio::test]
3419 async fn init_workspace_refuses_a_git_subdirectory() {
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 let sub = tmp.path().join("pkg");
3424 fs::create_dir_all(&sub).unwrap();
3425 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3426 _guard.set("XDG_CONFIG_HOME", tmp.path());
3427 _guard.set("TRACEVAULT_API_KEY", "tok");
3428 _guard.remove("TRACEVAULT_SERVER_URL");
3429
3430 let err = init_workspace(&sub, "visdom", Some("http://127.0.0.1:9"))
3431 .await
3432 .unwrap_err();
3433 assert!(err.to_string().contains("inside the git repo"), "{err}");
3434 assert!(!sub.join(".tracevault").exists());
3435 }
3436
3437 #[tokio::test]
3440 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
3441 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3442 let tmp = tempfile::tempdir().unwrap();
3443 crate::test_helpers::init_git_repo(tmp.path());
3444 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3445 fs::create_dir_all(tmp.path().join(".tracevault")).unwrap();
3446 fs::write(
3447 tmp.path().join(".tracevault/config.toml"),
3448 format!("repo_id = \"{STRAY}\"\n"),
3449 )
3450 .unwrap();
3451
3452 let (repo_id, requests) = init_against(
3453 tmp.path(),
3454 vec![http_response("500 Internal Server Error", "{}")],
3455 )
3456 .await;
3457
3458 assert_eq!(repo_id.as_deref(), Some(STRAY));
3459 assert!(!registered(&requests));
3460 }
3461
3462 #[tokio::test]
3464 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
3465 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3466 let tmp = tempfile::tempdir().unwrap();
3467 crate::test_helpers::init_git_repo(tmp.path());
3468 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3469
3470 let (repo_id, requests) = init_against(
3471 tmp.path(),
3472 vec![
3473 resolve_remote_ok(),
3474 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3475 ],
3476 )
3477 .await;
3478
3479 assert_eq!(repo_id, None);
3480 assert!(!registered(&requests));
3481 }
3482
3483 #[tokio::test]
3486 async fn init_registers_for_a_codebase_without_live_repos() {
3487 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3488 let tmp = tempfile::tempdir().unwrap();
3489 crate::test_helpers::init_git_repo(tmp.path());
3490 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3491
3492 let (repo_id, requests) = init_against(
3493 tmp.path(),
3494 vec![
3495 resolve_remote_ok(),
3496 remote_detail(&[]),
3497 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
3498 ],
3499 )
3500 .await;
3501
3502 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3503 assert!(registered(&requests));
3504 }
3505
3506 #[tokio::test]
3508 async fn init_does_not_register_when_the_remote_check_fails() {
3509 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3510 let tmp = tempfile::tempdir().unwrap();
3511 crate::test_helpers::init_git_repo(tmp.path());
3512 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3513
3514 let (repo_id, requests) = init_against(
3515 tmp.path(),
3516 vec![http_response("500 Internal Server Error", "{}")],
3517 )
3518 .await;
3519
3520 assert_eq!(repo_id, None);
3521 assert!(!registered(&requests));
3522 }
3523}