1use crate::api_client::ApiClient;
2use crate::config::{user_config_path_in, TracevaultConfig, UserContext};
3use crate::context::Context;
4use std::fs;
5use std::io::{self, BufRead, IsTerminal, Write};
6use std::path::{Path, PathBuf};
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
10pub enum ClaudeSettingsTarget {
11 Shared,
13 Local,
15}
16
17impl ClaudeSettingsTarget {
18 pub fn filename(self) -> &'static str {
19 match self {
20 ClaudeSettingsTarget::Shared => "settings.json",
21 ClaudeSettingsTarget::Local => "settings.local.json",
22 }
23 }
24
25 pub fn gitignore_entry(self) -> &'static str {
26 match self {
27 ClaudeSettingsTarget::Shared => ".claude/settings.json",
28 ClaudeSettingsTarget::Local => ".claude/settings.local.json",
29 }
30 }
31}
32
33fn resolve_claude_target(
37 explicit: Option<ClaudeSettingsTarget>,
38) -> io::Result<ClaudeSettingsTarget> {
39 if let Some(target) = explicit {
40 return Ok(target);
41 }
42 if !io::stdin().is_terminal() {
43 return Ok(ClaudeSettingsTarget::Shared);
44 }
45
46 let stdout = io::stdout();
47 let mut stdout = stdout.lock();
48 write!(
49 stdout,
50 "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
51 )?;
52 stdout.flush()?;
53
54 let mut line = String::new();
55 io::stdin().lock().read_line(&mut line)?;
56 let answer = line.trim().to_lowercase();
57 Ok(match answer.as_str() {
58 "l" | "local" => ClaudeSettingsTarget::Local,
59 _ => ClaudeSettingsTarget::Shared,
60 })
61}
62
63pub fn git_remote_url(project_root: &Path) -> Option<String> {
64 std::process::Command::new("git")
65 .args(["remote", "get-url", "origin"])
66 .current_dir(project_root)
67 .output()
68 .ok()
69 .filter(|o| o.status.success())
70 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
71 .filter(|s| !s.is_empty())
72}
73
74fn parse_github_org(remote_url: &str) -> Option<String> {
75 if let Some(path) = remote_url.strip_prefix("git@github.com:") {
77 return path.split('/').next().map(String::from);
78 }
79 if let Some(path) = remote_url
81 .strip_prefix("https://github.com/")
82 .or_else(|| remote_url.strip_prefix("http://github.com/"))
83 {
84 return path.split('/').next().map(String::from);
85 }
86 None
87}
88
89fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
97 let output = std::process::Command::new("git")
98 .args(["rev-parse", "--git-dir", "--git-common-dir"])
99 .current_dir(dir)
100 .output()
101 .ok()?;
102 if !output.status.success() {
103 return None;
104 }
105 let stdout = String::from_utf8(output.stdout).ok()?;
106 let mut lines = stdout.lines();
107 let git_dir = lines.next()?.trim();
108 let git_common_dir = lines.next()?.trim();
109
110 let git_dir = dir.join(git_dir).canonicalize().ok()?;
113 let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
114
115 if git_dir == git_common_dir {
116 None } else {
118 git_common_dir.parent().map(Path::to_path_buf)
119 }
120}
121
122pub fn validate_init_flags(
128 agent: crate::agent::Agent,
129 claude_settings_set: bool,
130) -> Result<(), String> {
131 if matches!(agent, crate::agent::Agent::Codex) && claude_settings_set {
132 return Err("--claude-settings only applies to --agent claude-code".to_string());
133 }
134 Ok(())
135}
136
137pub async fn init_in_directory(
138 project_root: &Path,
139 server_url: Option<&str>,
140 claude_settings: Option<ClaudeSettingsTarget>,
141 no_gitignore: bool,
142 user_context: UserContext,
143 agent: crate::agent::Agent,
144) -> Result<String, io::Error> {
145 if !project_root.join(".git").exists() {
147 return Err(io::Error::new(
148 io::ErrorKind::NotFound,
149 "Not a git repository. Run 'git init' first.",
150 ));
151 }
152
153 if let Some(primary) = linked_worktree_primary(project_root) {
159 return Err(io::Error::new(
160 io::ErrorKind::Unsupported,
161 format!(
162 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
163 cd there and run it again — all worktrees share the primary's .tracevault/.",
164 primary.display()
165 ),
166 ));
167 }
168
169 let (claude_target, hook_gitignore_entry): (Option<ClaudeSettingsTarget>, String) = match agent
172 {
173 crate::agent::Agent::ClaudeCode => {
174 let target = resolve_claude_target(claude_settings)?;
175 (Some(target), target.gitignore_entry().to_string())
176 }
177 crate::agent::Agent::Codex => (None, ".codex/hooks.json".to_string()),
178 };
179
180 let config_dir = TracevaultConfig::config_dir(project_root);
182 fs::create_dir_all(&config_dir)?;
183 fs::create_dir_all(config_dir.join("sessions"))?;
184 fs::create_dir_all(config_dir.join("cache"))?;
185 TracevaultConfig::ensure_gitignore(&config_dir)?;
188
189 if !no_gitignore {
191 update_root_gitignore(project_root, &hook_gitignore_entry)?;
192 }
193
194 let remote_url = git_remote_url(project_root);
196 if remote_url.is_none() {
197 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
198 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
199 }
200
201 let org_slug = remote_url.as_deref().and_then(parse_github_org);
203
204 let mut config = TracevaultConfig::default();
206 if let Some(url) = server_url {
207 config.server_url = Some(url.to_string());
208 }
209 config.org_slug = org_slug.clone();
210 config.user_context = Some(user_context);
211 fs::write(
212 TracevaultConfig::config_path(project_root),
213 config.to_toml(),
214 )?;
215
216 match agent {
218 crate::agent::Agent::ClaudeCode => {
219 let target =
221 claude_target.expect("claude settings target is resolved for the Claude agent");
222 install_claude_hooks(project_root, target)?;
223 }
224 crate::agent::Agent::Codex => install_codex_hooks(project_root)?,
225 }
226
227 install_git_hook(project_root)?;
229 install_post_commit_hook(project_root)?;
230
231 let detected = crate::hooks::detect_tools(project_root);
233 for tool in &detected {
234 println!(" Detected: {}", tool.name());
235 }
236
237 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
238 let effective_url = server_url.map(String::from).or(resolved_url);
239
240 if resolved_token.is_none() {
241 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
242 } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
243 let client = ApiClient::new(&url, resolved_token.as_deref());
244 let repo_name = git_repo_name(project_root);
245
246 match client
247 .register_repo(
248 &slug,
249 crate::api_client::RegisterRepoRequest {
250 repo_name,
251 github_url: Some(remote),
252 },
253 )
254 .await
255 {
256 Ok(resp) => {
257 println!("Repo registered on server (id: {})", resp.repo_id);
258 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
260 cfg.repo_id = Some(resp.repo_id.to_string());
261 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
262 }
263 }
264 Err(e) => {
265 let msg = e.to_string();
266 if msg.contains("404") {
267 eprintln!("Warning: organization '{}' not found on the server.", slug);
268 eprintln!(
269 "Create it first at your TraceVault instance, then run 'tracevault sync'."
270 );
271 } else if msg.contains("403") {
272 eprintln!("Warning: you are not a member of organization '{}'.", slug);
273 } else {
274 eprintln!("Warning: could not register repo on server: {e}");
275 }
276 }
277 }
278 }
279
280 Ok(hook_gitignore_entry)
281}
282
283fn update_root_gitignore(project_root: &Path, settings_entry: &str) -> Result<(), io::Error> {
284 let path = project_root.join(".gitignore");
285 let existing = if path.exists() {
286 fs::read_to_string(&path)?
287 } else {
288 String::new()
289 };
290
291 let needed: Vec<&str> = [".tracevault/", settings_entry]
295 .iter()
296 .copied()
297 .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
298 .collect();
299
300 if needed.is_empty() {
301 return Ok(());
302 }
303
304 let mut content = existing;
305 if !content.is_empty() && !content.ends_with('\n') {
306 content.push('\n');
307 }
308 content.push_str("\n# TraceVault — local only, do not commit\n");
309 for entry in needed {
310 content.push_str(entry);
311 content.push('\n');
312 }
313
314 fs::write(path, content)
315}
316
317fn git_repo_name(project_root: &Path) -> String {
318 std::process::Command::new("git")
319 .args(["rev-parse", "--show-toplevel"])
320 .current_dir(project_root)
321 .output()
322 .ok()
323 .filter(|o| o.status.success())
324 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
325 .as_deref()
326 .and_then(|p| p.rsplit('/').next())
327 .map(String::from)
328 .unwrap_or_else(|| "unknown".into())
329}
330
331const HOOK_MARKER: &str = "# tracevault:enforce";
332const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
333
334fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
335 let hooks_dir = project_root.join(".git/hooks");
336 fs::create_dir_all(&hooks_dir)?;
337
338 let hook_path = hooks_dir.join("pre-push");
339 let tracevault_block = format!(
340 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
341 );
342
343 if hook_path.exists() {
344 let existing = fs::read_to_string(&hook_path)?;
345
346 if existing.contains(HOOK_MARKER) {
348 return Ok(());
349 }
350
351 if existing.contains(OLD_HOOK_MARKER) {
353 let mut new_content = String::new();
354 let mut skip = false;
355 for line in existing.lines() {
356 if line.contains(OLD_HOOK_MARKER) {
357 skip = true;
358 continue;
359 }
360 if skip {
361 if line.starts_with("tracevault ") {
363 continue;
364 }
365 skip = false;
366 }
367 new_content.push_str(line);
368 new_content.push('\n');
369 }
370 if !new_content.ends_with('\n') {
371 new_content.push('\n');
372 }
373 new_content.push_str(&tracevault_block);
374 fs::write(&hook_path, new_content)?;
375 } else {
376 let mut content = existing;
378 if !content.ends_with('\n') {
379 content.push('\n');
380 }
381 content.push_str(&tracevault_block);
382 fs::write(&hook_path, content)?;
383 }
384 } else {
385 let content = format!("#!/bin/sh\n{tracevault_block}");
386 fs::write(&hook_path, content)?;
387 }
388
389 #[cfg(unix)]
391 {
392 use std::os::unix::fs::PermissionsExt;
393 let mut perms = fs::metadata(&hook_path)?.permissions();
394 perms.set_mode(0o755);
395 fs::set_permissions(&hook_path, perms)?;
396 }
397
398 Ok(())
399}
400
401const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
402
403fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
404 let hooks_dir = project_root.join(".git/hooks");
405 fs::create_dir_all(&hooks_dir)?;
406
407 let hook_path = hooks_dir.join("post-commit");
408 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
409
410 if hook_path.exists() {
411 let existing = fs::read_to_string(&hook_path)?;
412
413 if existing.contains(POST_COMMIT_MARKER) {
414 return Ok(());
415 }
416
417 let mut content = existing;
418 if !content.ends_with('\n') {
419 content.push('\n');
420 }
421 content.push_str(&tracevault_block);
422 fs::write(&hook_path, content)?;
423 } else {
424 let content = format!("#!/bin/sh\n{tracevault_block}");
425 fs::write(&hook_path, content)?;
426 }
427
428 #[cfg(unix)]
429 {
430 use std::os::unix::fs::PermissionsExt;
431 let mut perms = fs::metadata(&hook_path)?.permissions();
432 perms.set_mode(0o755);
433 fs::set_permissions(&hook_path, perms)?;
434 }
435
436 Ok(())
437}
438
439fn install_claude_hooks(
440 project_root: &Path,
441 target: ClaudeSettingsTarget,
442) -> Result<(), io::Error> {
443 let claude_dir = project_root.join(".claude");
444 fs::create_dir_all(&claude_dir)?;
445
446 let filename = target.filename();
447 let settings_path = claude_dir.join(filename);
448 let mut settings: serde_json::Value = if settings_path.exists() {
449 let content = fs::read_to_string(&settings_path)?;
450 serde_json::from_str(&content).map_err(|e| {
451 io::Error::new(
452 io::ErrorKind::InvalidData,
453 format!("Failed to parse .claude/{filename}: {e}"),
454 )
455 })?
456 } else {
457 serde_json::json!({})
458 };
459
460 let hooks = tracevault_hooks();
461
462 let settings_obj = settings.as_object_mut().ok_or_else(|| {
464 io::Error::new(
465 io::ErrorKind::InvalidData,
466 format!(".claude/{filename} is not a JSON object"),
467 )
468 })?;
469
470 settings_obj.insert("hooks".to_string(), hooks);
471
472 let formatted = serde_json::to_string_pretty(&settings)
473 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
474 fs::write(&settings_path, formatted)?;
475
476 Ok(())
477}
478
479pub fn tracevault_hooks() -> serde_json::Value {
480 serde_json::json!({
481 "PreToolUse": [{
482 "matcher": "Write|Edit|Bash",
483 "hooks": [{
484 "type": "command",
485 "command": "tracevault stream --event pre-tool-use",
486 "timeout": 10,
487 "statusMessage": "TraceVault: streaming pre-tool event"
488 }]
489 }],
490 "PostToolUse": [{
491 "matcher": "",
492 "hooks": [{
493 "type": "command",
494 "command": "tracevault stream --event post-tool-use",
495 "timeout": 10,
496 "statusMessage": "TraceVault: streaming post-tool event"
497 }]
498 }],
499 "Notification": [{
500 "matcher": "",
501 "hooks": [{
502 "type": "command",
503 "command": "tracevault stream --event notification",
504 "timeout": 10,
505 "statusMessage": "TraceVault: streaming notification"
506 }]
507 }],
508 "Stop": [{
509 "matcher": "",
510 "hooks": [{
511 "type": "command",
512 "command": "tracevault stream --event stop",
513 "timeout": 10,
514 "statusMessage": "TraceVault: finalizing session"
515 }]
516 }],
517 "SessionStart": [{
518 "matcher": "",
519 "hooks": [{
520 "type": "command",
521 "command": "tracevault session-start",
522 "timeout": 10,
523 "statusMessage": "TraceVault: session start"
524 }]
525 }],
526 "UserPromptSubmit": [{
527 "matcher": "",
528 "hooks": [{
529 "type": "command",
530 "command": "tracevault user-prompt",
531 "timeout": 10,
532 "statusMessage": "TraceVault: policy reinforcement"
533 }]
534 }]
535 })
536}
537
538pub fn codex_hooks() -> serde_json::Value {
549 serde_json::json!({
550 "SessionStart": [{
551 "matcher": "",
552 "hooks": [{ "type": "command", "command": "tracevault session-start", "timeout": 10, "statusMessage": "TraceVault: session start" }]
553 }],
554 "UserPromptSubmit": [{
555 "matcher": "",
556 "hooks": [{ "type": "command", "command": "tracevault user-prompt", "timeout": 10, "statusMessage": "TraceVault: policy reinforcement" }]
557 }],
558 "PostToolUse": [{
559 "matcher": "",
560 "hooks": [{ "type": "command", "command": "tracevault stream --event post-tool-use --agent codex", "timeout": 10, "statusMessage": "TraceVault: streaming post-tool event" }]
561 }],
562 "Stop": [{
563 "matcher": "",
564 "hooks": [{ "type": "command", "command": "tracevault stream --event stop --agent codex", "timeout": 10, "statusMessage": "TraceVault: finalizing session" }]
565 }]
566 })
567}
568
569fn merge_hooks_into_file(hooks_path: &Path, ours: &serde_json::Value) -> io::Result<()> {
579 if hooks_path
584 .components()
585 .any(|c| c == std::path::Component::ParentDir)
586 {
587 return Err(io::Error::new(
588 io::ErrorKind::InvalidInput,
589 format!("refusing to use path with '..': {}", hooks_path.display()),
590 ));
591 }
592 let mut root: serde_json::Value = if hooks_path.exists() {
593 let content = fs::read_to_string(hooks_path)?;
594 serde_json::from_str(&content).map_err(|e| {
595 io::Error::new(
596 io::ErrorKind::InvalidData,
597 format!("Failed to parse {}: {e}", hooks_path.display()),
598 )
599 })?
600 } else {
601 serde_json::json!({})
602 };
603
604 merge_hooks(&mut root, ours, hooks_path)?;
605
606 let formatted = serde_json::to_string_pretty(&root).map_err(|e| {
607 io::Error::other(format!("Failed to serialize {}: {e}", hooks_path.display()))
608 })?;
609 let tmp = hooks_path.with_extension("json.tmp");
610 fs::write(&tmp, formatted)?;
611 fs::rename(&tmp, hooks_path)?;
612 Ok(())
613}
614
615pub fn install_codex_hooks(project_root: &Path) -> io::Result<()> {
619 let codex_dir = project_root.join(".codex");
620 fs::create_dir_all(&codex_dir)?;
621 merge_hooks_into_file(&codex_dir.join("hooks.json"), &codex_hooks())
622}
623
624pub fn install_global_codex_hooks(codex_dir: &Path) -> io::Result<()> {
631 fs::create_dir_all(codex_dir)?;
632 let base = codex_dir.canonicalize()?;
634 merge_hooks_into_file(&safe_join(&base, "hooks.json")?, &codex_hooks())?;
635 append_workspace_md(&safe_join(&base, "AGENTS.md")?)
636}
637
638const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
642
643const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
644<!-- tracevault:workspace-mode -->
645## TraceVault (workspace mode)
646You may be running detached from any single repository. Before working on a repo, run
647`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
648output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
649already be registered with TraceVault.
650";
651
652fn append_workspace_md(md_path: &Path) -> io::Result<()> {
658 if md_path
660 .components()
661 .any(|c| c == std::path::Component::ParentDir)
662 {
663 return Err(io::Error::new(
664 io::ErrorKind::InvalidInput,
665 format!("refusing to use path with '..': {}", md_path.display()),
666 ));
667 }
668 let existing = if md_path.exists() {
669 fs::read_to_string(md_path)?
670 } else {
671 String::new()
672 };
673 if existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
674 return Ok(());
675 }
676 let mut content = existing;
677 if !content.is_empty() && !content.ends_with('\n') {
678 content.push('\n');
679 }
680 if !content.is_empty() {
681 content.push('\n');
682 }
683 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
684 fs::write(md_path, content)
685}
686
687fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
691 let joined = base.join(name);
692 if joined.parent() != Some(base) {
693 return Err(io::Error::new(
694 io::ErrorKind::InvalidInput,
695 format!(
696 "refusing to access path outside {}: {}",
697 base.display(),
698 joined.display()
699 ),
700 ));
701 }
702 Ok(joined)
703}
704
705fn merge_hooks(
718 settings: &mut serde_json::Value,
719 ours: &serde_json::Value,
720 path: &Path,
721) -> io::Result<()> {
722 if settings.is_null() {
723 *settings = serde_json::json!({});
724 }
725 let settings_obj = settings.as_object_mut().ok_or_else(|| {
726 io::Error::new(
727 io::ErrorKind::InvalidData,
728 format!("{} is not a JSON object", path.display()),
729 )
730 })?;
731
732 let hooks_value = settings_obj
733 .entry("hooks")
734 .or_insert_with(|| serde_json::json!({}));
735 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
736 io::Error::new(
737 io::ErrorKind::InvalidData,
738 format!("{} \"hooks\" key is not a JSON object", path.display()),
739 )
740 })?;
741
742 let Some(ours_obj) = ours.as_object() else {
743 return Ok(());
744 };
745
746 for (event, our_array) in ours_obj {
747 let Some(our_entries) = our_array.as_array() else {
748 continue;
749 };
750
751 let existing_value = hooks_obj
752 .entry(event.clone())
753 .or_insert_with(|| serde_json::json!([]));
754 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
755 io::Error::new(
756 io::ErrorKind::InvalidData,
757 format!(
758 "{} \"hooks\".\"{event}\" is not a JSON array",
759 path.display()
760 ),
761 )
762 })?;
763
764 for our_entry in our_entries {
765 let our_command = entry_command(our_entry);
766 let already_present = existing_array
767 .iter()
768 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
769 if !already_present {
770 existing_array.push(our_entry.clone());
771 }
772 }
773 }
774
775 Ok(())
776}
777
778fn entry_command(entry: &serde_json::Value) -> Option<&str> {
781 entry.get("hooks")?.get(0)?.get("command")?.as_str()
782}
783
784fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
789 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
790 return false;
791 };
792 hooks
793 .iter()
794 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
795}
796
797pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
803 fs::create_dir_all(claude_dir)?;
804
805 let base = claude_dir.canonicalize()?;
808
809 merge_hooks_into_file(&safe_join(&base, "settings.json")?, &tracevault_hooks())?;
811
812 append_workspace_md(&safe_join(&base, "CLAUDE.md")?)
814}
815
816pub fn write_global_user_config_in(
826 config_root: &Path,
827 requested: Option<UserContext>,
828) -> io::Result<Option<PathBuf>> {
829 fs::create_dir_all(config_root)?;
830 let mut config = crate::config::try_load_user_config_in(config_root)
832 .ok()
833 .flatten()
834 .unwrap_or_default();
835 let user_context = requested
837 .or_else(|| config.user_context.clone())
838 .unwrap_or(UserContext::Toggle(true));
839 let active = user_context
840 .resolve()
841 .map(|_| user_context.path_in(config_root));
842 config.user_context = Some(user_context);
843 fs::write(user_config_path_in(config_root), config.to_toml())?;
844 if let Some(ref ctx_path) = active {
845 if !ctx_path.exists() {
846 Context::default().save_to(ctx_path)?;
847 }
848 }
849 Ok(active)
850}
851
852#[cfg(test)]
853mod tests {
854 use super::*;
855
856 #[test]
857 fn linked_worktree_primary_detects_linked_and_primary() {
858 let tmp = tempfile::tempdir().unwrap();
859 let repo = tmp.path().join("repo");
860 let wt = tmp.path().join("linked-wt");
861 std::fs::create_dir_all(&repo).unwrap();
862 crate::test_helpers::init_git_repo(&repo);
863 crate::test_helpers::add_worktree(&repo, &wt);
864
865 assert!(
867 linked_worktree_primary(&repo).is_none(),
868 "primary checkout must not be flagged as a linked worktree"
869 );
870 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
872 assert_eq!(
873 primary.canonicalize().unwrap(),
874 repo.canonicalize().unwrap(),
875 "must resolve to the primary repo root"
876 );
877 }
878
879 #[test]
880 fn linked_worktree_primary_none_for_non_git() {
881 let tmp = tempfile::tempdir().unwrap();
882 assert!(
883 linked_worktree_primary(tmp.path()).is_none(),
884 "a non-git directory is not a linked worktree"
885 );
886 }
887
888 #[test]
889 fn parse_github_org_ssh() {
890 assert_eq!(
891 parse_github_org("git@github.com:myorg/myrepo.git"),
892 Some("myorg".into())
893 );
894 }
895
896 #[test]
897 fn parse_github_org_https() {
898 assert_eq!(
899 parse_github_org("https://github.com/myorg/myrepo"),
900 Some("myorg".into())
901 );
902 }
903
904 #[test]
905 fn parse_github_org_non_github_returns_none() {
906 assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
907 }
908
909 #[test]
910 fn parse_github_org_invalid() {
911 assert_eq!(parse_github_org("not-a-url"), None);
912 }
913
914 #[test]
915 fn merge_hooks_into_empty_settings_adds_all_our_events() {
916 let mut settings = serde_json::json!({});
917 let ours = tracevault_hooks();
918 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
919
920 let hooks = settings.get("hooks").unwrap();
921 for event in [
922 "PreToolUse",
923 "PostToolUse",
924 "Notification",
925 "Stop",
926 "SessionStart",
927 "UserPromptSubmit",
928 ] {
929 assert!(hooks.get(event).is_some(), "missing event {event}");
930 }
931 }
932
933 #[test]
934 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
935 let mut settings = serde_json::json!({
936 "model": "opus",
937 "hooks": {
938 "PreToolUse": [{
939 "matcher": "",
940 "hooks": [{ "type": "command", "command": "my-own-hook" }]
941 }]
942 }
943 });
944 let ours = tracevault_hooks();
945 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
946
947 assert_eq!(settings.get("model").unwrap(), "opus");
949
950 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
951 assert_eq!(pre_tool_use.len(), 2);
953 let commands: Vec<&str> = pre_tool_use
954 .iter()
955 .map(|e| entry_command(e).unwrap())
956 .collect();
957 assert!(commands.contains(&"my-own-hook"));
958 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
959
960 assert!(settings["hooks"]["SessionStart"].is_array());
962 }
963
964 #[test]
965 fn merge_hooks_is_idempotent() {
966 let mut settings = serde_json::json!({});
967 let ours = tracevault_hooks();
968 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
969 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
970
971 for event in [
972 "PreToolUse",
973 "PostToolUse",
974 "Notification",
975 "Stop",
976 "SessionStart",
977 "UserPromptSubmit",
978 ] {
979 let arr = settings["hooks"][event].as_array().unwrap();
980 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
981 }
982 }
983
984 #[test]
985 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
986 let mut settings = serde_json::json!({
990 "hooks": {
991 "PreToolUse": [{
992 "matcher": "Write|Edit|Bash",
993 "hooks": [
994 { "type": "command", "command": "other" },
995 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
996 ]
997 }]
998 }
999 });
1000 let ours = tracevault_hooks();
1001 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
1002
1003 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
1004 assert_eq!(
1005 pre_tool_use.len(),
1006 1,
1007 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
1008 );
1009 }
1010
1011 #[test]
1012 fn merge_hooks_errors_on_non_object_top_level() {
1013 let mut settings = serde_json::json!([1, 2, 3]);
1014 let ours = tracevault_hooks();
1015 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1016 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1017 assert!(err.to_string().contains("settings.json"));
1018 }
1019
1020 #[test]
1021 fn merge_hooks_errors_on_non_object_top_level_number() {
1022 let mut settings = serde_json::json!(42);
1023 let ours = tracevault_hooks();
1024 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1025 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1026 }
1027
1028 #[test]
1029 fn merge_hooks_errors_on_non_object_hooks() {
1030 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
1031 let ours = tracevault_hooks();
1032 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1033 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1034 assert!(err.to_string().contains("hooks"));
1035 }
1036
1037 #[test]
1038 fn merge_hooks_errors_on_non_array_event_value() {
1039 let mut settings = serde_json::json!({
1040 "hooks": {
1041 "PreToolUse": "not-an-array"
1042 }
1043 });
1044 let ours = tracevault_hooks();
1045 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
1046 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1047 assert!(err.to_string().contains("PreToolUse"));
1048 }
1049
1050 #[test]
1051 fn install_global_hooks_writes_settings_and_claude_md() {
1052 let tmp = tempfile::tempdir().unwrap();
1053 let claude_dir = tmp.path().join(".claude");
1054
1055 install_global_hooks(&claude_dir).unwrap();
1056
1057 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1058 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1059 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
1060 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
1061 }
1062
1063 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1064 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1065 }
1066
1067 #[test]
1068 fn install_global_hooks_is_idempotent() {
1069 let tmp = tempfile::tempdir().unwrap();
1070 let claude_dir = tmp.path().join(".claude");
1071
1072 install_global_hooks(&claude_dir).unwrap();
1073 install_global_hooks(&claude_dir).unwrap();
1074
1075 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1076 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1077 for event in [
1078 "PreToolUse",
1079 "PostToolUse",
1080 "Notification",
1081 "Stop",
1082 "SessionStart",
1083 "UserPromptSubmit",
1084 ] {
1085 let arr = settings["hooks"][event].as_array().unwrap();
1086 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
1087 }
1088
1089 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1090 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
1091 assert_eq!(
1092 marker_count, 1,
1093 "CLAUDE.md marker should appear exactly once"
1094 );
1095 }
1096
1097 #[test]
1098 fn install_global_hooks_preserves_existing_claude_md_content() {
1099 let tmp = tempfile::tempdir().unwrap();
1100 let claude_dir = tmp.path().join(".claude");
1101 fs::create_dir_all(&claude_dir).unwrap();
1102 fs::write(
1103 claude_dir.join("CLAUDE.md"),
1104 "# My existing notes\nSome content.\n",
1105 )
1106 .unwrap();
1107
1108 install_global_hooks(&claude_dir).unwrap();
1109
1110 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
1111 assert!(claude_md.contains("# My existing notes"));
1112 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
1113 }
1114
1115 #[test]
1116 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
1117 let tmp = tempfile::tempdir().unwrap();
1118 let claude_dir = tmp.path().join(".claude");
1119
1120 install_global_hooks(&claude_dir).unwrap();
1121
1122 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
1123 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
1124 assert!(settings["hooks"].get("SessionStart").is_some());
1125
1126 let leftover = fs::read_dir(&claude_dir)
1127 .unwrap()
1128 .filter_map(|e| e.ok())
1129 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1130 assert!(
1131 !leftover,
1132 "no settings.json.tmp should remain after install"
1133 );
1134 }
1135
1136 #[test]
1137 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
1138 let tmp = tempfile::tempdir().unwrap();
1139 let claude_dir = tmp.path().join(".claude");
1140 fs::create_dir_all(&claude_dir).unwrap();
1141 let settings_path = claude_dir.join("settings.json");
1142 let original = "[1, 2, 3]";
1143 fs::write(&settings_path, original).unwrap();
1144
1145 let err = install_global_hooks(&claude_dir).unwrap_err();
1146 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1147
1148 let after = fs::read_to_string(&settings_path).unwrap();
1151 assert_eq!(after, original);
1152 let leftover = fs::read_dir(&claude_dir)
1153 .unwrap()
1154 .filter_map(|e| e.ok())
1155 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1156 assert!(!leftover, "no tmp file should be left behind on error");
1157 }
1158
1159 #[test]
1160 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
1161 let tmp = tempfile::tempdir().unwrap();
1162 let claude_dir = tmp.path().join(".claude");
1163 fs::create_dir_all(&claude_dir).unwrap();
1164 let settings_path = claude_dir.join("settings.json");
1165 let original = r#"{"hooks": "oops"}"#;
1166 fs::write(&settings_path, original).unwrap();
1167
1168 let err = install_global_hooks(&claude_dir).unwrap_err();
1169 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1170
1171 let after = fs::read_to_string(&settings_path).unwrap();
1172 assert_eq!(after, original);
1173 }
1174
1175 #[test]
1176 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1177 let tmp = tempfile::tempdir().unwrap();
1178 let claude_dir = tmp.path().join(".claude");
1179 fs::create_dir_all(&claude_dir).unwrap();
1180 let settings_path = claude_dir.join("settings.json");
1181 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1182 fs::write(&settings_path, original).unwrap();
1183
1184 let err = install_global_hooks(&claude_dir).unwrap_err();
1185 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1186
1187 let after = fs::read_to_string(&settings_path).unwrap();
1188 assert_eq!(after, original);
1189 }
1190
1191 #[test]
1192 fn safe_join_allows_direct_child_file() {
1193 let tmp = tempfile::tempdir().unwrap();
1194 let base = tmp.path();
1195 let result = safe_join(base, "settings.json").unwrap();
1196 assert_eq!(result.parent(), Some(base));
1197 assert_eq!(result.file_name().unwrap(), "settings.json");
1198 }
1199
1200 #[test]
1201 fn safe_join_rejects_path_traversal() {
1202 let tmp = tempfile::tempdir().unwrap();
1203 let base = tmp.path();
1204 let result = safe_join(base, "../evil");
1205 assert!(result.is_err());
1206 let err = result.unwrap_err();
1207 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1208 assert!(err.to_string().contains("refusing to access path outside"));
1209 }
1210
1211 #[test]
1212 fn safe_join_rejects_absolute_path() {
1213 let tmp = tempfile::tempdir().unwrap();
1214 let base = tmp.path();
1215 let result = safe_join(base, "/etc/passwd");
1216 assert!(result.is_err());
1219 }
1220
1221 #[test]
1222 fn write_global_user_config_enables_and_creates_context() {
1223 let root = tempfile::tempdir().unwrap();
1224 let active = write_global_user_config_in(root.path(), None).unwrap();
1225 let cfg = crate::config::try_load_user_config_in(root.path())
1226 .unwrap()
1227 .unwrap();
1228 assert_eq!(
1231 cfg.user_context.unwrap().resolve_in(root.path()),
1232 Some(crate::config::default_user_context_path_in(root.path()))
1233 );
1234 let ctx = crate::config::default_user_context_path_in(root.path());
1235 assert_eq!(active, Some(ctx.clone()));
1236 assert!(ctx.exists());
1237 }
1238
1239 #[test]
1240 fn write_global_user_config_can_disable() {
1241 let root = tempfile::tempdir().unwrap();
1242 let active = write_global_user_config_in(
1243 root.path(),
1244 Some(crate::config::UserContext::Toggle(false)),
1245 )
1246 .unwrap();
1247 let cfg = crate::config::try_load_user_config_in(root.path())
1248 .unwrap()
1249 .unwrap();
1250 assert!(matches!(
1251 cfg.user_context,
1252 Some(crate::config::UserContext::Toggle(false))
1253 ));
1254 assert_eq!(active, None, "disabled → no active context path");
1255 assert!(
1257 !crate::config::default_user_context_path_in(root.path()).exists(),
1258 "disabled user context must not create a context.json"
1259 );
1260 }
1261
1262 #[test]
1263 fn write_global_user_config_custom_path_seeds_that_file_only() {
1264 let root = tempfile::tempdir().unwrap();
1265 let custom = root.path().join("custom-ctx.json");
1266 let active = write_global_user_config_in(
1267 root.path(),
1268 Some(crate::config::UserContext::Path(
1269 custom.to_string_lossy().into_owned(),
1270 )),
1271 )
1272 .unwrap();
1273 assert_eq!(active, Some(custom.clone()));
1274 assert!(custom.exists(), "the configured custom path must be seeded");
1275 assert!(
1276 !crate::config::default_user_context_path_in(root.path()).exists(),
1277 "the default context.json must NOT be created when a custom path is configured"
1278 );
1279 }
1280
1281 #[test]
1282 fn write_global_user_config_preserves_existing_on_rerun_without_flags() {
1283 let root = tempfile::tempdir().unwrap();
1284 let custom = root.path().join("custom-ctx.json");
1285 write_global_user_config_in(
1287 root.path(),
1288 Some(crate::config::UserContext::Path(
1289 custom.to_string_lossy().into_owned(),
1290 )),
1291 )
1292 .unwrap();
1293 let active = write_global_user_config_in(root.path(), None).unwrap();
1295 assert_eq!(
1296 active,
1297 Some(custom.clone()),
1298 "re-run without flags must preserve the custom path"
1299 );
1300 let cfg = crate::config::try_load_user_config_in(root.path())
1301 .unwrap()
1302 .unwrap();
1303 assert_eq!(cfg.user_context.unwrap().path_in(root.path()), custom);
1304 }
1305
1306 #[test]
1307 fn install_global_codex_hooks_writes_and_is_idempotent() {
1308 let tmp = tempfile::tempdir().unwrap();
1309 let codex_dir = tmp.path().join(".codex");
1310
1311 install_global_codex_hooks(&codex_dir).unwrap();
1312 install_global_codex_hooks(&codex_dir).unwrap();
1313
1314 let v: serde_json::Value =
1315 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1316 .unwrap();
1317 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1318 let arr = v["hooks"][event].as_array().unwrap();
1319 assert_eq!(arr.len(), 1, "event {event} must not be duplicated");
1320 }
1321 assert!(v["hooks"].get("PreToolUse").is_none());
1322 let agents_md = fs::read_to_string(codex_dir.join("AGENTS.md")).unwrap();
1324 assert_eq!(
1325 agents_md.matches(GLOBAL_CLAUDE_MD_MARKER).count(),
1326 1,
1327 "AGENTS.md workspace-mode block must appear exactly once"
1328 );
1329 let leftover = fs::read_dir(&codex_dir)
1331 .unwrap()
1332 .filter_map(|e| e.ok())
1333 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
1334 assert!(!leftover);
1335 }
1336
1337 #[test]
1338 fn codex_hooks_has_expected_events_and_commands() {
1339 let h = codex_hooks();
1340 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1341 assert!(h.get(event).is_some(), "missing codex event {event}");
1342 }
1343 assert!(h.get("PreToolUse").is_none());
1347 assert!(h.get("Notification").is_none());
1348 let cmd = |e: &str| h[e][0]["hooks"][0]["command"].as_str().unwrap().to_string();
1350 assert_eq!(
1351 cmd("PostToolUse"),
1352 "tracevault stream --event post-tool-use --agent codex"
1353 );
1354 assert_eq!(cmd("Stop"), "tracevault stream --event stop --agent codex");
1355 assert_eq!(cmd("SessionStart"), "tracevault session-start");
1356 assert_eq!(cmd("UserPromptSubmit"), "tracevault user-prompt");
1357 assert_eq!(h["PostToolUse"][0]["matcher"].as_str().unwrap(), "");
1359 }
1360
1361 #[test]
1362 fn install_codex_hooks_writes_hooks_json_and_is_idempotent() {
1363 let tmp = tempfile::tempdir().unwrap();
1364 install_codex_hooks(tmp.path()).unwrap();
1365 install_codex_hooks(tmp.path()).unwrap();
1366
1367 let content = fs::read_to_string(tmp.path().join(".codex").join("hooks.json")).unwrap();
1368 let v: serde_json::Value = serde_json::from_str(&content).unwrap();
1369 for event in ["SessionStart", "UserPromptSubmit", "PostToolUse", "Stop"] {
1370 let arr = v["hooks"][event].as_array().unwrap();
1371 assert_eq!(
1372 arr.len(),
1373 1,
1374 "event {event} must not be duplicated on re-run"
1375 );
1376 }
1377 assert!(v["hooks"].get("PreToolUse").is_none());
1378 }
1379
1380 #[test]
1381 fn install_codex_hooks_preserves_existing_user_hook() {
1382 let tmp = tempfile::tempdir().unwrap();
1383 let codex_dir = tmp.path().join(".codex");
1384 fs::create_dir_all(&codex_dir).unwrap();
1385 fs::write(
1388 codex_dir.join("hooks.json"),
1389 r#"{"hooks":{"PostToolUse":[{"matcher":"","hooks":[{"type":"command","command":"my-own"}]}],"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"user-pretool"}]}]}}"#,
1390 )
1391 .unwrap();
1392
1393 install_codex_hooks(tmp.path()).unwrap();
1394
1395 let v: serde_json::Value =
1396 serde_json::from_str(&fs::read_to_string(codex_dir.join("hooks.json")).unwrap())
1397 .unwrap();
1398 let post_cmds: Vec<&str> = v["hooks"]["PostToolUse"]
1400 .as_array()
1401 .unwrap()
1402 .iter()
1403 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1404 .collect();
1405 assert!(
1406 post_cmds.contains(&"my-own"),
1407 "user PostToolUse hook preserved"
1408 );
1409 assert!(post_cmds.contains(&"tracevault stream --event post-tool-use --agent codex"));
1410 let pre_cmds: Vec<&str> = v["hooks"]["PreToolUse"]
1412 .as_array()
1413 .unwrap()
1414 .iter()
1415 .map(|e| e["hooks"][0]["command"].as_str().unwrap())
1416 .collect();
1417 assert_eq!(pre_cmds, vec!["user-pretool"], "unmanaged event untouched");
1418 }
1419
1420 #[test]
1421 fn validate_init_flags_rejects_claude_settings_with_codex() {
1422 assert!(validate_init_flags(crate::agent::Agent::Codex, true).is_err());
1423 }
1424
1425 #[test]
1426 fn validate_init_flags_allows_codex_without_claude_settings() {
1427 assert!(validate_init_flags(crate::agent::Agent::Codex, false).is_ok());
1428 }
1429
1430 #[test]
1431 fn validate_init_flags_allows_claude_with_claude_settings() {
1432 assert!(validate_init_flags(crate::agent::Agent::ClaudeCode, true).is_ok());
1433 }
1434
1435 #[test]
1436 fn merge_hooks_into_file_rejects_parent_dir() {
1437 let tmp = tempfile::tempdir().unwrap();
1438 let bad = tmp.path().join("..").join("hooks.json");
1439 let err = merge_hooks_into_file(&bad, &codex_hooks()).unwrap_err();
1440 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1441 }
1442
1443 #[test]
1444 fn append_workspace_md_rejects_parent_dir() {
1445 let tmp = tempfile::tempdir().unwrap();
1446 let bad = tmp.path().join("..").join("AGENTS.md");
1447 let err = append_workspace_md(&bad).unwrap_err();
1448 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1449 }
1450
1451 #[tokio::test]
1452 async fn init_in_directory_codex_installs_codex_hooks_and_gitignores() {
1453 let tmp = tempfile::tempdir().unwrap();
1454 let root = tmp.path();
1455 crate::test_helpers::init_git_repo(root);
1456
1457 let entry = init_in_directory(
1458 root,
1459 None,
1460 None,
1461 false,
1462 crate::config::UserContext::Toggle(false),
1463 crate::agent::Agent::Codex,
1464 )
1465 .await
1466 .unwrap();
1467
1468 assert!(root.join(".codex").join("hooks.json").exists());
1470 assert!(!root.join(".claude").join("settings.json").exists());
1471 assert_eq!(entry, ".codex/hooks.json");
1472
1473 let gi = fs::read_to_string(root.join(".gitignore")).unwrap();
1475 assert!(gi.contains(".codex/hooks.json"));
1476 assert!(gi.contains(".tracevault/"));
1477 }
1478}