1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use crate::program::{CLI, ENV, TOP};
5use crate::resolution::{git_remote_url, git_repo_name, RegistrationPlan};
6use std::fs;
7use std::io::{self, BufRead, IsTerminal, Write};
8use std::path::{Path, PathBuf};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
12pub enum ClaudeSettingsTarget {
13 Shared,
15 Local,
17}
18
19impl ClaudeSettingsTarget {
20 pub fn filename(self) -> &'static str {
21 match self {
22 ClaudeSettingsTarget::Shared => "settings.json",
23 ClaudeSettingsTarget::Local => "settings.local.json",
24 }
25 }
26
27 pub fn gitignore_entry(self) -> &'static str {
28 match self {
29 ClaudeSettingsTarget::Shared => ".claude/settings.json",
30 ClaudeSettingsTarget::Local => ".claude/settings.local.json",
31 }
32 }
33}
34
35fn resolve_claude_target(
39 explicit: Option<ClaudeSettingsTarget>,
40) -> io::Result<ClaudeSettingsTarget> {
41 if let Some(target) = explicit {
42 return Ok(target);
43 }
44 if !io::stdin().is_terminal() {
45 return Ok(ClaudeSettingsTarget::Shared);
46 }
47
48 let stdout = io::stdout();
49 let mut stdout = stdout.lock();
50 write!(
51 stdout,
52 "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
53 )?;
54 stdout.flush()?;
55
56 let mut line = String::new();
57 io::stdin().lock().read_line(&mut line)?;
58 let answer = line.trim().to_lowercase();
59 Ok(match answer.as_str() {
60 "l" | "local" => ClaudeSettingsTarget::Local,
61 _ => ClaudeSettingsTarget::Shared,
62 })
63}
64
65fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
73 let output = std::process::Command::new("git")
74 .args(["rev-parse", "--git-dir", "--git-common-dir"])
75 .current_dir(dir)
76 .output()
77 .ok()?;
78 if !output.status.success() {
79 return None;
80 }
81 let stdout = String::from_utf8(output.stdout).ok()?;
82 let mut lines = stdout.lines();
83 let git_dir = lines.next()?.trim();
84 let git_common_dir = lines.next()?.trim();
85
86 let git_dir = dir.join(git_dir).canonicalize().ok()?;
89 let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
90
91 if git_dir == git_common_dir {
92 None } else {
94 git_common_dir.parent().map(Path::to_path_buf)
95 }
96}
97
98pub fn validate_init_flags(
104 agent: crate::agent::Agent,
105 claude_settings_set: bool,
106) -> Result<(), String> {
107 if matches!(
108 agent,
109 crate::agent::Agent::Codex
110 | crate::agent::Agent::Gsd
111 | crate::agent::Agent::OpenCode
112 | crate::agent::Agent::Amp
113 ) && claude_settings_set
114 {
115 return Err("--claude-settings only applies to --agent claude-code".to_string());
116 }
117 Ok(())
118}
119
120pub async fn init_in_directory(
125 project_root: &Path,
126 server_url: Option<&str>,
127 claude_settings: Option<ClaudeSettingsTarget>,
128 no_gitignore: bool,
129 user_context: Option<UserContext>,
130 agent: crate::agent::Agent,
131) -> Result<String, io::Error> {
132 if !project_root.join(".git").exists() {
134 return Err(io::Error::new(
135 io::ErrorKind::NotFound,
136 "Not a git repository. Run 'git init' first.",
137 ));
138 }
139
140 if let Some(primary) = linked_worktree_primary(project_root) {
146 return Err(io::Error::new(
147 io::ErrorKind::Unsupported,
148 format!(
149 "Run `{TOP} init` from the primary checkout ({}), not a linked worktree. \
150 cd there and run it again — all worktrees share the primary's .visdom/.",
151 primary.display()
152 ),
153 ));
154 }
155
156 let existing_config = TracevaultConfig::try_load(project_root).map_err(|e| {
160 io::Error::new(
161 io::ErrorKind::InvalidData,
162 format!(
163 "cannot read the existing .visdom/tracing.toml ({e}). Fix or remove it, \
164 then run `{TOP} init` again."
165 ),
166 )
167 })?;
168
169 let (resolved_url, resolved_credential) =
178 crate::credentials::resolve_credentials_quiet(project_root)
179 .map_err(|e| io::Error::other(e.to_string()))?;
180 let effective_url = server_url.map(String::from).or(resolved_url.clone());
181 if resolved_credential.is_none() {
182 return Err(io::Error::new(
183 io::ErrorKind::PermissionDenied,
184 not_logged_in_message(effective_url.as_deref()),
185 ));
186 }
187
188 let mut existing_config = existing_config;
193 if let (Some(cfg), Some(url)) = (existing_config.as_mut(), effective_url.as_deref()) {
194 if cfg.default_project.is_some() {
195 match credential_url_mismatch(resolved_url.as_deref(), server_url) {
198 Some(msg) => eprintln!(
199 "Warning: not migrating default_project: {msg}. Run `{CLI} sync` \
200 once logged in to that server."
201 ),
202 None => {
203 let client = ApiClient::with_credential(url, resolved_credential.clone());
204 migrate_config_in_init(cfg, &client).await?;
205 }
206 }
207 }
208 }
209
210 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
213 {
214 crate::agent::Agent::ClaudeCode => {
215 let target = resolve_claude_target(claude_settings)?;
216 (Some(target), target.gitignore_entry().to_string())
217 }
218 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
219 crate::agent::Agent::Gsd => (None, ".gsd/".to_string()),
225 crate::agent::Agent::OpenCode => (None, ".opencode/".to_string()),
230 crate::agent::Agent::Amp => (None, amp_plugin_gitignore_entry(project_root)),
233 };
234
235 let config_dir = TracevaultConfig::config_dir(project_root);
237 fs::create_dir_all(&config_dir)?;
238 fs::create_dir_all(config_dir.join("sessions"))?;
239 fs::create_dir_all(config_dir.join("cache"))?;
240 TracevaultConfig::ensure_gitignore(&config_dir)?;
243
244 if !no_gitignore {
246 update_root_gitignore(project_root, &hook_gitignore_entry)?;
247 }
248
249 let remote_url = git_remote_url(project_root);
251 if remote_url.is_none() {
252 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
253 eprintln!("Run 'git remote add origin <url>' then '{CLI} sync' to register.");
254 }
255
256 let mut config = existing_config.unwrap_or_default();
261 if let Some(url) = server_url {
262 config.server_url = Some(url.to_string());
263 }
264 config.user_context = user_context
265 .or(config.user_context)
266 .or(Some(UserContext::Toggle(true)));
267 config.save(project_root)?;
268
269 let previous_repo_id = config
272 .repo_id
273 .as_deref()
274 .and_then(|id| id.parse::<uuid::Uuid>().ok());
275
276 match agent {
278 crate::agent::Agent::ClaudeCode => {
279 let target =
281 claude_target.expect("claude settings target is resolved for the Claude agent");
282 install_claude_hooks(project_root, target)?;
283 }
284 crate::agent::Agent::Codex => {
285 install_codex_hooks(project_root)?;
286 println!("{}", codex_hook_trust_notice());
287 }
288 crate::agent::Agent::Gsd => {
289 install_gsd_extension(Some(project_root))?;
297 }
298 crate::agent::Agent::OpenCode => {
299 install_opencode_plugin(Some(project_root))?;
300 }
301 crate::agent::Agent::Amp => {
302 let path = install_amp_plugin(Some(project_root))?;
303 println!("Installed the Visdom Amp plugin in {}", path.display());
304 println!("{}", amp_headless_notice());
305 }
306 }
307
308 install_git_hook(project_root)?;
310 install_post_commit_hook(project_root)?;
311
312 let detected = crate::hooks::detect_tools(project_root);
314 for tool in &detected {
315 println!(" Detected: {}", tool.name());
316 }
317
318 if let (Some(url), Some(remote)) = (effective_url, remote_url) {
319 let client = ApiClient::with_credential(&url, resolved_credential);
320 let repo_name = git_repo_name(project_root);
321 let origin_url = remote.clone();
324
325 match crate::resolution::plan_registration(
329 &client,
330 &origin_url,
331 &repo_name,
332 previous_repo_id,
333 )
334 .await
335 {
336 Ok(RegistrationPlan::Existing(codebase, repo_id)) => {
337 println!(
338 "Bound to existing repo {} (id: {repo_id}); not registering another record \
339 for this codebase",
340 codebase
341 .repos
342 .iter()
343 .find(|r| r.id == repo_id)
344 .map_or("", |r| r.name.as_str())
345 );
346 println!(
347 "{}",
348 crate::resolution::codebase_line(
349 codebase.remote.name.as_deref(),
350 &codebase.remote.normalized_url,
351 &codebase.remote.clone_status
352 )
353 );
354 persist_repo_binding(project_root, repo_id, Some(&codebase.remote));
355 }
356 Ok(RegistrationPlan::Ambiguous(codebase)) => {
357 eprintln!(
358 "Warning: codebase {} already has {} repo records ({}) and none is named \
359 '{repo_name}'; not registering another. Set `repo_id = \"<id>\"` in \
360 .visdom/tracing.toml to the one this checkout belongs to.",
361 codebase.display_name(),
362 codebase.repos.len(),
363 codebase.repo_list()
364 );
365 }
366 Ok(RegistrationPlan::Register) => {
367 register_new_repo(&client, project_root, repo_name, origin_url).await;
368 }
369 Err(e) => {
372 eprintln!(
373 "Warning: could not check the server for an existing repo of this remote \
374 ({e}); not registering. Run `{TOP} init` again once the server is \
375 reachable."
376 );
377 }
378 }
379 }
380
381 Ok(hook_gitignore_entry)
382}
383
384async fn migrate_config_in_init(
389 config: &mut TracevaultConfig,
390 client: &ApiClient,
391) -> Result<(), io::Error> {
392 use crate::commands::migrate::{migrate_default_project, migration_report, ResolveNameError};
393 match migrate_default_project(config, client).await {
394 Ok(migration) => {
395 if let Some(line) = migration_report(&migration) {
396 println!("{line}");
397 }
398 Ok(())
399 }
400 Err(ResolveNameError::Unreachable(e)) => {
401 eprintln!(
402 "Warning: could not migrate default_project (could not list projects: {e}); \
403 it stays unused for capture until `{CLI} sync` succeeds."
404 );
405 Ok(())
406 }
407 Err(e @ ResolveNameError::Name(_)) => {
408 Err(io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))
409 }
410 }
411}
412
413pub async fn migrate_cwd_config(cwd: &Path) -> Result<(), io::Error> {
421 let root = crate::paths::resolve_project_root(cwd).root;
422 let Ok(Some(mut config)) = TracevaultConfig::try_load(&root) else {
423 return Ok(());
424 };
425 if config.default_project.is_none() {
426 return Ok(());
427 }
428 let Ok((Some(url), credential @ Some(_))) =
429 crate::credentials::resolve_credentials_quiet(&root)
430 else {
431 eprintln!(
432 "Warning: {} has a legacy default_project that needs a login to migrate; run \
433 `{CLI} sync` there once logged in.",
434 TracevaultConfig::config_path(&root).display()
435 );
436 return Ok(());
437 };
438 let client = ApiClient::with_credential(&url, credential);
439 migrate_config_in_init(&mut config, &client).await?;
440 if config.default_project.is_none() {
441 config.save(&root)?;
442 }
443 Ok(())
444}
445
446fn credential_url_mismatch(resolved: Option<&str>, explicit: Option<&str>) -> Option<String> {
454 let env_key = std::env::var("TRACEVAULT_API_KEY")
455 .ok()
456 .is_some_and(|k| !k.trim().is_empty());
457 if env_key {
458 return None;
459 }
460 let (resolved, explicit) = (resolved?, explicit?);
461 (!crate::credentials::same_server(resolved, explicit)).then(|| {
462 format!(
463 "the credential in use is for {resolved}, not --server-url {explicit}; log in \
464 there first (`{TOP} login --server-url {explicit}`) or omit --server-url"
465 )
466 })
467}
468
469#[derive(Debug)]
471pub struct WorkspaceInit {
472 pub project_id: uuid::Uuid,
473 pub project_name: String,
474 pub config_path: PathBuf,
476}
477
478pub async fn init_workspace(
494 dir: &Path,
495 project_name: &str,
496 server_url: Option<&str>,
497) -> Result<WorkspaceInit, io::Error> {
498 let resolved = crate::paths::resolve_project_root(dir);
499 if resolved.source == crate::paths::ProjectRootSource::Git {
500 let same = match (resolved.root.canonicalize(), dir.canonicalize()) {
501 (Ok(a), Ok(b)) => a == b,
502 _ => resolved.root == dir,
503 };
504 if !same {
505 return Err(io::Error::new(
506 io::ErrorKind::InvalidInput,
507 format!(
508 "{} is inside the git repo {}; sessions here read that repo's \
509 .visdom/tracing.toml, so a workspace binding here would never be used. \
510 Run `{TOP} init --workspace` from the repo root or from a directory \
511 that is not inside a repo.",
512 dir.display(),
513 resolved.root.display()
514 ),
515 ));
516 }
517 }
518
519 let existing = TracevaultConfig::try_load(dir).map_err(|e| {
520 io::Error::new(
521 io::ErrorKind::InvalidData,
522 format!(
523 "cannot read the existing .visdom/tracing.toml ({e}). Fix or remove it, \
524 then run `{TOP} init --workspace` again."
525 ),
526 )
527 })?;
528
529 let (resolved_url, credential) = crate::credentials::resolve_credentials_quiet(dir)
530 .map_err(|e| io::Error::other(e.to_string()))?;
531 if let Some(msg) = credential_url_mismatch(resolved_url.as_deref(), server_url) {
534 return Err(io::Error::new(io::ErrorKind::PermissionDenied, msg));
535 }
536 let url = server_url.map(String::from).or(resolved_url);
537 let (Some(url), Some(_)) = (url.as_deref(), credential.as_ref()) else {
538 return Err(io::Error::new(
539 io::ErrorKind::PermissionDenied,
540 format!(
541 "Not logged in. `init --workspace` resolves the project name on the server, \
542 so nothing was written.\nLog in, then run it again:\n\n \
543 {TOP} login --server-url {}\n \
544 {TOP} init --workspace --project {project_name}",
545 url.as_deref().unwrap_or("<URL>")
546 ),
547 ));
548 };
549 let client = ApiClient::with_credential(url, credential);
550 let project = crate::commands::migrate::resolve_project_by_name(&client, project_name)
551 .await
552 .map_err(|e| io::Error::new(io::ErrorKind::InvalidInput, e.to_string()))?;
553
554 let config_dir = TracevaultConfig::config_dir(dir);
555 fs::create_dir_all(&config_dir)?;
556 TracevaultConfig::ensure_gitignore(&config_dir)?;
557
558 let mut config = existing.unwrap_or_default();
559 if let Some(url) = server_url {
560 config.server_url = Some(url.to_string());
561 }
562 config.project_id = Some(project.id.to_string());
563 config.project_name = Some(project.name.clone());
564 config.default_project = None;
565 config.save(dir)?;
566
567 Ok(WorkspaceInit {
568 project_id: project.id,
569 project_name: project.name,
570 config_path: TracevaultConfig::config_path(dir),
571 })
572}
573
574pub fn not_logged_in_message(url: Option<&str>) -> String {
579 let url = url.unwrap_or("<URL>");
580 format!(
581 "Not logged in. Without a login Visdom cannot register this repo, and its hooks \
582 would record nothing, so nothing was installed.\n\
583 Log in, then run init again:\n\
584 \n {TOP} login --server-url {url}\n {TOP} init\n\n\
585 (In CI, set {ENV}_API_KEY instead of logging in.)"
586 )
587}
588
589pub(crate) fn persist_repo_binding(
596 project_root: &Path,
597 repo_id: uuid::Uuid,
598 codebase: Option<&crate::api_client::ResolveRemoteResponse>,
599) -> bool {
600 let Some(mut cfg) = TracevaultConfig::load(project_root) else {
601 return false;
602 };
603 cfg.repo_id = Some(repo_id.to_string());
604 if let Some(remote) = codebase {
605 cfg.remote_id = Some(remote.remote_id.to_string());
606 cfg.codebase_name = remote.name.clone();
607 }
608 cfg.save(project_root).is_ok()
609}
610
611async fn register_new_repo(
615 client: &ApiClient,
616 project_root: &Path,
617 repo_name: String,
618 origin_url: String,
619) {
620 match client
621 .register_repo(crate::api_client::RegisterRepoRequest {
622 repo_name,
623 github_url: Some(origin_url.clone()),
624 })
625 .await
626 {
627 Ok(resp) => {
628 println!("Repo registered on server (id: {})", resp.repo_id);
629 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
631 cfg.repo_id = Some(resp.repo_id.to_string());
632 if let Ok(Some(remote)) = client.resolve_remote(&origin_url).await {
638 println!(
639 "{}",
640 crate::resolution::codebase_line(
641 remote.name.as_deref(),
642 &remote.normalized_url,
643 &remote.clone_status
644 )
645 );
646 cfg.remote_id = Some(remote.remote_id.to_string());
647 cfg.codebase_name = remote.name.clone();
648 }
649 let _ = cfg.save(project_root);
650 }
651 }
652 Err(e) => {
653 eprintln!("{}", registration_failure_message(e.as_ref()));
654 }
655 }
656}
657
658fn registration_failure_message(err: &dyn std::error::Error) -> String {
673 let msg = err.to_string();
674 if msg.starts_with("Server returned 403 ") {
675 "Warning: you are not authorized to register this repo.".to_string()
676 } else if msg.starts_with("Server returned 404 ") {
677 crate::program::say(
678 "Warning: could not register repo on server (404) — this endpoint may not exist on \
679 this server yet, possibly a CLI/server version mismatch. Run `tracevault sync` again \
680 once the server is upgraded.",
681 )
682 .to_string()
683 } else {
684 format!("Warning: could not register repo on server: {err}")
685 }
686}
687
688fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
689 let path = project_root.join(".gitignore");
690 let existing = if path.exists() {
691 fs::read_to_string(&path)?
692 } else {
693 String::new()
694 };
695
696 let needed: Vec<&str> = [settings_entry]
704 .iter()
705 .copied()
706 .filter(|entry| !entry.is_empty() && !existing.lines().any(|line| line.trim() == *entry))
707 .collect();
708
709 if needed.is_empty() {
710 return Ok(());
711 }
712
713 let mut content = existing;
714 if !content.is_empty() && !content.ends_with('\n') {
715 content.push('\n');
716 }
717 content.push_str("\n# Visdom tracing — local only, do not commit\n");
718 for entry in needed {
719 content.push_str(entry);
720 content.push('\n');
721 }
722
723 fs::write(path, content)
724}
725
726pub const PRE_PUSH_MARKER: &str = "# tracevault:enforce";
728const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
729
730fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
731 let hooks_dir = project_root.join(".git/hooks");
732 fs::create_dir_all(&hooks_dir)?;
733
734 let hook_path = hooks_dir.join("pre-push");
735 let tracevault_block = format!(
742 "{marker}\n\
743 # Capture git's pre-push ref list once; `check` uses it to determine\n\
744 # which files are being pushed.\n\
745 {var}=$(cat)\n\
746 {cli} sync 2>/dev/null || true\n\
747 printf '%s' \"${var}\" | {cli} check || {{ echo \"{TOP}: policy check failed\"; exit 1; }}\n",
748 cli = crate::program::name(crate::program::is_visdom()),
749 marker = marker_to_install(PRE_PUSH_MARKER),
750 var = PREPUSH_VARS[usize::from(crate::program::is_visdom())],
751 );
752
753 if hook_path.exists() {
754 let existing = fs::read_to_string(&hook_path)?;
755
756 if has_marker(&existing, PRE_PUSH_MARKER) {
758 return respell_git_hook(&hook_path, &existing, PRE_PUSH_MARKER);
759 }
760
761 if existing.contains(OLD_HOOK_MARKER) {
763 let mut new_content = String::new();
764 let mut skip = false;
765 for line in existing.lines() {
766 if line.contains(OLD_HOOK_MARKER) {
767 skip = true;
768 continue;
769 }
770 if skip {
771 if line.starts_with("tracevault ") {
773 continue;
774 }
775 skip = false;
776 }
777 new_content.push_str(line);
778 new_content.push('\n');
779 }
780 if !new_content.ends_with('\n') {
781 new_content.push('\n');
782 }
783 new_content.push_str(&tracevault_block);
784 fs::write(&hook_path, new_content)?;
785 } else {
786 let mut content = existing;
788 if !content.ends_with('\n') {
789 content.push('\n');
790 }
791 content.push_str(&tracevault_block);
792 fs::write(&hook_path, content)?;
793 }
794 } else {
795 let content = format!("#!/bin/sh\n{tracevault_block}");
796 fs::write(&hook_path, content)?;
797 }
798
799 #[cfg(unix)]
801 {
802 use std::os::unix::fs::PermissionsExt;
803 let mut perms = fs::metadata(&hook_path)?.permissions();
804 perms.set_mode(0o755);
805 fs::set_permissions(&hook_path, perms)?;
806 }
807
808 Ok(())
809}
810
811pub const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
813
814const GIT_HOOK_SUBCOMMANDS: [&str; 3] = ["sync", "check", "commit-push"];
816
817pub fn marker_for_visdom(marker: &str) -> String {
820 marker.replacen("tracevault:", "visdom:", 1)
821}
822
823fn marker_to_install(marker: &str) -> String {
825 if crate::program::is_visdom() {
826 marker_for_visdom(marker)
827 } else {
828 marker.to_string()
829 }
830}
831
832pub fn has_marker(content: &str, marker: &str) -> bool {
835 content.contains(marker) || content.contains(&marker_for_visdom(marker))
836}
837
838const PREPUSH_VARS: [&str; 2] = ["tracevault_prepush_stdin", "visdom_prepush_stdin"];
841
842fn git_hook_line_for_visdom(line: &str) -> Option<String> {
847 use crate::program::{TRACEVAULT, VISDOM_TRACE};
848 let piped = PREPUSH_VARS
849 .iter()
850 .map(|var| format!("printf '%s' \"${var}\" | "))
851 .find(|piped| line.starts_with(piped.as_str()));
852 let command = &line[piped.as_ref().map_or(0, String::len)..];
853 let rest = [VISDOM_TRACE, TRACEVAULT]
854 .iter()
855 .find_map(|name| command.strip_prefix(name)?.strip_prefix(' '))?;
856 let ours = GIT_HOOK_SUBCOMMANDS.iter().any(|sub| {
857 rest.strip_prefix(sub)
858 .is_some_and(|after| after.starts_with(' ') || after.trim_end().is_empty())
859 });
860 let head = if piped.is_some() {
861 format!("printf '%s' \"${}\" | ", PREPUSH_VARS[1])
862 } else {
863 String::new()
864 };
865 let rest = rest.replace(
866 "echo \"tracevault: policy check failed\"",
867 "echo \"visdom: policy check failed\"",
868 );
869 ours.then(|| format!("{head}{VISDOM_TRACE} {rest}"))
870}
871
872fn git_hook_filler_for_visdom(line: &str) -> Option<String> {
876 if line.starts_with('#') {
877 return Some(line.to_string());
878 }
879 let rest = PREPUSH_VARS
880 .iter()
881 .find_map(|var| line.strip_prefix(var)?.strip_prefix('='))?;
882 Some(format!("{}={rest}", PREPUSH_VARS[1]))
883}
884
885fn git_hook_block_for_visdom(content: &str, marker: &str) -> Option<String> {
893 let visdom_marker = marker_for_visdom(marker);
894 let mut out = String::with_capacity(content.len() + 32);
895 let mut in_block = false;
896 for line in content.split_inclusive('\n') {
897 let text = line.trim_end();
898 if text == marker || text == visdom_marker {
899 in_block = true;
900 out.push_str(&visdom_marker);
901 out.push_str(&line[text.len()..]);
902 continue;
903 }
904 if in_block {
905 match git_hook_line_for_visdom(line).or_else(|| git_hook_filler_for_visdom(line)) {
906 Some(ours) => {
907 out.push_str(&ours);
908 continue;
909 }
910 None => in_block = false,
911 }
912 }
913 out.push_str(line);
914 }
915 (out != content).then_some(out)
916}
917
918fn respell_git_hook(hook_path: &Path, existing: &str, marker: &str) -> Result<(), io::Error> {
921 if !crate::program::is_visdom() {
922 return Ok(());
923 }
924 match git_hook_block_for_visdom(existing, marker) {
925 Some(content) => fs::write(hook_path, content),
926 None => Ok(()),
927 }
928}
929
930fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
931 let hooks_dir = project_root.join(".git/hooks");
932 fs::create_dir_all(&hooks_dir)?;
933
934 let hook_path = hooks_dir.join("post-commit");
935 let tracevault_block = format!(
936 "{}\n{} commit-push 2>/dev/null &\n",
937 marker_to_install(POST_COMMIT_MARKER),
938 crate::program::name(crate::program::is_visdom())
939 );
940
941 if hook_path.exists() {
942 let existing = fs::read_to_string(&hook_path)?;
943
944 if has_marker(&existing, POST_COMMIT_MARKER) {
945 return respell_git_hook(&hook_path, &existing, POST_COMMIT_MARKER);
946 }
947
948 let mut content = existing;
949 if !content.ends_with('\n') {
950 content.push('\n');
951 }
952 content.push_str(&tracevault_block);
953 fs::write(&hook_path, content)?;
954 } else {
955 let content = format!("#!/bin/sh\n{tracevault_block}");
956 fs::write(&hook_path, content)?;
957 }
958
959 #[cfg(unix)]
960 {
961 use std::os::unix::fs::PermissionsExt;
962 let mut perms = fs::metadata(&hook_path)?.permissions();
963 perms.set_mode(0o755);
964 fs::set_permissions(&hook_path, perms)?;
965 }
966
967 Ok(())
968}
969
970fn install_claude_hooks(
971 project_root: &Path,
972 target: ClaudeSettingsTarget,
973) -> Result<(), io::Error> {
974 let claude_dir = project_root.join(".claude");
975 fs::create_dir_all(&claude_dir)?;
976 merge_hooks_into_file(&claude_dir.join(target.filename()), &tracevault_hooks())?;
977 if crate::program::is_visdom() {
980 for other in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
981 if other.filename() != target.filename() {
982 hooks_file_for_visdom(&claude_dir.join(other.filename()))?;
983 }
984 }
985 }
986 Ok(())
987}
988
989fn hooks_file_for_visdom(path: &Path) -> io::Result<()> {
993 if !matches!(has_tracevault_hooks(path), Ok(true)) {
994 return Ok(());
995 }
996 update_json_file(path, "its hooks", |root| {
997 if let Some(hooks) = root.get_mut("hooks") {
998 *hooks = hooks_spelled(hooks, true);
999 }
1000 Ok(())
1001 })
1002}
1003
1004pub fn tracevault_hooks() -> serde_json::Value {
1005 serde_json::json!({
1006 "PreToolUse": [{
1007 "matcher": "Write|Edit|Bash",
1008 "hooks": [{
1009 "type": "command",
1010 "command": "tracevault stream --event pre-tool-use",
1011 "timeout": 10,
1012 "statusMessage": "Visdom: streaming pre-tool event"
1013 }]
1014 }],
1015 "PostToolUse": [{
1016 "matcher": "",
1017 "hooks": [{
1018 "type": "command",
1019 "command": "tracevault stream --event post-tool-use",
1020 "timeout": 10,
1021 "statusMessage": "Visdom: streaming post-tool event"
1022 }]
1023 }],
1024 "Notification": [{
1025 "matcher": "",
1026 "hooks": [{
1027 "type": "command",
1028 "command": "tracevault stream --event notification",
1029 "timeout": 10,
1030 "statusMessage": "Visdom: streaming notification"
1031 }]
1032 }],
1033 "Stop": [{
1034 "matcher": "",
1035 "hooks": [{
1036 "type": "command",
1037 "command": "tracevault stream --event stop",
1038 "timeout": 10,
1039 "statusMessage": "Visdom: finalizing session"
1040 }]
1041 }],
1042 "SessionEnd": [{
1045 "matcher": "",
1046 "hooks": [{
1047 "type": "command",
1048 "command": "tracevault stream --event session-end",
1049 "timeout": 10,
1050 "statusMessage": "Visdom: sending session cost"
1051 }]
1052 }],
1053 "SubagentStop": [{
1056 "matcher": "",
1057 "hooks": [{
1058 "type": "command",
1059 "command": "tracevault stream --event subagent-stop",
1060 "timeout": 10,
1061 "statusMessage": "Visdom: streaming subagent transcript"
1062 }]
1063 }],
1064 "SessionStart": [{
1065 "matcher": "",
1066 "hooks": [{
1067 "type": "command",
1068 "command": "tracevault session-start",
1069 "timeout": 10,
1070 "statusMessage": "Visdom: session start"
1071 }]
1072 }],
1073 "UserPromptSubmit": [{
1074 "matcher": "",
1075 "hooks": [{
1076 "type": "command",
1077 "command": "tracevault user-prompt",
1078 "timeout": 10,
1079 "statusMessage": "Visdom: policy reinforcement"
1080 }]
1081 }]
1082 })
1083}
1084
1085pub fn codex_hook_trust_notice() -> &'static str {
1095 "Codex gates hooks behind hook trust: until it is granted, `codex exec` skips them \
1096 silently and no session is captured. Run `codex` once interactively in a repo and \
1097 approve the hook-trust prompt; unattended runs (CI) can pass \
1098 `--dangerously-bypass-hook-trust` instead."
1099}
1100
1101pub fn codex_hooks() -> serde_json::Value {
1111 serde_json::json!({
1112 "SessionStart": [{
1113 "matcher": "",
1114 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "Visdom: session start" }]
1115 }],
1116 "UserPromptSubmit": [{
1117 "matcher": "",
1118 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "Visdom: policy reinforcement" }]
1119 }],
1120 "PostToolUse": [{
1121 "matcher": "",
1122 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "Visdom: streaming post-tool event" }]
1123 }],
1124 "Stop": [{
1125 "matcher": "",
1126 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "Visdom: finalizing session" }]
1127 }]
1128 })
1129}
1130
1131const GSD_EXT_INDEX_TS: &str = include_str!("../../assets/gsd-extension/index.ts");
1135const GSD_EXT_PACKAGE_JSON: &str = include_str!("../../assets/gsd-extension/package.json");
1136const GSD_EXT_MANIFEST_JSON: &str =
1137 include_str!("../../assets/gsd-extension/extension-manifest.json");
1138
1139fn gsd_extension_source_dir() -> io::Result<PathBuf> {
1143 let config_dir = dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
1144 let config_dir = config_dir
1145 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no config or home dir"))?;
1146 let visdom = crate::layout::user_dir_in(&config_dir).join("gsd-extension");
1147 let earlier = config_dir
1148 .join(crate::layout::LEGACY_USER_DIR)
1149 .join("gsd-extension");
1150 Ok(
1151 if crate::program::installs_visdom(visdom.join("index.ts").exists()) {
1152 visdom
1153 } else {
1154 earlier
1155 },
1156 )
1157}
1158
1159fn earlier_gsd_extension_source_dir(source_dir: &Path) -> Option<PathBuf> {
1164 let earlier = crate::layout::legacy_sibling(source_dir.parent()?)?.join("gsd-extension");
1165 earlier.is_dir().then_some(earlier)
1166}
1167
1168fn gsd_extension_file(source: &str, source_dir: &Path) -> String {
1171 let visdom = source_dir
1172 .parent()
1173 .and_then(Path::file_name)
1174 .is_some_and(|name| name == crate::layout::USER_DIR);
1175 if visdom {
1176 source
1177 .replacen("\"id\": \"tracevault\"", "\"id\": \"visdom\"", 1)
1178 .replacen("\"name\": \"tracevault\"", "\"name\": \"visdom\"", 1)
1179 } else {
1180 source.to_string()
1181 }
1182}
1183
1184pub fn install_gsd_extension(project_root: Option<&Path>) -> io::Result<()> {
1208 let home =
1209 dirs::home_dir().ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no home dir"))?;
1210 let gsd_home = home.join(".gsd");
1211
1212 let source_dir = gsd_extension_source_dir()?;
1213 fs::create_dir_all(&source_dir)?;
1214 write_plugin(&source_dir.join("index.ts"), GSD_EXT_INDEX_TS)?;
1215 fs::write(
1216 source_dir.join("package.json"),
1217 gsd_extension_file(GSD_EXT_PACKAGE_JSON, &source_dir),
1218 )?;
1219 fs::write(
1220 source_dir.join("extension-manifest.json"),
1221 gsd_extension_file(GSD_EXT_MANIFEST_JSON, &source_dir),
1222 )?;
1223
1224 if let Err(e) = cleanup_stale_gsd_registration(&gsd_home) {
1228 eprintln!("Warning: could not clean up the previous GSD extension registration: {e}");
1229 }
1230
1231 let local_flag = project_root.is_some();
1235 let mut cmd = std::process::Command::new("gsd");
1236 cmd.arg("install").arg(&source_dir);
1237 if let Some(root) = project_root {
1238 cmd.arg("-l");
1239 cmd.current_dir(root);
1240 }
1241
1242 let retry_hint = format!(
1243 "gsd install {}{}",
1244 source_dir.display(),
1245 if local_flag { " -l" } else { "" }
1246 );
1247
1248 match cmd.output() {
1249 Ok(output) if output.status.success() => {
1250 println!(
1251 "Visdom: installed and registered the GSD extension ({}).",
1252 source_dir.display()
1253 );
1254 if let Some(earlier) = earlier_gsd_extension_source_dir(&source_dir) {
1261 let mut remove = std::process::Command::new("gsd");
1262 remove.arg("remove").arg(&earlier);
1263 if let Some(root) = project_root {
1264 remove.arg("-l");
1265 remove.current_dir(root);
1266 }
1267 let _ = remove.output();
1268 }
1269 }
1270 Ok(output) => {
1271 eprintln!(
1272 "Visdom: installed the GSD extension source to {}, but `gsd install` failed:\n{}Ensure `gsd` is on PATH and run: `{retry_hint}` to enable capture.",
1273 source_dir.display(),
1274 String::from_utf8_lossy(&output.stderr),
1275 );
1276 }
1277 Err(e) => {
1278 eprintln!(
1279 "Visdom: 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.",
1280 source_dir.display(),
1281 );
1282 }
1283 }
1284
1285 Ok(())
1286}
1287
1288const OPENCODE_PLUGIN_INDEX: &str = include_str!("../../assets/opencode-plugin/index.ts");
1291
1292pub fn install_opencode_plugin(project_root: Option<&Path>) -> io::Result<()> {
1308 let plugins_dir = match project_root {
1309 Some(root) => root.join(".opencode").join("plugins"),
1310 None => {
1311 let config_dir =
1312 dirs::config_dir().or_else(|| dirs::home_dir().map(|h| h.join(".config")));
1313 config_dir
1314 .ok_or_else(|| {
1315 io::Error::new(
1316 io::ErrorKind::NotFound,
1317 "could not determine the config directory for the OpenCode plugin install",
1318 )
1319 })?
1320 .join("opencode")
1321 .join("plugins")
1322 }
1323 };
1324
1325 write_opencode_plugin_files(&plugins_dir)
1326}
1327
1328fn write_opencode_plugin_files(plugins_dir: &Path) -> io::Result<()> {
1329 fs::create_dir_all(plugins_dir)?;
1330 let name = plugin_name(plugins_dir.join("visdom.ts").exists());
1331 write_plugin(
1332 &plugins_dir.join(format!("{name}.ts")),
1333 OPENCODE_PLUGIN_INDEX,
1334 )?;
1335 if name == "visdom" {
1336 match fs::remove_file(plugins_dir.join("tracevault.ts")) {
1338 Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
1339 _ => {}
1340 }
1341 }
1342 Ok(())
1343}
1344
1345fn plugin_name(visdom_one_exists: bool) -> &'static str {
1351 if crate::program::installs_visdom(visdom_one_exists) {
1352 "visdom"
1353 } else {
1354 crate::program::TRACEVAULT
1355 }
1356}
1357
1358const PLUGIN_CLI_LINES: [(&str, &str); 2] = [
1362 (
1363 "const CLI = [\"tracevault\"];",
1364 "const CLI = [\"visdom\", \"trace\"];",
1365 ),
1366 (
1367 "const CLI = ['tracevault']",
1368 "const CLI = ['visdom', 'trace']",
1369 ),
1370];
1371
1372pub fn plugin_source(source: &str, visdom: bool) -> String {
1374 if !visdom {
1375 return source.to_string();
1376 }
1377 PLUGIN_CLI_LINES
1378 .iter()
1379 .fold(source.to_string(), |text, (ours, theirs)| {
1380 text.replacen(ours, theirs, 1)
1381 })
1382 .replace("[tracevault]", "[visdom]")
1384 .replace("(tracevault stream", "(visdom trace stream")
1385}
1386
1387fn plugin_runs_visdom(path: &Path) -> bool {
1389 fs::read_to_string(path).is_ok_and(|text| {
1390 PLUGIN_CLI_LINES
1391 .iter()
1392 .any(|(_, visdom)| text.contains(visdom))
1393 })
1394}
1395
1396fn write_plugin(path: &Path, source: &str) -> io::Result<()> {
1399 let visdom = crate::program::installs_visdom(plugin_runs_visdom(path));
1400 fs::write(path, plugin_source(source, visdom))
1401}
1402
1403pub const AMP_PLUGIN_INDEX: &str = include_str!("../../assets/amp-plugin/index.ts");
1406
1407fn amp_plugin_gitignore_entry(project_root: &Path) -> String {
1410 let plugins_dir = project_root.join(".amp").join("plugins");
1411 let name = plugin_name(plugins_dir.join("visdom").join("index.ts").exists());
1412 format!(".amp/plugins/{name}/")
1413}
1414
1415pub fn install_amp_plugin(project_root: Option<&Path>) -> io::Result<PathBuf> {
1424 let plugins_dir = match project_root {
1425 Some(root) => root.join(".amp").join("plugins"),
1426 None => amp_user_config_dir()
1427 .ok_or_else(|| {
1428 io::Error::new(
1429 io::ErrorKind::NotFound,
1430 "could not determine the config directory for the Amp plugin install",
1431 )
1432 })?
1433 .join("plugins"),
1434 };
1435 let name = plugin_name(plugins_dir.join("visdom").join("index.ts").exists());
1436 let plugin_dir = plugins_dir.join(name);
1437 fs::create_dir_all(&plugin_dir)?;
1438 let path = plugin_dir.join("index.ts");
1439 write_plugin(&path, AMP_PLUGIN_INDEX)?;
1440 if name == "visdom" {
1441 let earlier = plugins_dir.join(crate::program::TRACEVAULT);
1443 match fs::remove_file(earlier.join("index.ts")) {
1444 Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
1445 _ => {}
1446 }
1447 let _ = fs::remove_dir(&earlier);
1449 }
1450 Ok(path)
1451}
1452
1453fn amp_user_config_dir() -> Option<PathBuf> {
1457 let xdg = std::env::var_os("XDG_CONFIG_HOME")
1458 .map(PathBuf::from)
1459 .filter(|p| p.is_absolute());
1460 xdg.or_else(|| dirs::home_dir().map(|h| h.join(".config")))
1461 .map(|c| c.join("amp"))
1462}
1463
1464pub fn amp_headless_notice() -> &'static str {
1469 "Amp loads the plugin in interactive sessions. For headless runs use \
1470`amp -x \"<prompt>\" --plugin-ready-timeout 30`, so Amp waits for the plugin before the turn \
1471starts. A headless run waits forever on an approval dialog (for example a file under a guarded \
1472path), so allow what it needs up front.\n\
1473The plugin injects the repo's agent policies into each thread. Amp hides them in its UI but, \
1474unlike Claude Code, stores them in the thread with your message: whoever opens the thread on \
1475ampcode.com, or exports it, can read them."
1476}
1477
1478pub fn cleanup_stale_gsd_registration(gsd_home: &Path) -> io::Result<()> {
1490 let ext_root = gsd_home.join("extensions");
1491 let reg_path = ext_root.join("registry.json");
1492
1493 let reg: Option<serde_json::Value> = if reg_path.exists() {
1498 let content = fs::read_to_string(®_path)?;
1499 let parsed: serde_json::Value = match serde_json::from_str(&content) {
1500 Ok(v) => v,
1501 Err(_) => return Ok(()), };
1503 let corrupt = match parsed.as_object() {
1504 None => true,
1505 Some(obj) => matches!(obj.get("entries"), Some(v) if !v.is_object()),
1506 };
1507 if corrupt {
1508 return Ok(()); }
1510 Some(parsed)
1511 } else {
1512 None
1513 };
1514
1515 let stale = ext_root.join("tracevault-tracker");
1517 if stale.exists() {
1518 fs::remove_dir_all(&stale)?;
1519 }
1520
1521 if let Some(mut reg) = reg {
1523 if let Some(entries) = reg.get_mut("entries").and_then(|e| e.as_object_mut()) {
1524 let removed_tracker = entries.remove("tracevault-tracker").is_some();
1525 let removed_inert = entries.remove("tracevault").is_some();
1526 if removed_tracker || removed_inert {
1527 let tmp = reg_path.with_extension("json.tmp");
1529 fs::write(&tmp, serde_json::to_string_pretty(®)?)?;
1530 fs::rename(&tmp, ®_path)?;
1531 }
1532 }
1533 }
1534 Ok(())
1535}
1536
1537fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
1547 update_json_file(hooks_path, "its hooks", |root| {
1548 merge_hooks(root, ours, hooks_path)
1549 })
1550}
1551
1552pub(crate) fn update_json_file(
1560 path: &Path,
1561 what: &str,
1562 mut mutate: impl FnMut(&mut serde_json::Value) -> io::Result<()>,
1563) -> io::Result<()> {
1564 if path
1569 .components()
1570 .any(|c| c == std::path::Component::ParentDir)
1571 {
1572 return Err(io::Error::new(
1573 io::ErrorKind::InvalidInput,
1574 format!("refusing to use path with '..': {}", path.display()),
1575 ));
1576 }
1577 let target = match fs::symlink_metadata(path) {
1581 Ok(meta) if meta.file_type().is_symlink() => fs::canonicalize(path)?,
1582 _ => path.to_path_buf(),
1583 };
1584 for _ in 0..3 {
1590 let existing = read_existing(&target)?;
1591 let mut root: serde_json::Value = match &existing {
1592 Some((_, content)) => serde_json::from_str(content).map_err(|e| {
1593 io::Error::new(
1594 io::ErrorKind::InvalidData,
1595 format!("Failed to parse {}: {e}", path.display()),
1596 )
1597 })?,
1598 None => serde_json::json!({}),
1599 };
1600
1601 let before = existing.is_some().then(|| root.to_string());
1602 mutate(&mut root)?;
1603 if before.as_deref() == Some(root.to_string().as_str())
1604 || (existing.is_none() && root == serde_json::json!({}))
1605 {
1606 return Ok(());
1607 }
1608
1609 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
1610 io::Error::other(format!("Failed to serialize {}: {e}", path.display()))
1611 })?;
1612 let tmp = unique_temp_sibling(&target);
1613 let published = write_owner_only(&tmp, formatted.as_bytes())
1614 .and_then(|()| {
1615 match &existing {
1618 Some((permissions, _)) => fs::set_permissions(&tmp, permissions.clone()),
1619 None => Ok(()),
1620 }
1621 })
1622 .and_then(|()| {
1623 let unchanged = read_existing(&target)?.map(|(_, c)| c)
1624 == existing.as_ref().map(|(_, c)| c.clone());
1625 if unchanged {
1626 fs::rename(&tmp, &target).map(|()| true)
1627 } else {
1628 Ok(false)
1629 }
1630 });
1631 match published {
1632 Ok(true) => return Ok(()),
1633 Ok(false) => {
1634 let _ = fs::remove_file(&tmp);
1635 }
1636 Err(e) => {
1637 let _ = fs::remove_file(&tmp);
1638 return Err(e);
1639 }
1640 }
1641 }
1642 Err(io::Error::other(format!(
1643 "{} kept changing while Visdom updated {what}; re-run `{TOP} init`",
1644 path.display()
1645 )))
1646}
1647
1648fn read_existing(path: &Path) -> io::Result<Option<(fs::Permissions, String)>> {
1650 let permissions = match fs::metadata(path) {
1651 Ok(meta) => meta.permissions(),
1652 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
1653 Err(e) => return Err(e),
1654 };
1655 Ok(Some((permissions, fs::read_to_string(path)?)))
1656}
1657
1658fn unique_temp_sibling(target: &Path) -> PathBuf {
1662 static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1663 let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1664 let nanos = std::time::SystemTime::now()
1665 .duration_since(std::time::UNIX_EPOCH)
1666 .map(|d| d.subsec_nanos())
1667 .unwrap_or_default();
1668 let mut name = target.file_name().unwrap_or_default().to_os_string();
1669 name.push(format!(".{}.{n}.{nanos}.tmp", std::process::id()));
1670 target.with_file_name(name)
1671}
1672
1673fn write_owner_only(path: &Path, contents: &[u8]) -> io::Result<()> {
1677 let mut options = fs::OpenOptions::new();
1678 options.write(true).create_new(true);
1679 #[cfg(unix)]
1680 {
1681 use std::os::unix::fs::OpenOptionsExt;
1682 options.mode(0o600);
1683 }
1684 options.open(path)?.write_all(contents)
1685}
1686
1687pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
1691 let codex_dir = project_root.join(".codex");
1692 fs::create_dir_all(&codex_dir)?;
1693 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
1694}
1695
1696pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
1703 fs::create_dir_all(codex_dir)?;
1704 let base = codex_dir.canonicalize()?;
1706 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
1707 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
1708}
1709
1710const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
1714
1715const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
1716<!-- tracevault:workspace-mode -->
1717## Visdom (workspace mode)
1718A session started in a registered repo's checkout is bound to that repo automatically. To work
1719on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1720policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1721one-off. Repos must already be registered with Visdom. In a directory bound to a project
1722with `tracevault init --workspace`, sessions are recorded to that project without it, so
1723`repo switch` there is optional: it only adds the repo and its policies.
1724";
1725
1726const PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS: &[&str] = &[
1730 "\
1731<!-- tracevault:workspace-mode -->
1732## TraceVault (workspace mode)
1733You may be running detached from any single repository. Before working on a repo, run
1734`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
1735output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
1736already be registered with TraceVault.
1737",
1738 "\
1739<!-- tracevault:workspace-mode -->
1740## TraceVault (workspace mode)
1741A session started in a registered repo's checkout is bound to that repo automatically. To work
1742on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1743policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1744one-off. Repos must already be registered with TraceVault.
1745",
1746 "\
1748<!-- tracevault:workspace-mode -->
1749## TraceVault (workspace mode)
1750A session started in a registered repo's checkout is bound to that repo automatically. To work
1751on a different repo, run `tracevault repo switch <path>` to bind tracing and fetch that repo's
1752policies; treat its output as binding. Use `--path <path>` on `tracevault repo status` for a
1753one-off. Repos must already be registered with TraceVault. In a directory bound to a project
1754with `tracevault init --workspace`, sessions are recorded to that project without it, so
1755`repo switch` there is optional: it only adds the repo and its policies.
1756",
1757];
1758
1759fn workspace_block(block: &str, visdom: bool) -> String {
1766 if visdom {
1767 block.replace("`tracevault ", "`visdom trace ").replace(
1768 GLOBAL_CLAUDE_MD_MARKER,
1769 &marker_for_visdom(GLOBAL_CLAUDE_MD_MARKER),
1770 )
1771 } else {
1772 block.to_string()
1773 }
1774}
1775
1776fn visdom_workspace_blocks(block: &str) -> [String; 2] {
1780 [
1781 workspace_block(block, true),
1782 block.replace("`tracevault ", "`visdom trace "),
1783 ]
1784}
1785
1786fn replace_managed_block(content: &str) -> String {
1787 let known = || std::iter::once(&GLOBAL_CLAUDE_MD_BLOCK).chain(PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS);
1788 let visdom = crate::program::installs_visdom(
1791 known()
1792 .flat_map(|block| visdom_workspace_blocks(block))
1793 .any(|block| content.contains(&block)),
1794 );
1795 let current = workspace_block(GLOBAL_CLAUDE_MD_BLOCK, visdom);
1796 if content.contains(¤t) {
1797 return content.to_string();
1798 }
1799 known()
1800 .flat_map(|old| {
1801 let [marked, unmarked] = visdom_workspace_blocks(old);
1802 [old.to_string(), marked, unmarked]
1803 })
1804 .find(|old| content.contains(old))
1805 .map_or_else(
1806 || content.to_string(),
1807 |old| content.replacen(&old, ¤t, 1),
1808 )
1809}
1810
1811fn append_workspace_md(md_path: &Path) -> io::Result<()> {
1818 if md_path
1820 .components()
1821 .any(|c| c == std::path::Component::ParentDir)
1822 {
1823 return Err(io::Error::new(
1824 io::ErrorKind::InvalidInput,
1825 format!("refusing to use path with '..': {}", md_path.display()),
1826 ));
1827 }
1828 let existing = if md_path.exists() {
1829 fs::read_to_string(md_path)?
1830 } else {
1831 String::new()
1832 };
1833 if has_marker(&existing, GLOBAL_CLAUDE_MD_MARKER) {
1834 let replaced = replace_managed_block(&existing);
1837 if replaced != existing {
1838 fs::write(md_path, replaced)?;
1839 }
1840 return Ok(());
1841 }
1842 let mut content = existing;
1843 if !content.is_empty() && !content.ends_with('\n') {
1844 content.push('\n');
1845 }
1846 if !content.is_empty() {
1847 content.push('\n');
1848 }
1849 content.push_str(&workspace_block(
1850 GLOBAL_CLAUDE_MD_BLOCK,
1851 crate::program::is_visdom(),
1852 ));
1853 fs::write(md_path, content)
1854}
1855
1856pub(crate) fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
1860 let joined = base.join(name);
1861 if joined.parent() != Some(base) {
1862 return Err(io::Error::new(
1863 io::ErrorKind::InvalidInput,
1864 format!(
1865 "refusing to access path outside {}: {}",
1866 base.display(),
1867 joined.display()
1868 ),
1869 ));
1870 }
1871 Ok(joined)
1872}
1873
1874const HOOK_SUBCOMMANDS: [&str; 3] = ["stream", "session-start", "user-prompt"];
1882
1883fn is_tracevault_hook(hook: &serde_json::Value) -> bool {
1888 hook_command(hook)
1889 .and_then(crate::program::subcommand)
1890 .is_some_and(|rest| {
1891 HOOK_SUBCOMMANDS.iter().any(|sub| {
1892 rest.strip_prefix(sub)
1893 .is_some_and(|after| after.is_empty() || after.starts_with(' '))
1894 })
1895 })
1896}
1897
1898fn hook_command(hook: &serde_json::Value) -> Option<&str> {
1899 hook.get("command").and_then(|c| c.as_str())
1900}
1901
1902fn hooks_in(hooks: &serde_json::Value) -> impl Iterator<Item = &serde_json::Value> {
1904 hooks
1905 .as_object()
1906 .into_iter()
1907 .flat_map(|events| events.values())
1908 .filter_map(|groups| groups.as_array())
1909 .flatten()
1910 .filter_map(|group| group.get("hooks").and_then(|h| h.as_array()))
1911 .flatten()
1912}
1913
1914fn hooks_spelled(ours: &serde_json::Value, visdom: bool) -> serde_json::Value {
1917 let mut ours = ours.clone();
1918 let groups = ours
1919 .as_object_mut()
1920 .into_iter()
1921 .flat_map(|events| events.values_mut())
1922 .filter_map(|groups| groups.as_array_mut())
1923 .flatten();
1924 for group in groups {
1925 let hooks = group.get_mut("hooks").and_then(|h| h.as_array_mut());
1926 for hook in hooks.into_iter().flatten() {
1927 if !is_tracevault_hook(hook) {
1928 continue;
1929 }
1930 if let Some(command) = hook_command(hook).map(|c| crate::program::spelled(c, visdom)) {
1931 hook["command"] = command.into();
1932 }
1933 }
1934 }
1935 ours
1936}
1937
1938fn strip_tracevault_hooks(entries: &mut Vec<serde_json::Value>) -> Option<usize> {
1945 let mut slot = None;
1946 let mut kept = Vec::with_capacity(entries.len());
1947 for mut entry in entries.drain(..) {
1948 if let Some(inner) = entry.get_mut("hooks").and_then(|h| h.as_array_mut()) {
1949 let before = inner.len();
1950 inner.retain(|hook| !is_tracevault_hook(hook));
1951 if inner.is_empty() && before > 0 {
1952 slot.get_or_insert(kept.len());
1953 continue;
1954 }
1955 }
1956 kept.push(entry);
1957 }
1958 *entries = kept;
1959 slot
1960}
1961
1962fn merge_hooks(
1976 settings: &mut serde_json::Value,
1977 ours: &serde_json::Value,
1978 path: &Path,
1979) -> io::Result<()> {
1980 let settings_obj = settings.as_object_mut().ok_or_else(|| {
1981 io::Error::new(
1982 io::ErrorKind::InvalidData,
1983 format!("{} is not a JSON object", path.display()),
1984 )
1985 })?;
1986
1987 let hooks_value = settings_obj
1988 .entry("hooks")
1989 .or_insert_with(|| serde_json::json!({}));
1990 if !hooks_value.is_object() {
1991 return Err(io::Error::new(
1992 io::ErrorKind::InvalidData,
1993 format!("{} \"hooks\" key is not a JSON object", path.display()),
1994 ));
1995 }
1996
1997 let already_visdom = hooks_in(hooks_value)
2000 .filter(|hook| is_tracevault_hook(hook))
2001 .filter_map(hook_command)
2002 .any(crate::program::is_visdom_command);
2003 let ours = hooks_spelled(ours, crate::program::installs_visdom(already_visdom));
2004 let hooks_obj = hooks_value.as_object_mut().expect("checked above");
2005 let empty = serde_json::Map::new();
2006 let ours_obj = ours.as_object().unwrap_or(&empty);
2007
2008 for event in ours_obj.keys() {
2010 if hooks_obj.get(event).is_some_and(|v| !v.is_array()) {
2011 return Err(io::Error::new(
2012 io::ErrorKind::InvalidData,
2013 format!(
2014 "{} \"hooks\".\"{event}\" is not a JSON array",
2015 path.display()
2016 ),
2017 ));
2018 }
2019 }
2020
2021 let mut emptied = Vec::new();
2022 for (event, value) in hooks_obj.iter_mut() {
2023 let Some(existing) = value.as_array_mut() else {
2024 continue;
2025 };
2026 let had_entries = !existing.is_empty();
2027 let slot = strip_tracevault_hooks(existing);
2028 let our_entries = ours_obj.get(event).and_then(|v| v.as_array());
2029 match our_entries {
2030 Some(our_entries) => {
2031 let at = slot.unwrap_or(existing.len());
2032 existing.splice(at..at, our_entries.iter().cloned());
2033 }
2034 None if had_entries && existing.is_empty() => emptied.push(event.clone()),
2035 None => {}
2036 }
2037 }
2038 hooks_obj.retain(|event, _| !emptied.contains(event));
2040
2041 for (event, our_array) in ours_obj {
2042 if !hooks_obj.contains_key(event) {
2043 hooks_obj.insert(event.clone(), our_array.clone());
2044 }
2045 }
2046
2047 Ok(())
2048}
2049
2050pub fn has_tracevault_hooks(path: &Path) -> io::Result<bool> {
2055 let text = match fs::read_to_string(path) {
2056 Ok(text) => text,
2057 Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(false),
2058 Err(e) => return Err(e),
2059 };
2060 let settings: serde_json::Value =
2061 serde_json::from_str(&text).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
2062 Ok(settings
2063 .get("hooks")
2064 .is_some_and(|hooks| hooks_in(hooks).any(is_tracevault_hook)))
2065}
2066
2067pub(crate) fn refresh_claude_hooks(path: &Path) -> io::Result<()> {
2071 merge_hooks_into_file(path, &tracevault_hooks())
2072}
2073
2074pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
2080 fs::create_dir_all(claude_dir)?;
2081
2082 let base = claude_dir.canonicalize()?;
2085
2086 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
2088
2089 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
2091}
2092
2093pub fn write_global_user_config_in(
2103 config_root: &Path,
2104 requested: Option<UserContext>,
2105) -> io::Result<Option<PathBuf>> {
2106 fs::create_dir_all(config_root)?;
2107 let mut config = crate::config::try_load_user_config_in(config_root)
2109 .ok()
2110 .flatten()
2111 .unwrap_or_default();
2112 let user_context = requested
2114 .or_else(|| config.user_context.clone())
2115 .unwrap_or(UserContext::Toggle(true));
2116 let active = user_context
2117 .resolve()
2118 .map(|_| user_context.path_in(config_root));
2119 config.user_context = Some(user_context);
2120 fs::write(user_config_path_in(config_root), config.to_toml())?;
2121 if let Some(ref ctx_path) = active {
2122 if !ctx_path.exists() {
2123 Context::default().save_to(ctx_path)?;
2124 }
2125 }
2126 Ok(active)
2127}
2128
2129#[cfg(test)]
2130mod tests {
2131 use super::*;
2132 use std::io::{BufRead, BufReader, Write};
2133 use std::net::TcpListener;
2134 use std::thread;
2135
2136 #[test]
2142 fn codex_hook_trust_notice_explains_how_to_grant_trust() {
2143 let notice = codex_hook_trust_notice();
2144 assert!(
2145 notice.contains("hook trust"),
2146 "notice must name what is missing: {notice}"
2147 );
2148 assert!(
2149 notice.contains("codex") && notice.contains("approve"),
2150 "notice must tell the user to run codex and approve the prompt: {notice}"
2151 );
2152 assert!(
2153 notice.contains("--dangerously-bypass-hook-trust"),
2154 "notice must name the flag for unattended/CI runs: {notice}"
2155 );
2156 assert!(
2157 notice.contains("silently"),
2158 "notice must say the failure is silent, which is why it needs saying: {notice}"
2159 );
2160 }
2161
2162 fn spawn_once(response: String) -> String {
2165 let response: &'static str = Box::leak(response.into_boxed_str());
2166 let listener = TcpListener::bind("127.0.0.1:0").unwrap();
2167 let addr = listener.local_addr().unwrap();
2168 thread::spawn(move || {
2169 if let Ok((stream, _)) = listener.accept() {
2170 let mut reader = BufReader::new(stream);
2171 let mut request_line = String::new();
2172 let _ = reader.read_line(&mut request_line);
2173 let mut stream = reader.into_inner();
2174 let _ = stream.write_all(response.as_bytes());
2175 let _ = stream.flush();
2176 }
2177 });
2178 format!("http://{addr}")
2179 }
2180
2181 fn http_response(status: &str, body: &str) -> String {
2184 format!(
2185 "HTTP/1.1 {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
2186 status,
2187 body.len(),
2188 body
2189 )
2190 }
2191
2192 fn add_origin_remote(dir: &Path, url: &str) {
2193 let ok = std::process::Command::new("git")
2194 .args(["-C", &dir.to_string_lossy(), "remote", "add", "origin", url])
2195 .status()
2196 .expect("git remote add failed")
2197 .success();
2198 assert!(ok, "git remote add must succeed");
2199 }
2200
2201 #[test]
2202 fn linked_worktree_primary_detects_linked_and_primary() {
2203 let tmp = tempfile::tempdir().unwrap();
2204 let repo = tmp.path().join("repo");
2205 let wt = tmp.path().join("linked-wt");
2206 std::fs::create_dir_all(&repo).unwrap();
2207 crate::test_helpers::init_git_repo(&repo);
2208 crate::test_helpers::add_worktree(&repo, &wt);
2209
2210 assert!(
2212 linked_worktree_primary(&repo).is_none(),
2213 "primary checkout must not be flagged as a linked worktree"
2214 );
2215 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
2217 assert_eq!(
2218 primary.canonicalize().unwrap(),
2219 repo.canonicalize().unwrap(),
2220 "must resolve to the primary repo root"
2221 );
2222 }
2223
2224 #[test]
2225 fn linked_worktree_primary_none_for_non_git() {
2226 let tmp = tempfile::tempdir().unwrap();
2227 assert!(
2228 linked_worktree_primary(tmp.path()).is_none(),
2229 "a non-git directory is not a linked worktree"
2230 );
2231 }
2232
2233 fn entry_command(entry: &serde_json::Value) -> Option<&str> {
2235 entry.get("hooks")?.get(0)?.get("command")?.as_str()
2236 }
2237
2238 #[test]
2239 fn merge_hooks_into_empty_settings_adds_all_our_events() {
2240 let mut settings = serde_json::json!({});
2241 let ours = tracevault_hooks();
2242 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
2243
2244 let hooks = settings.get("hooks").unwrap();
2245 for event in [
2246 "PreToolUse",
2247 "PostToolUse",
2248 "Notification",
2249 "Stop",
2250 "SessionEnd",
2251 "SubagentStop",
2252 "SessionStart",
2253 "UserPromptSubmit",
2254 ] {
2255 assert!(hooks.get(event).is_some(), "missing event {event}");
2256 }
2257 }
2258
2259 #[test]
2260 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
2261 let mut settings = serde_json::json!({
2262 "model": "opus",
2263 "hooks": {
2264 "PreToolUse": [{
2265 "matcher": "",
2266 "hooks": [{ "type": "command", "command": "my-own-hook" }]
2267 }]
2268 }
2269 });
2270 let ours = tracevault_hooks();
2271 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
2272
2273 assert_eq!(settings.get("model").unwrap(), "opus");
2275
2276 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
2277 assert_eq!(pre_tool_use.len(), 2);
2279 let commands: Vec<&str> = pre_tool_use
2280 .iter()
2281 .map(|e| entry_command(e).unwrap())
2282 .collect();
2283 assert!(commands.contains(&"my-own-hook"));
2284 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
2285
2286 assert!(settings["hooks"]["SessionStart"].is_array());
2288 }
2289
2290 #[test]
2291 fn merge_hooks_is_idempotent() {
2292 let mut settings = serde_json::json!({});
2293 let ours = tracevault_hooks();
2294 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
2295 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
2296
2297 for event in [
2298 "PreToolUse",
2299 "PostToolUse",
2300 "Notification",
2301 "Stop",
2302 "SessionEnd",
2303 "SubagentStop",
2304 "SessionStart",
2305 "UserPromptSubmit",
2306 ] {
2307 let arr = settings["hooks"][event].as_array().unwrap();
2308 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
2309 }
2310 }
2311
2312 #[test]
2313 fn merge_hooks_keeps_foreign_hook_sharing_a_group_with_ours() {
2314 let mut settings = serde_json::json!({
2318 "hooks": {
2319 "PreToolUse": [{
2320 "matcher": "Write|Edit|Bash",
2321 "hooks": [
2322 { "type": "command", "command": "other", "timeout": 3 },
2323 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
2324 ]
2325 }]
2326 }
2327 });
2328 merge_hooks(
2329 &mut settings,
2330 &tracevault_hooks(),
2331 Path::new("settings.json"),
2332 )
2333 .unwrap();
2334
2335 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
2336 assert_eq!(
2337 pre_tool_use[0],
2338 serde_json::json!({
2339 "matcher": "Write|Edit|Bash",
2340 "hooks": [{ "type": "command", "command": "other", "timeout": 3 }]
2341 })
2342 );
2343 assert_eq!(
2344 &pre_tool_use[1..],
2345 tracevault_hooks()["PreToolUse"].as_array().unwrap()
2346 );
2347 }
2348
2349 fn stale_tracevault_hooks() -> serde_json::Value {
2352 let entry = |matcher: &str, event: &str| {
2353 serde_json::json!([{
2354 "matcher": matcher,
2355 "hooks": [{ "type": "command", "command": format!("tracevault stream --event {event}"), "timeout": 5 }]
2356 }])
2357 };
2358 serde_json::json!({
2359 "PreToolUse": entry("Write|Edit", "pre-tool-use"),
2360 "PostToolUse": entry("", "post-tool-use"),
2361 "Notification": entry("", "notification"),
2362 "Stop": entry("", "stop"),
2363 })
2364 }
2365
2366 #[test]
2367 fn merge_hooks_upgrades_stale_tracevault_entries() {
2368 let mut settings = serde_json::json!({ "hooks": stale_tracevault_hooks() });
2369 merge_hooks(
2370 &mut settings,
2371 &tracevault_hooks(),
2372 Path::new("settings.json"),
2373 )
2374 .unwrap();
2375 assert_eq!(settings["hooks"], tracevault_hooks());
2376 }
2377
2378 #[test]
2379 fn merge_hooks_removes_our_entries_from_events_we_no_longer_install() {
2380 let mut settings = serde_json::json!({
2383 "hooks": {
2384 "PreToolUse": [{ "matcher": "", "hooks": [{ "type": "command", "command": "tracevault stream --event pre-tool-use --agent codex" }] }],
2385 "SubagentStop": [{ "matcher": "", "hooks": [{ "type": "command", "command": "notify-me" }] }],
2386 "Custom": "left alone"
2387 }
2388 });
2389 merge_hooks(&mut settings, &codex_hooks(), Path::new("hooks.json")).unwrap();
2390
2391 let hooks = settings["hooks"].as_object().unwrap();
2392 assert!(!hooks.contains_key("PreToolUse"), "retired event must go");
2393 assert_eq!(hooks["SubagentStop"][0]["hooks"][0]["command"], "notify-me");
2394 assert_eq!(hooks["Custom"], "left alone");
2395 for (event, entries) in codex_hooks().as_object().unwrap() {
2396 assert_eq!(&hooks[event], entries, "{event}");
2397 }
2398 }
2399
2400 #[test]
2401 fn merge_hooks_rerun_keeps_our_entry_in_place() {
2402 let mut settings = serde_json::json!({ "hooks": tracevault_hooks() });
2405 settings["hooks"]["Stop"]
2406 .as_array_mut()
2407 .unwrap()
2408 .push(serde_json::json!({ "matcher": "", "hooks": [{ "type": "command", "command": "say done" }] }));
2409 let before = settings.clone();
2410 merge_hooks(
2411 &mut settings,
2412 &tracevault_hooks(),
2413 Path::new("settings.json"),
2414 )
2415 .unwrap();
2416 assert_eq!(settings.to_string(), before.to_string());
2417 }
2418
2419 #[test]
2420 fn merge_hooks_does_not_claim_commands_merely_mentioning_tracevault() {
2421 let foreign = serde_json::json!({
2422 "matcher": "",
2423 "hooks": [
2424 { "type": "command", "command": "tracevault-wrapper stream" },
2425 { "type": "command", "command": "echo tracevault stream" },
2426 { "type": "command", "command": " tracevault check" }
2427 ]
2428 });
2429 let mut settings = serde_json::json!({ "hooks": { "Stop": [foreign.clone()] } });
2430 merge_hooks(
2431 &mut settings,
2432 &tracevault_hooks(),
2433 Path::new("settings.json"),
2434 )
2435 .unwrap();
2436 assert_eq!(settings["hooks"]["Stop"][0], foreign);
2437 assert_eq!(settings["hooks"]["Stop"].as_array().unwrap().len(), 2);
2438 }
2439
2440 #[test]
2441 fn merge_hooks_errors_on_non_object_top_level() {
2442 let mut settings = serde_json::json!([1, 2, 3]);
2443 let ours = tracevault_hooks();
2444 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2445 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2446 assert!(err.to_string().contains("settings.json"));
2447 }
2448
2449 #[test]
2450 fn merge_hooks_errors_on_non_object_top_level_number() {
2451 let mut settings = serde_json::json!(42);
2452 let ours = tracevault_hooks();
2453 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2454 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2455 }
2456
2457 #[test]
2458 fn merge_hooks_errors_on_non_object_hooks() {
2459 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
2460 let ours = tracevault_hooks();
2461 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2462 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2463 assert!(err.to_string().contains("hooks"));
2464 }
2465
2466 #[test]
2467 fn merge_hooks_errors_on_non_array_event_value() {
2468 let mut settings = serde_json::json!({
2469 "hooks": {
2470 "PreToolUse": "not-an-array"
2471 }
2472 });
2473 let ours = tracevault_hooks();
2474 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
2475 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2476 assert!(err.to_string().contains("PreToolUse"));
2477 }
2478
2479 #[test]
2480 fn install_global_hooks_writes_settings_and_claude_md() {
2481 let tmp = tempfile::tempdir().unwrap();
2482 let claude_dir = tmp.path().join(".claude");
2483
2484 install_global_hooks(&claude_dir).unwrap();
2485
2486 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2487 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2488 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
2489 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
2490 }
2491
2492 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2493 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2494 }
2495
2496 #[test]
2497 fn install_global_hooks_is_idempotent() {
2498 let tmp = tempfile::tempdir().unwrap();
2499 let claude_dir = tmp.path().join(".claude");
2500
2501 install_global_hooks(&claude_dir).unwrap();
2502 install_global_hooks(&claude_dir).unwrap();
2503
2504 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2505 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2506 for event in [
2507 "PreToolUse",
2508 "PostToolUse",
2509 "Notification",
2510 "Stop",
2511 "SessionEnd",
2512 "SubagentStop",
2513 "SessionStart",
2514 "UserPromptSubmit",
2515 ] {
2516 let arr = settings["hooks"][event].as_array().unwrap();
2517 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
2518 }
2519
2520 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2521 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
2522 assert_eq!(
2523 marker_count, 1,
2524 "CLAUDE.md marker should appear exactly once"
2525 );
2526 }
2527
2528 #[test]
2529 fn install_global_hooks_preserves_existing_claude_md_content() {
2530 let tmp = tempfile::tempdir().unwrap();
2531 let claude_dir = tmp.path().join(".claude");
2532 fs::create_dir_all(&claude_dir).unwrap();
2533 fs::write(
2534 claude_dir.join("CLAUDE.md"),
2535 "# My existing notes\nSome content.\n",
2536 )
2537 .unwrap();
2538
2539 install_global_hooks(&claude_dir).unwrap();
2540
2541 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
2542 assert!(claude_md.contains("# My existing notes"));
2543 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
2544 }
2545
2546 #[test]
2547 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
2548 let tmp = tempfile::tempdir().unwrap();
2549 let claude_dir = tmp.path().join(".claude");
2550
2551 install_global_hooks(&claude_dir).unwrap();
2552
2553 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
2554 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
2555 assert!(settings["hooks"].get("SessionStart").is_some());
2556
2557 let leftover = fs::read_dir(&claude_dir)
2558 .unwrap()
2559 .filter_map(|e| e.ok())
2560 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2561 assert!(
2562 !leftover,
2563 "no settings.json.tmp should remain after install"
2564 );
2565 }
2566
2567 #[test]
2568 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
2569 let tmp = tempfile::tempdir().unwrap();
2570 let claude_dir = tmp.path().join(".claude");
2571 fs::create_dir_all(&claude_dir).unwrap();
2572 let settings_path = claude_dir.join("settings.json");
2573 let original = "[1, 2, 3]";
2574 fs::write(&settings_path, original).unwrap();
2575
2576 let err = install_global_hooks(&claude_dir).unwrap_err();
2577 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2578
2579 let after = fs::read_to_string(&settings_path).unwrap();
2582 assert_eq!(after, original);
2583 let leftover = fs::read_dir(&claude_dir)
2584 .unwrap()
2585 .filter_map(|e| e.ok())
2586 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2587 assert!(!leftover, "no tmp file should be left behind on error");
2588 }
2589
2590 #[test]
2591 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
2592 let tmp = tempfile::tempdir().unwrap();
2593 let claude_dir = tmp.path().join(".claude");
2594 fs::create_dir_all(&claude_dir).unwrap();
2595 let settings_path = claude_dir.join("settings.json");
2596 let original = r#"{"hooks": "oops"}"#;
2597 fs::write(&settings_path, original).unwrap();
2598
2599 let err = install_global_hooks(&claude_dir).unwrap_err();
2600 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2601
2602 let after = fs::read_to_string(&settings_path).unwrap();
2603 assert_eq!(after, original);
2604 }
2605
2606 #[test]
2607 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
2608 let tmp = tempfile::tempdir().unwrap();
2609 let claude_dir = tmp.path().join(".claude");
2610 fs::create_dir_all(&claude_dir).unwrap();
2611 let settings_path = claude_dir.join("settings.json");
2612 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
2613 fs::write(&settings_path, original).unwrap();
2614
2615 let err = install_global_hooks(&claude_dir).unwrap_err();
2616 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
2617
2618 let after = fs::read_to_string(&settings_path).unwrap();
2619 assert_eq!(after, original);
2620 }
2621
2622 #[test]
2623 fn safe_join_allows_direct_child_file() {
2624 let tmp = tempfile::tempdir().unwrap();
2625 let base = tmp.path();
2626 let result = safe_join(base, "settings.json").unwrap();
2627 assert_eq!(result.parent(), Some(base));
2628 assert_eq!(result.file_name().unwrap(), "settings.json");
2629 }
2630
2631 #[test]
2632 fn safe_join_rejects_path_traversal() {
2633 let tmp = tempfile::tempdir().unwrap();
2634 let base = tmp.path();
2635 let result = safe_join(base, "../evil");
2636 assert!(result.is_err());
2637 let err = result.unwrap_err();
2638 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
2639 assert!(err.to_string().contains("refusing to access path outside"));
2640 }
2641
2642 #[test]
2643 fn safe_join_rejects_absolute_path() {
2644 let tmp = tempfile::tempdir().unwrap();
2645 let base = tmp.path();
2646 let result = safe_join(base, "/etc/passwd");
2647 assert!(result.is_err());
2650 }
2651
2652 #[test]
2653 fn write_global_user_config_enables_and_creates_context() {
2654 let root = tempfile::tempdir().unwrap();
2655 let active = write_global_user_config_in(root.path(), None).unwrap();
2656 let cfg = crate::config::try_load_user_config_in(root.path())
2657 .unwrap()
2658 .unwrap();
2659 assert_eq!(
2662 cfg.user_context.unwrap().resolve_in(root.path()),
2663 Some(crate::config::default_user_context_path_in(root.path()))
2664 );
2665 let ctx = crate::config::default_user_context_path_in(root.path());
2666 assert_eq!(active, Some(ctx.clone()));
2667 assert!(ctx.exists());
2668 }
2669
2670 #[test]
2671 fn write_global_user_config_can_disable() {
2672 let root = tempfile::tempdir().unwrap();
2673 let active = write_global_user_config_in(
2674 root.path(),
2675 Some(crate::config::UserContext::Toggle(false)),
2676 )
2677 .unwrap();
2678 let cfg = crate::config::try_load_user_config_in(root.path())
2679 .unwrap()
2680 .unwrap();
2681 assert!(matches!(
2682 cfg.user_context,
2683 Some(crate::config::UserContext::Toggle(false))
2684 ));
2685 assert_eq!(active, None, "disabled → no active context path");
2686 assert!(
2688 !crate::config::default_user_context_path_in(root.path()).exists(),
2689 "disabled user context must not create a context.json"
2690 );
2691 }
2692
2693 #[test]
2694 fn write_global_user_config_custom_path_seeds_that_file_only() {
2695 let root = tempfile::tempdir().unwrap();
2696 let custom = root.path().join("custom-ctx.json");
2697 let active = write_global_user_config_in(
2698 root.path(),
2699 Some(crate::config::UserContext::Path(
2700 custom.to_string_lossy().into_owned(),
2701 )),
2702 )
2703 .unwrap();
2704 assert_eq!(active, Some(custom.clone()));
2705 assert!(custom.exists(), "the configured custom path must be seeded");
2706 assert!(
2707 !crate::config::default_user_context_path_in(root.path()).exists(),
2708 "the default context.json must NOT be created when a custom path is configured"
2709 );
2710 }
2711
2712 #[test]
2713 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
2714 let root = tempfile::tempdir().unwrap();
2715 let custom = root.path().join("custom-ctx.json");
2716 write_global_user_config_in(
2718 root.path(),
2719 Some(crate::config::UserContext::Path(
2720 custom.to_string_lossy().into_owned(),
2721 )),
2722 )
2723 .unwrap();
2724 let active = write_global_user_config_in(root.path(), None).unwrap();
2726 assert_eq!(
2727 active,
2728 Some(custom.clone()),
2729 "re-run without flags must preserve the custom path"
2730 );
2731 let cfg = crate::config::try_load_user_config_in(root.path())
2732 .unwrap()
2733 .unwrap();
2734 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
2735 }
2736
2737 #[test]
2738 fn install_global_codex_hooks_writes_and_is_idempotent() {
2739 let tmp = tempfile::tempdir().unwrap();
2740 let codex_dir = tmp.path().join(".codex");
2741
2742 install_global_codex_hooks(&codex_dir).unwrap();
2743 install_global_codex_hooks(&codex_dir).unwrap();
2744
2745 let v: serde_json::Value =
2746 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2747 .unwrap();
2748 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2749 let arr = v["hooks"][event].as_array().unwrap();
2750 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
2751 }
2752 assert!(v["hooks"].get("PreToolUse").is_none());
2753 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
2755 assert_eq!(
2756 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
2757 1,
2758 "AGENTS.md workspace-mode block must appear exactly once"
2759 );
2760 let leftover = fs::read_dir(&codex_dir)
2762 .unwrap()
2763 .filter_map(|e| e.ok())
2764 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
2765 assert!(!leftover);
2766 }
2767
2768 #[test]
2771 fn has_tracevault_hooks_reads_codex_hooks_json() {
2772 let tmp = tempfile::tempdir().unwrap();
2773 let codex_dir = tmp.path().join(".codex");
2774 install_global_codex_hooks(&codex_dir).unwrap();
2775 assert!(has_tracevault_hooks(&codex_dir.join("hooks.json")).unwrap());
2776
2777 let foreign = tmp.path().join("foreign.json");
2778 fs::write(
2779 &foreign,
2780 r#"{"hooks":{"Stop":[{"matcher":"","hooks":[{"type":"command","command":"other-tool stop"}]}]}}"#,
2781 )
2782 .unwrap();
2783 assert!(!has_tracevault_hooks(&foreign).unwrap());
2784 }
2785
2786 #[test]
2787 fn codex_hooks_has_expected_events_and_commands() {
2788 let h = codex_hooks();
2789 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2790 assert!(h.get(event).is_some(), "missing codex event {event}");
2791 }
2792 assert!(h.get("PreToolUse").is_none());
2796 assert!(h.get("Notification").is_none());
2797 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
2799 assert_eq!(
2800 cmd("PostToolUse"),
2801 "tracevault stream --event post-tool-use --agent codex"
2802 );
2803 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
2804 assert_eq!(cmd("SessionStart"), "tracevault session-start");
2805 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
2806 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
2808 }
2809
2810 #[test]
2811 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
2812 let tmp = tempfile::tempdir().unwrap();
2813 install_codex_hooks(tmp.path()).unwrap();
2814 install_codex_hooks(tmp.path()).unwrap();
2815
2816 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
2817 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
2818 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
2819 let arr = v["hooks"][event].as_array().unwrap();
2820 assert_eq!(
2821 arr.len(),
2822 1,
2823 "event {event} must not be duplicated on re-run"
2824 );
2825 }
2826 assert!(v["hooks"].get("PreToolUse").is_none());
2827 }
2828
2829 #[test]
2830 fn install_codex_hooks_preserves_existing_user_hook() {
2831 let tmp = tempfile::tempdir().unwrap();
2832 let codex_dir = tmp.path().join(".codex");
2833 fs::create_dir_all(&codex_dir).unwrap();
2834 fs::write(
2837 codex_dir.join("hooks.json"),
2838 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
2839 )
2840 .unwrap();
2841
2842 install_codex_hooks(tmp.path()).unwrap();
2843
2844 let v: serde_json::Value =
2845 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
2846 .unwrap();
2847 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
2849 .as_array()
2850 .unwrap()
2851 .iter()
2852 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2853 .collect();
2854 assert!(
2855 post_cmds.contains(&"my-own"),
2856 "user PostToolUse hook preserved"
2857 );
2858 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
2859 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
2861 .as_array()
2862 .unwrap()
2863 .iter()
2864 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
2865 .collect();
2866 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
2867 }
2868
2869 const FOREIGN_SETTINGS: &str = r#"{
2873 "permissions": { "allow": ["Bash(ls)"] },
2874 "hooks": {
2875 "PreToolUse": [
2876 { "matcher": "Bash", "hooks": [ { "type": "command", "command": "./guard.sh", "timeout": 7 } ] },
2877 { "matcher": "Write|Edit", "hooks": [
2878 { "type": "command", "command": "tracevault stream --event pre-tool-use", "timeout": 5 },
2879 { "type": "command", "command": "prettier --check", "statusMessage": "fmt" }
2880 ] }
2881 ],
2882 "Stop": [ { "matcher": "", "hooks": [ { "type": "command", "command": "tracevault stream --event stop", "timeout": 5 } ] } ],
2883 "SubagentStop": [ { "hooks": [ { "command": "notify", "type": "command" } ], "matcher": "" } ]
2884 },
2885 "model": "opus"
2886}"#;
2887
2888 fn expected_foreign_entries() -> Vec<String> {
2892 [
2893 r#"{"matcher":"Bash","hooks":[{"type":"command","command":"./guard.sh","timeout":7}]}"#,
2894 r#"{"matcher":"Write|Edit","hooks":[{"type":"command","command":"prettier --check","statusMessage":"fmt"}]}"#,
2895 r#"{"hooks":[{"command":"notify","type":"command"}],"matcher":""}"#,
2896 ]
2897 .map(String::from)
2898 .to_vec()
2899 }
2900
2901 fn holds_tracevault_hook(entry: &serde_json::Value) -> bool {
2902 entry["hooks"]
2903 .as_array()
2904 .unwrap()
2905 .iter()
2906 .any(is_tracevault_hook)
2907 }
2908
2909 fn assert_installed_over_foreign(path: &Path, ours: &serde_json::Value) {
2910 let v: serde_json::Value =
2911 serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap();
2912 assert_eq!(
2913 v.as_object().unwrap().keys().collect::<Vec<_>>(),
2914 ["permissions", "hooks", "model"],
2915 "top-level keys kept, in their order"
2916 );
2917 assert_eq!(
2918 v["permissions"],
2919 serde_json::json!({ "allow": ["Bash(ls)"] })
2920 );
2921 let hooks = v["hooks"].as_object().unwrap();
2922 let foreign: Vec<String> = hooks
2923 .values()
2924 .flat_map(|entries| entries.as_array().unwrap())
2925 .filter(|e| !holds_tracevault_hook(e))
2926 .map(|e| e.to_string())
2927 .collect();
2928 assert_eq!(foreign, expected_foreign_entries());
2929 let ours = ours.as_object().unwrap();
2930 for (event, entries) in hooks {
2931 let mine: Vec<&serde_json::Value> = entries
2932 .as_array()
2933 .unwrap()
2934 .iter()
2935 .filter(|e| holds_tracevault_hook(e))
2936 .collect();
2937 let want: Vec<&serde_json::Value> = ours
2938 .get(event)
2939 .map(|o| o.as_array().unwrap().iter().collect())
2940 .unwrap_or_default();
2941 assert_eq!(mine, want, "Visdom entries under {event}");
2942 }
2943 for event in ours.keys() {
2944 assert!(hooks.contains_key(event), "missing {event}");
2945 }
2946 }
2947
2948 #[test]
2949 fn install_claude_hooks_keeps_foreign_hooks_in_both_settings_files() {
2950 for target in [ClaudeSettingsTarget::Shared, ClaudeSettingsTarget::Local] {
2951 let tmp = tempfile::tempdir().unwrap();
2952 let path = tmp.path().join(".claude").join(target.filename());
2953 fs::create_dir_all(path.parent().unwrap()).unwrap();
2954 fs::write(&path, FOREIGN_SETTINGS).unwrap();
2955
2956 install_claude_hooks(tmp.path(), target).unwrap();
2957 assert_installed_over_foreign(&path, &tracevault_hooks());
2958
2959 let after_first = fs::read(&path).unwrap();
2961 install_claude_hooks(tmp.path(), target).unwrap();
2962 assert_eq!(fs::read(&path).unwrap(), after_first, "{target:?}");
2963 }
2964 }
2965
2966 #[test]
2967 fn install_global_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2968 let tmp = tempfile::tempdir().unwrap();
2969 let claude_dir = tmp.path().join(".claude");
2970 fs::create_dir_all(&claude_dir).unwrap();
2971 fs::write(claude_dir.join("settings.json"), FOREIGN_SETTINGS).unwrap();
2972
2973 install_global_hooks(&claude_dir).unwrap();
2974 assert_installed_over_foreign(&claude_dir.join("settings.json"), &tracevault_hooks());
2975 }
2976
2977 #[test]
2978 fn install_codex_hooks_keeps_foreign_hooks_and_upgrades_ours() {
2979 for global in [false, true] {
2980 let tmp = tempfile::tempdir().unwrap();
2981 let codex_dir = tmp.path().join(".codex");
2982 fs::create_dir_all(&codex_dir).unwrap();
2983 fs::write(codex_dir.join("hooks.json"), FOREIGN_SETTINGS).unwrap();
2984
2985 if global {
2986 install_global_codex_hooks(&codex_dir).unwrap();
2987 } else {
2988 install_codex_hooks(tmp.path()).unwrap();
2989 }
2990 assert_installed_over_foreign(&codex_dir.join("hooks.json"), &codex_hooks());
2991 }
2992 }
2993
2994 #[test]
2995 fn up_to_date_hook_file_is_not_rewritten() {
2996 let tmp = tempfile::tempdir().unwrap();
2998 let path = tmp.path().join(".claude/settings.json");
2999 fs::create_dir_all(path.parent().unwrap()).unwrap();
3000 let mut body = Vec::new();
3001 let fmt = serde_json::ser::PrettyFormatter::with_indent(b" ");
3002 let mut ser = serde_json::Serializer::with_formatter(&mut body, fmt);
3003 serde::Serialize::serialize(
3004 &serde_json::json!({ "hooks": tracevault_hooks() }),
3005 &mut ser,
3006 )
3007 .unwrap();
3008 fs::write(&path, &body).unwrap();
3009
3010 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).unwrap();
3011 assert_eq!(fs::read(&path).unwrap(), body);
3012 }
3013
3014 #[test]
3015 fn install_claude_hooks_refuses_malformed_settings_without_clobbering() {
3016 for (target, body) in [
3017 (ClaudeSettingsTarget::Shared, "{ not json"),
3018 (ClaudeSettingsTarget::Local, "[1, 2]"),
3019 (ClaudeSettingsTarget::Shared, "null"),
3020 (ClaudeSettingsTarget::Shared, r#"{"hooks": []}"#),
3021 (ClaudeSettingsTarget::Local, r#"{"hooks": {"Stop": {}}}"#),
3022 ] {
3023 let tmp = tempfile::tempdir().unwrap();
3024 let path = tmp.path().join(".claude").join(target.filename());
3025 fs::create_dir_all(path.parent().unwrap()).unwrap();
3026 fs::write(&path, body).unwrap();
3027
3028 let err = install_claude_hooks(tmp.path(), target).unwrap_err();
3029 assert_eq!(err.kind(), io::ErrorKind::InvalidData, "{body}");
3030 assert_eq!(
3031 fs::read_to_string(&path).unwrap(),
3032 body,
3033 "file must be untouched"
3034 );
3035 assert_eq!(
3036 fs::read_dir(path.parent().unwrap()).unwrap().count(),
3037 1,
3038 "no temp file left behind"
3039 );
3040 }
3041 }
3042
3043 #[test]
3044 fn concurrent_installs_never_publish_a_partial_file() {
3045 let tmp = tempfile::tempdir().unwrap();
3051 let path = tmp.path().join("settings.json");
3052 fs::write(&path, FOREIGN_SETTINGS).unwrap();
3053 let done = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
3054 let reader = {
3055 let (path, done) = (path.clone(), done.clone());
3056 std::thread::spawn(move || {
3057 while !done.load(std::sync::atomic::Ordering::Relaxed) {
3058 let body = fs::read_to_string(&path).unwrap();
3059 serde_json::from_str::<serde_json::Value>(&body).unwrap();
3060 }
3061 })
3062 };
3063 let writers: Vec<_> = [tracevault_hooks(), codex_hooks()]
3064 .into_iter()
3065 .map(|ours| {
3066 let path = path.clone();
3067 std::thread::spawn(move || {
3068 for _ in 0..200 {
3069 if let Err(e) = merge_hooks_into_file(&path, &ours) {
3070 assert!(e.to_string().contains("kept changing"), "{e}");
3071 }
3072 }
3073 })
3074 })
3075 .collect();
3076 for writer in writers {
3077 writer.join().unwrap();
3078 }
3079 done.store(true, std::sync::atomic::Ordering::Relaxed);
3080 reader.join().unwrap();
3081 let v: serde_json::Value =
3082 serde_json::from_str(&fs::read_to_string(&path).unwrap()).unwrap();
3083 assert_eq!(v["model"], "opus");
3084 assert_eq!(
3085 fs::read_dir(tmp.path()).unwrap().count(),
3086 1,
3087 "no temp file left"
3088 );
3089 }
3090
3091 #[cfg(unix)]
3092 #[test]
3093 fn install_claude_hooks_keeps_file_permissions() {
3094 use std::os::unix::fs::PermissionsExt;
3095 let tmp = tempfile::tempdir().unwrap();
3096 let path = tmp.path().join(".claude/settings.local.json");
3097 fs::create_dir_all(path.parent().unwrap()).unwrap();
3098 fs::write(&path, FOREIGN_SETTINGS).unwrap();
3099 fs::set_permissions(&path, fs::Permissions::from_mode(0o600)).unwrap();
3100
3101 install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Local).unwrap();
3102
3103 let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
3104 assert_eq!(mode, 0o600);
3105 assert_installed_over_foreign(&path, &tracevault_hooks());
3106 }
3107
3108 #[cfg(unix)]
3109 #[test]
3110 fn install_claude_hooks_updates_symlinked_settings_at_its_target() {
3111 let tmp = tempfile::tempdir().unwrap();
3112 let central = tmp.path().join("central/claude-settings.json");
3113 fs::create_dir_all(central.parent().unwrap()).unwrap();
3114 fs::write(¢ral, FOREIGN_SETTINGS).unwrap();
3115 let link = tmp.path().join("repo/.claude/settings.json");
3116 fs::create_dir_all(link.parent().unwrap()).unwrap();
3117 std::os::unix::fs::symlink(¢ral, &link).unwrap();
3118
3119 install_claude_hooks(&tmp.path().join("repo"), ClaudeSettingsTarget::Shared).unwrap();
3120
3121 assert!(fs::symlink_metadata(&link)
3122 .unwrap()
3123 .file_type()
3124 .is_symlink());
3125 assert_installed_over_foreign(¢ral, &tracevault_hooks());
3126 }
3127
3128 #[cfg(unix)]
3129 #[test]
3130 fn install_claude_hooks_refuses_dangling_symlink() {
3131 let tmp = tempfile::tempdir().unwrap();
3132 let link = tmp.path().join(".claude/settings.json");
3133 fs::create_dir_all(link.parent().unwrap()).unwrap();
3134 std::os::unix::fs::symlink(tmp.path().join("gone.json"), &link).unwrap();
3135
3136 assert!(install_claude_hooks(tmp.path(), ClaudeSettingsTarget::Shared).is_err());
3137 assert!(fs::symlink_metadata(&link)
3138 .unwrap()
3139 .file_type()
3140 .is_symlink());
3141 assert!(!tmp.path().join("gone.json").exists());
3142 }
3143
3144 #[test]
3145 fn validate_init_flags_rejects_claude_settings_with_codex() {
3146 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
3147 }
3148
3149 #[test]
3150 fn validate_init_flags_allows_codex_without_claude_settings() {
3151 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
3152 }
3153
3154 #[test]
3155 fn validate_init_flags_allows_claude_with_claude_settings() {
3156 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
3157 }
3158
3159 #[test]
3160 fn merge_hooks_into_file_rejects_parent_dir() {
3161 let tmp = tempfile::tempdir().unwrap();
3162 let bad = tmp.path().join("..").join("hooks.json");
3163 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
3164 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
3165 }
3166
3167 #[test]
3168 fn append_workspace_md_rejects_parent_dir() {
3169 let tmp = tempfile::tempdir().unwrap();
3170 let bad = tmp.path().join("..").join("AGENTS.md");
3171 let err = append_workspace_md(&bad).unwrap_err();
3172 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
3173 }
3174
3175 #[tokio::test]
3176 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
3177 let tmp = tempfile::tempdir().unwrap();
3178 let root = tmp.path();
3179 crate::test_helpers::init_git_repo(root);
3180 fs::create_dir_all(root.join(".visdom")).unwrap();
3183 fs::write(
3184 root.join(".visdom/tracing.toml"),
3185 "api_key = \"tvk_test\"\n",
3186 )
3187 .unwrap();
3188
3189 let entry = init_in_directory(
3190 root,
3191 None,
3192 None,
3193 false,
3194 Some(crate::config::UserContext::Toggle(false)),
3195 crate::agent::Agent::Codex,
3196 )
3197 .await
3198 .unwrap();
3199
3200 assert!(root.join(".codex").join("hooks.json").exists());
3202 assert!(!root.join(".claude").join("settings.json").exists());
3203 assert_eq!(entry, ".codex/hooks.json");
3204
3205 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
3207 assert!(gi.contains(".codex/hooks.json"));
3208 assert!(root.join(".visdom/.gitignore").exists());
3209 }
3210
3211 #[tokio::test]
3223 async fn init_in_directory_registers_repo_and_persists_repo_id() {
3224 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3225 let tmp = tempfile::tempdir().unwrap();
3226 let root = tmp.path();
3227 crate::test_helpers::init_git_repo(root);
3228 add_origin_remote(root, "git@github.com:org/repo.git");
3229
3230 let repo_id = "11111111-1111-4111-8111-111111111111";
3231 let body = format!(r#"{{"repo_id":"{repo_id}"}}"#);
3232 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
3235 http_response("404 Not Found", NO_REMOTE),
3236 http_response("200 OK", &body),
3237 ]);
3238
3239 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3240 _guard.set("XDG_CONFIG_HOME", tmp.path());
3241 _guard.set("TRACEVAULT_API_KEY", "tok");
3242 _guard.remove("TRACEVAULT_SERVER_URL");
3243
3244 init_in_directory(
3245 root,
3246 Some(&base),
3247 None,
3248 true,
3249 Some(crate::config::UserContext::Toggle(false)),
3250 crate::agent::Agent::Codex,
3251 )
3252 .await
3253 .unwrap();
3254
3255 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
3256 assert_eq!(
3257 cfg.repo_id,
3258 Some(repo_id.to_string()),
3259 "successful registration must persist repo_id to config.toml"
3260 );
3261 }
3262
3263 #[tokio::test]
3269 async fn init_in_directory_registration_403_does_not_persist_repo_id() {
3270 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3271 let tmp = tempfile::tempdir().unwrap();
3272 let root = tmp.path();
3273 crate::test_helpers::init_git_repo(root);
3274 add_origin_remote(root, "git@github.com:org/repo.git");
3275
3276 let (base, _rx) = crate::test_helpers::spawn_seq(vec![
3277 http_response("404 Not Found", NO_REMOTE),
3278 http_response("403 Forbidden", ""),
3279 ]);
3280
3281 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3282 _guard.set("XDG_CONFIG_HOME", tmp.path());
3283 _guard.set("TRACEVAULT_API_KEY", "tok");
3284 _guard.remove("TRACEVAULT_SERVER_URL");
3285
3286 let entry = init_in_directory(
3287 root,
3288 Some(&base),
3289 None,
3290 true,
3291 Some(crate::config::UserContext::Toggle(false)),
3292 crate::agent::Agent::Codex,
3293 )
3294 .await
3295 .expect("a registration failure (403) must not abort init itself");
3296 assert_eq!(entry, ".codex/hooks.json");
3297
3298 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
3299 assert!(
3300 cfg.repo_id.is_none(),
3301 "a 403 registration failure must not persist a repo_id"
3302 );
3303 }
3304
3305 #[tokio::test]
3310 async fn registration_failure_message_flags_403_as_not_authorized() {
3311 let base = spawn_once(http_response("403 Forbidden", ""));
3312 let client = ApiClient::new(&base, Some("tok"));
3313 let err = client
3314 .register_repo(crate::api_client::RegisterRepoRequest {
3315 repo_name: "repo".into(),
3316 github_url: Some("git@github.com:org/repo.git".into()),
3317 })
3318 .await
3319 .unwrap_err();
3320 let msg = registration_failure_message(err.as_ref());
3321 assert!(
3322 msg.contains("not authorized"),
3323 "403 registration failure must surface a not-authorized message; got: {msg}"
3324 );
3325 }
3326
3327 #[tokio::test]
3330 async fn registration_failure_message_generic_for_non_403() {
3331 let base = spawn_once(http_response("500 Internal Server Error", ""));
3332 let client = ApiClient::new(&base, Some("tok"));
3333 let err = client
3334 .register_repo(crate::api_client::RegisterRepoRequest {
3335 repo_name: "repo".into(),
3336 github_url: Some("git@github.com:org/repo.git".into()),
3337 })
3338 .await
3339 .unwrap_err();
3340 let msg = registration_failure_message(err.as_ref());
3341 assert!(
3342 msg.contains("could not register repo on server"),
3343 "got: {msg}"
3344 );
3345 assert!(!msg.contains("not authorized"), "got: {msg}");
3346 }
3347
3348 #[tokio::test]
3353 async fn registration_failure_message_does_not_misclassify_403_in_body() {
3354 let base = spawn_once(http_response(
3355 "500 Internal Server Error",
3356 "upstream error 403 from proxy",
3357 ));
3358 let client = ApiClient::new(&base, Some("tok"));
3359 let err = client
3360 .register_repo(crate::api_client::RegisterRepoRequest {
3361 repo_name: "repo".into(),
3362 github_url: Some("git@github.com:org/repo.git".into()),
3363 })
3364 .await
3365 .unwrap_err();
3366 let msg = registration_failure_message(err.as_ref());
3367 assert!(
3368 !msg.contains("not authorized"),
3369 "a 403 substring in the body must not trigger the not-authorized message; got: {msg}"
3370 );
3371 assert!(
3372 msg.contains("could not register repo on server"),
3373 "got: {msg}"
3374 );
3375 }
3376
3377 #[tokio::test]
3381 async fn registration_failure_message_flags_404_as_version_mismatch() {
3382 let base = spawn_once(http_response("404 Not Found", ""));
3383 let client = ApiClient::new(&base, Some("tok"));
3384 let err = client
3385 .register_repo(crate::api_client::RegisterRepoRequest {
3386 repo_name: "repo".into(),
3387 github_url: Some("git@github.com:org/repo.git".into()),
3388 })
3389 .await
3390 .unwrap_err();
3391 let msg = registration_failure_message(err.as_ref());
3392 assert!(
3393 msg.to_lowercase().contains("version mismatch"),
3394 "a 404 registration failure should hint at a version mismatch; got: {msg}"
3395 );
3396 }
3397
3398 const NO_REMOTE: &str = r#"{"error":"No remote for that URL"}"#;
3402 const REMOTE_ID: &str = "2280a1c9-0000-4000-8000-000000000003";
3403 const CANONICAL: &str = "44000761-0000-4000-8000-000000000001";
3404 const STRAY: &str = "7995d35d-0000-4000-8000-000000000002";
3405
3406 fn resolve_remote_ok() -> String {
3407 http_response(
3408 "200 OK",
3409 &format!(
3410 r#"{{"remote_id":"{REMOTE_ID}","name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready"}}"#
3411 ),
3412 )
3413 }
3414
3415 fn remote_detail(repos: &[(&str, &str)]) -> String {
3416 let repos: Vec<String> = repos
3417 .iter()
3418 .map(|(id, name)| format!(r#"{{"id":"{id}","name":"{name}"}}"#))
3419 .collect();
3420 http_response(
3421 "200 OK",
3422 &format!(
3423 r#"{{"name":"tracing","normalized_url":"github.com/org/repo","clone_status":"ready","repos":[{}]}}"#,
3424 repos.join(",")
3425 ),
3426 )
3427 }
3428
3429 async fn init_against(root: &Path, responses: Vec<String>) -> (Option<String>, Vec<String>) {
3432 let (base, rx) = crate::test_helpers::spawn_seq(responses);
3433 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3434 _guard.set("XDG_CONFIG_HOME", root);
3435 _guard.set("TRACEVAULT_API_KEY", "tok");
3436 _guard.remove("TRACEVAULT_SERVER_URL");
3437
3438 init_in_directory(
3439 root,
3440 Some(&base),
3441 None,
3442 true,
3443 Some(crate::config::UserContext::Toggle(false)),
3444 crate::agent::Agent::Codex,
3445 )
3446 .await
3447 .expect("init succeeds");
3448
3449 let cfg = crate::config::TracevaultConfig::load(root).expect("config.toml written by init");
3450 (cfg.repo_id, rx.try_iter().collect())
3451 }
3452
3453 fn registered(requests: &[String]) -> bool {
3454 requests.iter().any(|r| r.starts_with("POST /api/v1/repos"))
3455 }
3456
3457 #[tokio::test]
3460 async fn init_binds_the_existing_repo_of_a_known_remote() {
3461 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3462 let tmp = tempfile::tempdir().unwrap();
3463 crate::test_helpers::init_git_repo(tmp.path());
3464 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3465
3466 let (repo_id, requests) = init_against(
3467 tmp.path(),
3468 vec![
3469 resolve_remote_ok(),
3470 remote_detail(&[(CANONICAL, "tracevault")]),
3471 ],
3472 )
3473 .await;
3474
3475 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3476 assert!(!registered(&requests), "requests: {requests:?}");
3477 }
3478
3479 #[tokio::test]
3482 async fn init_binds_the_record_named_like_the_checkout() {
3483 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3484 let tmp = tempfile::tempdir().unwrap();
3485 crate::test_helpers::init_git_repo(tmp.path());
3486 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3487 let dir_name = crate::resolution::git_repo_name(tmp.path());
3488
3489 let (repo_id, requests) = init_against(
3490 tmp.path(),
3491 vec![
3492 resolve_remote_ok(),
3493 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, &dir_name)]),
3494 ],
3495 )
3496 .await;
3497
3498 assert_eq!(repo_id.as_deref(), Some(STRAY));
3499 assert!(!registered(&requests));
3500 }
3501
3502 #[tokio::test]
3504 async fn init_rerun_keeps_the_previously_bound_repo() {
3505 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3506 let tmp = tempfile::tempdir().unwrap();
3507 crate::test_helpers::init_git_repo(tmp.path());
3508 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3509 fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
3510 fs::write(
3511 tmp.path().join(".visdom/tracing.toml"),
3512 format!("repo_id = \"{STRAY}\"\n"),
3513 )
3514 .unwrap();
3515
3516 let (repo_id, requests) = init_against(
3517 tmp.path(),
3518 vec![
3519 resolve_remote_ok(),
3520 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3521 ],
3522 )
3523 .await;
3524
3525 assert_eq!(repo_id.as_deref(), Some(STRAY));
3526 assert!(!registered(&requests));
3527 }
3528
3529 #[tokio::test]
3532 async fn init_binding_keeps_the_rest_of_the_config() {
3533 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3534 let tmp = tempfile::tempdir().unwrap();
3535 crate::test_helpers::init_git_repo(tmp.path());
3536 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3537 fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
3538 fs::write(
3539 tmp.path().join(".visdom/tracing.toml"),
3540 "api_key = \"tvk_kept\"\ndefault_project = \"payments\"\nuser_context = false\n",
3541 )
3542 .unwrap();
3543
3544 let (repo_id, requests) = init_against(
3545 tmp.path(),
3546 vec![
3547 http_response(
3549 "200 OK",
3550 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3551 ),
3552 resolve_remote_ok(),
3553 remote_detail(&[(CANONICAL, "tracevault")]),
3554 ],
3555 )
3556 .await;
3557
3558 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3559 assert!(
3560 requests[0].starts_with("GET /api/v1/projects"),
3561 "{requests:?}"
3562 );
3563 let cfg = crate::config::TracevaultConfig::load(tmp.path()).unwrap();
3564 assert_eq!(cfg.api_key.as_deref(), Some("tvk_kept"));
3565 assert_eq!(cfg.default_project, None);
3566 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3567 assert_eq!(cfg.project_name.as_deref(), Some("payments"));
3568 }
3569
3570 const PROJECT: &str = "00000000-0000-4000-8000-0000000000aa";
3571
3572 #[tokio::test]
3575 async fn init_unknown_default_project_errors_and_writes_nothing() {
3576 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3577 let tmp = tempfile::tempdir().unwrap();
3578 crate::test_helpers::init_git_repo(tmp.path());
3579 fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
3580 let content = "default_project = \"typo\"\n";
3581 fs::write(tmp.path().join(".visdom/tracing.toml"), content).unwrap();
3582 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3583 "200 OK",
3584 &format!(r#"[{{"id":"{PROJECT}","name":"payments"}}]"#),
3585 )]);
3586 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3587 _guard.set("XDG_CONFIG_HOME", tmp.path());
3588 _guard.set("TRACEVAULT_API_KEY", "tok");
3589 _guard.remove("TRACEVAULT_SERVER_URL");
3590
3591 let err = init_in_directory(
3592 tmp.path(),
3593 Some(&base),
3594 None,
3595 true,
3596 None,
3597 crate::agent::Agent::Codex,
3598 )
3599 .await
3600 .unwrap_err();
3601
3602 assert!(err.to_string().contains("'typo'"), "{err}");
3603 assert_eq!(
3604 fs::read_to_string(tmp.path().join(".visdom/tracing.toml")).unwrap(),
3605 content
3606 );
3607 assert!(!tmp.path().join(".codex/hooks.json").exists());
3608 }
3609
3610 #[tokio::test]
3614 async fn init_workspace_binds_a_non_git_dir_to_a_project() {
3615 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3616 let tmp = tempfile::tempdir().unwrap();
3617 let dir = tmp.path().join("umbrella");
3618 fs::create_dir_all(&dir).unwrap();
3619 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response(
3620 "200 OK",
3621 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3622 )]);
3623 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3624 _guard.set("XDG_CONFIG_HOME", tmp.path());
3625 _guard.set("TRACEVAULT_API_KEY", "tok");
3626 _guard.remove("TRACEVAULT_SERVER_URL");
3627
3628 let bound = init_workspace(&dir, "visdom", Some(&base)).await.unwrap();
3629
3630 assert_eq!(bound.project_id.to_string(), PROJECT);
3631 assert_eq!(bound.project_name, "visdom");
3632 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3633 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3634 assert_eq!(cfg.project_name.as_deref(), Some("visdom"));
3635 assert_eq!(cfg.repo_id, None);
3636 assert_eq!(cfg.server_url.as_deref(), Some(base.as_str()));
3637 assert!(dir.join(".visdom/.gitignore").exists());
3638 let requests: Vec<String> = rx.try_iter().collect();
3639 assert_eq!(requests.len(), 1, "{requests:?}");
3640 let sub = dir.join("notes");
3642 fs::create_dir_all(&sub).unwrap();
3643 assert_eq!(
3644 crate::paths::resolve_project_root(&sub)
3645 .root
3646 .canonicalize()
3647 .unwrap(),
3648 dir.canonicalize().unwrap()
3649 );
3650 }
3651
3652 #[tokio::test]
3655 async fn init_workspace_rebinds_and_keeps_other_keys() {
3656 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3657 let tmp = tempfile::tempdir().unwrap();
3658 let dir = tmp.path();
3659 fs::create_dir_all(dir.join(".visdom")).unwrap();
3660 fs::write(
3661 dir.join(".visdom/tracing.toml"),
3662 "default_project = \"old\"\nproject_id = \"00000000-0000-4000-8000-000000000001\"\nuser_context = false\n",
3663 )
3664 .unwrap();
3665 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3666 "200 OK",
3667 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3668 )]);
3669 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3670 _guard.set("XDG_CONFIG_HOME", dir);
3671 _guard.set("TRACEVAULT_API_KEY", "tok");
3672 _guard.remove("TRACEVAULT_SERVER_URL");
3673
3674 init_workspace(dir, "visdom", Some(&base)).await.unwrap();
3675
3676 let cfg = crate::config::TracevaultConfig::load(dir).unwrap();
3677 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3678 assert_eq!(cfg.default_project, None);
3679 assert!(matches!(
3680 cfg.user_context,
3681 Some(crate::config::UserContext::Toggle(false))
3682 ));
3683 }
3684
3685 #[test]
3689 fn append_workspace_md_upgrades_an_older_block_in_place() {
3690 let tmp = tempfile::tempdir().unwrap();
3691 let md = tmp.path().join("CLAUDE.md");
3692 for old in PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS {
3693 fs::write(
3695 &md,
3696 format!("# Mine\nkeep me\n\n{old}## After\nalso keep\n"),
3697 )
3698 .unwrap();
3699
3700 append_workspace_md(&md).unwrap();
3701 let got = fs::read_to_string(&md).unwrap();
3702 assert_eq!(
3703 got,
3704 format!("# Mine\nkeep me\n\n{GLOBAL_CLAUDE_MD_BLOCK}## After\nalso keep\n")
3705 );
3706 append_workspace_md(&md).unwrap();
3707 assert_eq!(fs::read_to_string(&md).unwrap(), got);
3708 }
3709
3710 let edited = "x\n\n<!-- tracevault:workspace-mode -->\n## T\nmy own words\n";
3712 fs::write(&md, edited).unwrap();
3713 append_workspace_md(&md).unwrap();
3714 assert_eq!(fs::read_to_string(&md).unwrap(), edited);
3715 }
3716
3717 #[tokio::test]
3720 async fn init_workspace_refuses_a_server_url_the_credential_is_not_for() {
3721 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3722 let tmp = tempfile::tempdir().unwrap();
3723 let (base, rx) = crate::test_helpers::spawn_seq(vec![http_response("200 OK", "[]")]);
3724 fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
3725 fs::write(
3726 tmp.path().join(".visdom/tracing.toml"),
3727 "server_url = \"http://other.example.invalid\"\napi_key = \"tvk_x\"\n",
3728 )
3729 .unwrap();
3730 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3731 _guard.set("XDG_CONFIG_HOME", tmp.path());
3732 _guard.remove("TRACEVAULT_API_KEY");
3733 _guard.remove("TRACEVAULT_SERVER_URL");
3734
3735 let err = init_workspace(tmp.path(), "visdom", Some(&base))
3736 .await
3737 .unwrap_err();
3738 assert!(err.to_string().contains("not --server-url"), "{err}");
3739 assert_eq!(rx.try_iter().count(), 0, "no request may be sent");
3740 }
3741
3742 #[tokio::test]
3743 async fn credential_url_mismatch_only_for_a_different_explicit_server() {
3744 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3745 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3746 _guard.remove("TRACEVAULT_API_KEY");
3747 assert!(credential_url_mismatch(Some("https://a/"), Some("https://a")).is_none());
3748 assert!(credential_url_mismatch(None, Some("https://b")).is_none());
3749 assert!(credential_url_mismatch(Some("https://a"), None).is_none());
3750 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_some());
3751 _guard.set("TRACEVAULT_API_KEY", "tvk_for_b");
3753 assert!(credential_url_mismatch(Some("https://a"), Some("https://b")).is_none());
3754 }
3755
3756 #[tokio::test]
3759 async fn migrate_cwd_config_migrates_the_dirs_config() {
3760 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3761 let tmp = tempfile::tempdir().unwrap();
3762 let dir = tmp.path().join("umbrella");
3763 fs::create_dir_all(dir.join(".visdom")).unwrap();
3764 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3765 "200 OK",
3766 &format!(r#"[{{"id":"{PROJECT}","name":"visdom"}}]"#),
3767 )]);
3768 fs::write(
3769 dir.join(".visdom/tracing.toml"),
3770 format!("server_url = \"{base}\"\napi_key = \"tvk_x\"\ndefault_project = \"visdom\"\n"),
3771 )
3772 .unwrap();
3773 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3774 _guard.set("XDG_CONFIG_HOME", tmp.path());
3775 _guard.remove("TRACEVAULT_API_KEY");
3776 _guard.remove("TRACEVAULT_SERVER_URL");
3777
3778 migrate_cwd_config(&dir).await.unwrap();
3779
3780 let cfg = crate::config::TracevaultConfig::load(&dir).unwrap();
3781 assert_eq!(cfg.project_id.as_deref(), Some(PROJECT));
3782 assert_eq!(cfg.default_project, None);
3783 }
3784
3785 #[tokio::test]
3787 async fn init_workspace_unknown_or_ambiguous_name_writes_nothing() {
3788 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3789 for name in ["nope", "dup"] {
3790 let tmp = tempfile::tempdir().unwrap();
3791 let (base, _rx) = crate::test_helpers::spawn_seq(vec![http_response(
3792 "200 OK",
3793 r#"[{"id":"00000000-0000-4000-8000-000000000001","name":"dup"},{"id":"00000000-0000-4000-8000-000000000002","name":"dup"}]"#,
3794 )]);
3795 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3796 _guard.set("XDG_CONFIG_HOME", tmp.path());
3797 _guard.set("TRACEVAULT_API_KEY", "tok");
3798 _guard.remove("TRACEVAULT_SERVER_URL");
3799
3800 let err = init_workspace(tmp.path(), name, Some(&base))
3801 .await
3802 .unwrap_err();
3803 assert!(err.to_string().contains(&format!("'{name}'")), "{err}");
3804 assert!(!tmp.path().join(".visdom").exists(), "{name}");
3805 }
3806 }
3807
3808 #[tokio::test]
3811 async fn init_workspace_refuses_a_git_subdirectory() {
3812 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3813 let tmp = tempfile::tempdir().unwrap();
3814 crate::test_helpers::init_git_repo(tmp.path());
3815 let sub = tmp.path().join("pkg");
3816 fs::create_dir_all(&sub).unwrap();
3817 let mut _guard = crate::test_helpers::EnvVarGuard::new();
3818 _guard.set("XDG_CONFIG_HOME", tmp.path());
3819 _guard.set("TRACEVAULT_API_KEY", "tok");
3820 _guard.remove("TRACEVAULT_SERVER_URL");
3821
3822 let err = init_workspace(&sub, "visdom", Some("http://127.0.0.1:9"))
3823 .await
3824 .unwrap_err();
3825 assert!(err.to_string().contains("inside the git repo"), "{err}");
3826 assert!(!sub.join(".visdom").exists());
3827 }
3828
3829 #[tokio::test]
3832 async fn init_rerun_keeps_repo_id_when_the_server_check_fails() {
3833 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3834 let tmp = tempfile::tempdir().unwrap();
3835 crate::test_helpers::init_git_repo(tmp.path());
3836 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3837 fs::create_dir_all(tmp.path().join(".visdom")).unwrap();
3838 fs::write(
3839 tmp.path().join(".visdom/tracing.toml"),
3840 format!("repo_id = \"{STRAY}\"\n"),
3841 )
3842 .unwrap();
3843
3844 let (repo_id, requests) = init_against(
3845 tmp.path(),
3846 vec![http_response("500 Internal Server Error", "{}")],
3847 )
3848 .await;
3849
3850 assert_eq!(repo_id.as_deref(), Some(STRAY));
3851 assert!(!registered(&requests));
3852 }
3853
3854 #[tokio::test]
3856 async fn init_registers_nothing_when_the_codebase_is_ambiguous() {
3857 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3858 let tmp = tempfile::tempdir().unwrap();
3859 crate::test_helpers::init_git_repo(tmp.path());
3860 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3861
3862 let (repo_id, requests) = init_against(
3863 tmp.path(),
3864 vec![
3865 resolve_remote_ok(),
3866 remote_detail(&[(CANONICAL, "tracevault"), (STRAY, "tracing-old")]),
3867 ],
3868 )
3869 .await;
3870
3871 assert_eq!(repo_id, None);
3872 assert!(!registered(&requests));
3873 }
3874
3875 #[tokio::test]
3878 async fn init_registers_for_a_codebase_without_live_repos() {
3879 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3880 let tmp = tempfile::tempdir().unwrap();
3881 crate::test_helpers::init_git_repo(tmp.path());
3882 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3883
3884 let (repo_id, requests) = init_against(
3885 tmp.path(),
3886 vec![
3887 resolve_remote_ok(),
3888 remote_detail(&[]),
3889 http_response("201 Created", &format!(r#"{{"repo_id":"{CANONICAL}"}}"#)),
3890 ],
3891 )
3892 .await;
3893
3894 assert_eq!(repo_id.as_deref(), Some(CANONICAL));
3895 assert!(registered(&requests));
3896 }
3897
3898 #[tokio::test]
3900 async fn init_does_not_register_when_the_remote_check_fails() {
3901 let _env_lock = crate::test_helpers::lock_env_mutation().await;
3902 let tmp = tempfile::tempdir().unwrap();
3903 crate::test_helpers::init_git_repo(tmp.path());
3904 add_origin_remote(tmp.path(), "git@github.com:org/repo.git");
3905
3906 let (repo_id, requests) = init_against(
3907 tmp.path(),
3908 vec![http_response("500 Internal Server Error", "{}")],
3909 )
3910 .await;
3911
3912 assert_eq!(repo_id, None);
3913 assert!(!registered(&requests));
3914 }
3915
3916 fn our_commands(settings: &serde_json::Value) -> Vec<String> {
3918 hooks_in(&settings["hooks"])
3919 .filter(|hook| is_tracevault_hook(hook))
3920 .filter_map(hook_command)
3921 .map(String::from)
3922 .collect()
3923 }
3924
3925 #[test]
3926 fn hooks_are_spelled_for_the_binary_that_installs_them() {
3927 let visdom = hooks_spelled(&tracevault_hooks(), true);
3928 let commands: Vec<_> = hooks_in(&visdom).filter_map(hook_command).collect();
3929 assert!(!commands.is_empty());
3930 assert!(
3931 commands.iter().all(|c| c.starts_with("visdom trace ")),
3932 "{commands:?}"
3933 );
3934 assert!(commands.contains(&"visdom trace stream --event stop"));
3935 assert_eq!(
3936 hooks_spelled(&tracevault_hooks(), false),
3937 tracevault_hooks()
3938 );
3939 }
3940
3941 #[test]
3946 fn merge_hooks_keeps_hooks_that_already_call_visdom() {
3947 let mut settings = serde_json::json!({"hooks": {
3948 "Stop": [{"matcher": "", "hooks": [
3949 {"type": "command", "command": "visdom trace stream --event stop"},
3950 {"type": "command", "command": "my-own-hook"}]}],
3951 }});
3952 merge_hooks(
3953 &mut settings,
3954 &tracevault_hooks(),
3955 Path::new("settings.json"),
3956 )
3957 .unwrap();
3958
3959 let commands = our_commands(&settings);
3960 assert!(commands.len() > 1, "{commands:?}");
3961 assert!(
3962 commands.iter().all(|c| c.starts_with("visdom trace ")),
3963 "{commands:?}"
3964 );
3965 let all: Vec<_> = hooks_in(&settings["hooks"])
3966 .filter_map(hook_command)
3967 .collect();
3968 assert!(all.contains(&"my-own-hook"), "{all:?}");
3969 let once = settings.clone();
3971 merge_hooks(
3972 &mut settings,
3973 &tracevault_hooks(),
3974 Path::new("settings.json"),
3975 )
3976 .unwrap();
3977 assert_eq!(settings, once);
3978 }
3979
3980 #[test]
3981 fn a_git_hook_block_is_respelled_for_visdom_and_the_rest_left_alone() {
3982 let hook = "#!/bin/sh\ntracevault check # the user's own line\n\n\
3983 # tracevault:enforce\n\
3984 tracevault_prepush_stdin=$(cat)\n\
3985 tracevault sync 2>/dev/null || true\n\
3986 printf '%s' \"$tracevault_prepush_stdin\" | tracevault check || { echo \"tracevault: policy check failed\"; exit 1; }\n\
3987 \ntracevault sync # also the user's\n";
3988 let respelled = git_hook_block_for_visdom(hook, PRE_PUSH_MARKER).unwrap();
3989 assert_eq!(
3990 respelled,
3991 "#!/bin/sh\ntracevault check # the user's own line\n\n\
3992 # visdom:enforce\n\
3993 visdom_prepush_stdin=$(cat)\n\
3994 visdom trace sync 2>/dev/null || true\n\
3995 printf '%s' \"$visdom_prepush_stdin\" | visdom trace check || { echo \"visdom: policy check failed\"; exit 1; }\n\
3996 \ntracevault sync # also the user's\n"
3997 );
3998 assert_eq!(git_hook_block_for_visdom(&respelled, PRE_PUSH_MARKER), None);
4000 assert_eq!(
4001 git_hook_block_for_visdom(
4002 "#!/bin/sh\n# tracevault:post-commit\ntracevault commit-push 2>/dev/null &\n",
4003 POST_COMMIT_MARKER
4004 )
4005 .as_deref(),
4006 Some("#!/bin/sh\n# visdom:post-commit\nvisdom trace commit-push 2>/dev/null &\n")
4007 );
4008 }
4009
4010 #[test]
4011 fn every_plugin_can_be_written_to_run_visdom() {
4012 for source in [AMP_PLUGIN_INDEX, OPENCODE_PLUGIN_INDEX, GSD_EXT_INDEX_TS] {
4013 assert_eq!(plugin_source(source, false), source);
4014 let visdom = plugin_source(source, true);
4015 assert_ne!(visdom, source);
4016 assert!(
4017 PLUGIN_CLI_LINES
4018 .iter()
4019 .any(|(_, line)| visdom.contains(line)),
4020 "the plugin has no CLI line to rewrite"
4021 );
4022 assert!(
4024 !visdom.contains("spawn(\"tracevault\"") && !visdom.contains("spawn('tracevault'")
4025 );
4026 }
4027 let dir = tempfile::tempdir().unwrap();
4028 let path = dir.path().join("index.ts");
4029 fs::write(&path, plugin_source(AMP_PLUGIN_INDEX, true)).unwrap();
4030 write_plugin(&path, AMP_PLUGIN_INDEX).unwrap();
4032 assert!(plugin_runs_visdom(&path));
4033 }
4034
4035 #[test]
4036 fn the_workspace_block_keeps_naming_visdom_once_it_does() {
4037 let visdom_block = workspace_block(GLOBAL_CLAUDE_MD_BLOCK, true);
4038 assert!(visdom_block.contains("`visdom trace repo switch <path>`"));
4039 assert!(!visdom_block.contains("`tracevault "));
4040 let content = format!("# Mine\n\n{visdom_block}\nmore\n");
4041 assert_eq!(replace_managed_block(&content), content);
4042 let old = workspace_block(PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS[0], true);
4045 assert_eq!(
4046 replace_managed_block(&format!("# Mine\n\n{old}")),
4047 format!("# Mine\n\n{visdom_block}")
4048 );
4049 }
4050
4051 #[test]
4052 fn a_users_own_tracing_command_in_a_hook_is_not_ours() {
4053 let own = |command: &str| serde_json::json!({"type": "command", "command": command});
4054 assert!(is_tracevault_hook(&own("visdom trace stream --event stop")));
4055 assert!(is_tracevault_hook(&own("tracevault session-start")));
4056 assert!(!is_tracevault_hook(&own("visdom trace flush")));
4057 assert!(!is_tracevault_hook(&own("tracevault streamer")));
4058 assert!(!is_tracevault_hook(&own("visdom doctor")));
4059
4060 let mut settings = serde_json::json!({"hooks": {
4061 "PreCompact": [{"matcher": "", "hooks": [own("visdom trace flush")]}],
4062 "Stop": [{"matcher": "", "hooks": [own("tracevault flush"), own("tracevault stream --event stop")]}],
4063 }});
4064 merge_hooks(
4065 &mut settings,
4066 &tracevault_hooks(),
4067 Path::new("settings.json"),
4068 )
4069 .unwrap();
4070
4071 let all: Vec<_> = hooks_in(&settings["hooks"])
4072 .filter_map(hook_command)
4073 .collect();
4074 assert!(all.contains(&"visdom trace flush"), "{all:?}");
4075 assert!(all.contains(&"tracevault flush"), "{all:?}");
4076 assert!(all.contains(&"tracevault stream --event stop"), "{all:?}");
4078 let respelled = hooks_spelled(&settings["hooks"], true);
4080 let all: Vec<_> = hooks_in(&respelled).filter_map(hook_command).collect();
4081 assert!(all.contains(&"tracevault flush"), "{all:?}");
4082 assert!(all.contains(&"visdom trace stream --event stop"), "{all:?}");
4083 }
4084
4085 #[test]
4086 fn a_users_line_right_after_a_git_hook_block_is_left_alone() {
4087 let hook = "#!/bin/sh\n# tracevault:post-commit\ntracevault commit-push 2>/dev/null &\n\
4088 custom-tracevault check\ntracevault check-something\ntracevault sync\n";
4089 assert_eq!(
4090 git_hook_block_for_visdom(hook, POST_COMMIT_MARKER).as_deref(),
4091 Some(
4092 "#!/bin/sh\n# visdom:post-commit\nvisdom trace commit-push 2>/dev/null &\n\
4093 custom-tracevault check\ntracevault check-something\ntracevault sync\n"
4094 )
4095 );
4096 }
4097
4098 #[test]
4099 fn the_gsd_extension_is_named_after_the_directory_it_is_installed_in() {
4100 let visdom = Path::new("/cfg/visdom/gsd-extension");
4101 let earlier = Path::new("/cfg/tracevault/gsd-extension");
4102 assert!(gsd_extension_file(GSD_EXT_MANIFEST_JSON, visdom).contains("\"id\": \"visdom\""));
4103 assert!(gsd_extension_file(GSD_EXT_PACKAGE_JSON, visdom).contains("\"name\": \"visdom\""));
4104 assert_eq!(
4105 gsd_extension_file(GSD_EXT_MANIFEST_JSON, earlier),
4106 GSD_EXT_MANIFEST_JSON
4107 );
4108 assert_eq!(
4109 gsd_extension_file(GSD_EXT_PACKAGE_JSON, earlier),
4110 GSD_EXT_PACKAGE_JSON
4111 );
4112 }
4113
4114 #[test]
4115 fn markers_are_recognised_under_either_spelling() {
4116 assert_eq!(marker_for_visdom(PRE_PUSH_MARKER), "# visdom:enforce");
4117 assert!(has_marker(
4118 "#!/bin/sh\n# visdom:post-commit\n",
4119 POST_COMMIT_MARKER
4120 ));
4121 assert!(has_marker(
4122 "#!/bin/sh\n# tracevault:post-commit\n",
4123 POST_COMMIT_MARKER
4124 ));
4125 assert!(!has_marker(
4126 "#!/bin/sh\n# visdom:enforce\n",
4127 POST_COMMIT_MARKER
4128 ));
4129 let old = PREVIOUS_GLOBAL_CLAUDE_MD_BLOCKS.last().unwrap();
4132 assert!(old.contains("## TraceVault (workspace mode)"));
4133 assert_eq!(replace_managed_block(old), GLOBAL_CLAUDE_MD_BLOCK);
4134 let old_visdom = old.replace("`tracevault ", "`visdom trace ");
4135 let now = replace_managed_block(&old_visdom);
4136 assert!(
4137 now.starts_with("<!-- visdom:workspace-mode -->\n## Visdom (workspace mode)"),
4138 "{now}"
4139 );
4140 assert!(!now.contains("tracevault"), "{now}");
4141 }
4142}