1use crate::api_client::ApiClient;
2use crate::config::{TracevaultConfig, UserContext};
3use std::fs;
4use std::io::{self, BufRead, IsTerminal, Write};
5use std::path::{Path, PathBuf};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
9pub enum ClaudeSettingsTarget {
10 Shared,
12 Local,
14}
15
16impl ClaudeSettingsTarget {
17 pub fn filename(self) -> &'static str {
18 match self {
19 ClaudeSettingsTarget::Shared => "settings.json",
20 ClaudeSettingsTarget::Local => "settings.local.json",
21 }
22 }
23
24 pub fn gitignore_entry(self) -> &'static str {
25 match self {
26 ClaudeSettingsTarget::Shared => ".claude/settings.json",
27 ClaudeSettingsTarget::Local => ".claude/settings.local.json",
28 }
29 }
30}
31
32fn resolve_claude_target(
36 explicit: Option<ClaudeSettingsTarget>,
37) -> io::Result<ClaudeSettingsTarget> {
38 if let Some(target) = explicit {
39 return Ok(target);
40 }
41 if !io::stdin().is_terminal() {
42 return Ok(ClaudeSettingsTarget::Shared);
43 }
44
45 let stdout = io::stdout();
46 let mut stdout = stdout.lock();
47 write!(
48 stdout,
49 "Install Claude Code hooks into [s]hared (.claude/settings.json) or [l]ocal (.claude/settings.local.json)? [s]: "
50 )?;
51 stdout.flush()?;
52
53 let mut line = String::new();
54 io::stdin().lock().read_line(&mut line)?;
55 let answer = line.trim().to_lowercase();
56 Ok(match answer.as_str() {
57 "l" | "local" => ClaudeSettingsTarget::Local,
58 _ => ClaudeSettingsTarget::Shared,
59 })
60}
61
62pub fn git_remote_url(project_root: &Path) -> Option<String> {
63 std::process::Command::new("git")
64 .args(["remote", "get-url", "origin"])
65 .current_dir(project_root)
66 .output()
67 .ok()
68 .filter(|o| o.status.success())
69 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
70 .filter(|s| !s.is_empty())
71}
72
73fn parse_github_org(remote_url: &str) -> Option<String> {
74 if let Some(path) = remote_url.strip_prefix("git@github.com:") {
76 return path.split('/').next().map(String::from);
77 }
78 if let Some(path) = remote_url
80 .strip_prefix("https://github.com/")
81 .or_else(|| remote_url.strip_prefix("http://github.com/"))
82 {
83 return path.split('/').next().map(String::from);
84 }
85 None
86}
87
88fn linked_worktree_primary(dir: &Path) -> Option<PathBuf> {
96 let output = std::process::Command::new("git")
97 .args(["rev-parse", "--git-dir", "--git-common-dir"])
98 .current_dir(dir)
99 .output()
100 .ok()?;
101 if !output.status.success() {
102 return None;
103 }
104 let stdout = String::from_utf8(output.stdout).ok()?;
105 let mut lines = stdout.lines();
106 let git_dir = lines.next()?.trim();
107 let git_common_dir = lines.next()?.trim();
108
109 let git_dir = dir.join(git_dir).canonicalize().ok()?;
112 let git_common_dir = dir.join(git_common_dir).canonicalize().ok()?;
113
114 if git_dir == git_common_dir {
115 None } else {
117 git_common_dir.parent().map(Path::to_path_buf)
118 }
119}
120
121pub async fn init_in_directory(
122 project_root: &Path,
123 server_url: Option<&str>,
124 claude_settings: Option<ClaudeSettingsTarget>,
125 no_gitignore: bool,
126 user_context: UserContext,
127) -> Result<ClaudeSettingsTarget, io::Error> {
128 if !project_root.join(".git").exists() {
130 return Err(io::Error::new(
131 io::ErrorKind::NotFound,
132 "Not a git repository. Run 'git init' first.",
133 ));
134 }
135
136 if let Some(primary) = linked_worktree_primary(project_root) {
142 return Err(io::Error::new(
143 io::ErrorKind::Unsupported,
144 format!(
145 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
146 cd there and run it again — all worktrees share the primary's .tracevault/.",
147 primary.display()
148 ),
149 ));
150 }
151
152 let target = resolve_claude_target(claude_settings)?;
153
154 let config_dir = TracevaultConfig::config_dir(project_root);
156 fs::create_dir_all(&config_dir)?;
157 fs::create_dir_all(config_dir.join("sessions"))?;
158 fs::create_dir_all(config_dir.join("cache"))?;
159 TracevaultConfig::ensure_gitignore(&config_dir)?;
162
163 if !no_gitignore {
165 update_root_gitignore(project_root, target)?;
166 }
167
168 let remote_url = git_remote_url(project_root);
170 if remote_url.is_none() {
171 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
172 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
173 }
174
175 let org_slug = remote_url.as_deref().and_then(parse_github_org);
177
178 let mut config = TracevaultConfig::default();
180 if let Some(url) = server_url {
181 config.server_url = Some(url.to_string());
182 }
183 config.org_slug = org_slug.clone();
184 config.user_context = user_context;
185 fs::write(
186 TracevaultConfig::config_path(project_root),
187 config.to_toml(),
188 )?;
189
190 install_claude_hooks(project_root, target)?;
192
193 install_git_hook(project_root)?;
195 install_post_commit_hook(project_root)?;
196
197 let detected = crate::hooks::detect_tools(project_root);
199 for tool in &detected {
200 println!(" Detected: {}", tool.name());
201 }
202
203 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
204 let effective_url = server_url.map(String::from).or(resolved_url);
205
206 if resolved_token.is_none() {
207 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
208 } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
209 let client = ApiClient::new(&url, resolved_token.as_deref());
210 let repo_name = git_repo_name(project_root);
211
212 match client
213 .register_repo(
214 &slug,
215 crate::api_client::RegisterRepoRequest {
216 repo_name,
217 github_url: Some(remote),
218 },
219 )
220 .await
221 {
222 Ok(resp) => {
223 println!("Repo registered on server (id: {})", resp.repo_id);
224 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
226 cfg.repo_id = Some(resp.repo_id.to_string());
227 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
228 }
229 }
230 Err(e) => {
231 let msg = e.to_string();
232 if msg.contains("404") {
233 eprintln!("Warning: organization '{}' not found on the server.", slug);
234 eprintln!(
235 "Create it first at your TraceVault instance, then run 'tracevault sync'."
236 );
237 } else if msg.contains("403") {
238 eprintln!("Warning: you are not a member of organization '{}'.", slug);
239 } else {
240 eprintln!("Warning: could not register repo on server: {e}");
241 }
242 }
243 }
244 }
245
246 Ok(target)
247}
248
249fn update_root_gitignore(
250 project_root: &Path,
251 target: ClaudeSettingsTarget,
252) -> Result<(), io::Error> {
253 let path = project_root.join(".gitignore");
254 let existing = if path.exists() {
255 fs::read_to_string(&path)?
256 } else {
257 String::new()
258 };
259
260 let needed: Vec<&str> = [".tracevault/", target.gitignore_entry()]
264 .iter()
265 .copied()
266 .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
267 .collect();
268
269 if needed.is_empty() {
270 return Ok(());
271 }
272
273 let mut content = existing;
274 if !content.is_empty() && !content.ends_with('\n') {
275 content.push('\n');
276 }
277 content.push_str("\n# TraceVault — local only, do not commit\n");
278 for entry in needed {
279 content.push_str(entry);
280 content.push('\n');
281 }
282
283 fs::write(path, content)
284}
285
286fn git_repo_name(project_root: &Path) -> String {
287 std::process::Command::new("git")
288 .args(["rev-parse", "--show-toplevel"])
289 .current_dir(project_root)
290 .output()
291 .ok()
292 .filter(|o| o.status.success())
293 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
294 .as_deref()
295 .and_then(|p| p.rsplit('/').next())
296 .map(String::from)
297 .unwrap_or_else(|| "unknown".into())
298}
299
300const HOOK_MARKER: &str = "# tracevault:enforce";
301const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
302
303fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
304 let hooks_dir = project_root.join(".git/hooks");
305 fs::create_dir_all(&hooks_dir)?;
306
307 let hook_path = hooks_dir.join("pre-push");
308 let tracevault_block = format!(
309 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
310 );
311
312 if hook_path.exists() {
313 let existing = fs::read_to_string(&hook_path)?;
314
315 if existing.contains(HOOK_MARKER) {
317 return Ok(());
318 }
319
320 if existing.contains(OLD_HOOK_MARKER) {
322 let mut new_content = String::new();
323 let mut skip = false;
324 for line in existing.lines() {
325 if line.contains(OLD_HOOK_MARKER) {
326 skip = true;
327 continue;
328 }
329 if skip {
330 if line.starts_with("tracevault ") {
332 continue;
333 }
334 skip = false;
335 }
336 new_content.push_str(line);
337 new_content.push('\n');
338 }
339 if !new_content.ends_with('\n') {
340 new_content.push('\n');
341 }
342 new_content.push_str(&tracevault_block);
343 fs::write(&hook_path, new_content)?;
344 } else {
345 let mut content = existing;
347 if !content.ends_with('\n') {
348 content.push('\n');
349 }
350 content.push_str(&tracevault_block);
351 fs::write(&hook_path, content)?;
352 }
353 } else {
354 let content = format!("#!/bin/sh\n{tracevault_block}");
355 fs::write(&hook_path, content)?;
356 }
357
358 #[cfg(unix)]
360 {
361 use std::os::unix::fs::PermissionsExt;
362 let mut perms = fs::metadata(&hook_path)?.permissions();
363 perms.set_mode(0o755);
364 fs::set_permissions(&hook_path, perms)?;
365 }
366
367 Ok(())
368}
369
370const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
371
372fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
373 let hooks_dir = project_root.join(".git/hooks");
374 fs::create_dir_all(&hooks_dir)?;
375
376 let hook_path = hooks_dir.join("post-commit");
377 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
378
379 if hook_path.exists() {
380 let existing = fs::read_to_string(&hook_path)?;
381
382 if existing.contains(POST_COMMIT_MARKER) {
383 return Ok(());
384 }
385
386 let mut content = existing;
387 if !content.ends_with('\n') {
388 content.push('\n');
389 }
390 content.push_str(&tracevault_block);
391 fs::write(&hook_path, content)?;
392 } else {
393 let content = format!("#!/bin/sh\n{tracevault_block}");
394 fs::write(&hook_path, content)?;
395 }
396
397 #[cfg(unix)]
398 {
399 use std::os::unix::fs::PermissionsExt;
400 let mut perms = fs::metadata(&hook_path)?.permissions();
401 perms.set_mode(0o755);
402 fs::set_permissions(&hook_path, perms)?;
403 }
404
405 Ok(())
406}
407
408fn install_claude_hooks(
409 project_root: &Path,
410 target: ClaudeSettingsTarget,
411) -> Result<(), io::Error> {
412 let claude_dir = project_root.join(".claude");
413 fs::create_dir_all(&claude_dir)?;
414
415 let filename = target.filename();
416 let settings_path = claude_dir.join(filename);
417 let mut settings: serde_json::Value = if settings_path.exists() {
418 let content = fs::read_to_string(&settings_path)?;
419 serde_json::from_str(&content).map_err(|e| {
420 io::Error::new(
421 io::ErrorKind::InvalidData,
422 format!("Failed to parse .claude/{filename}: {e}"),
423 )
424 })?
425 } else {
426 serde_json::json!({})
427 };
428
429 let hooks = tracevault_hooks();
430
431 let settings_obj = settings.as_object_mut().ok_or_else(|| {
433 io::Error::new(
434 io::ErrorKind::InvalidData,
435 format!(".claude/{filename} is not a JSON object"),
436 )
437 })?;
438
439 settings_obj.insert("hooks".to_string(), hooks);
440
441 let formatted = serde_json::to_string_pretty(&settings)
442 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
443 fs::write(&settings_path, formatted)?;
444
445 Ok(())
446}
447
448pub fn tracevault_hooks() -> serde_json::Value {
449 serde_json::json!({
450 "PreToolUse": [{
451 "matcher": "Write|Edit|Bash",
452 "hooks": [{
453 "type": "command",
454 "command": "tracevault stream --event pre-tool-use",
455 "timeout": 10,
456 "statusMessage": "TraceVault: streaming pre-tool event"
457 }]
458 }],
459 "PostToolUse": [{
460 "matcher": "",
461 "hooks": [{
462 "type": "command",
463 "command": "tracevault stream --event post-tool-use",
464 "timeout": 10,
465 "statusMessage": "TraceVault: streaming post-tool event"
466 }]
467 }],
468 "Notification": [{
469 "matcher": "",
470 "hooks": [{
471 "type": "command",
472 "command": "tracevault stream --event notification",
473 "timeout": 10,
474 "statusMessage": "TraceVault: streaming notification"
475 }]
476 }],
477 "Stop": [{
478 "matcher": "",
479 "hooks": [{
480 "type": "command",
481 "command": "tracevault stream --event stop",
482 "timeout": 10,
483 "statusMessage": "TraceVault: finalizing session"
484 }]
485 }],
486 "SessionStart": [{
487 "matcher": "",
488 "hooks": [{
489 "type": "command",
490 "command": "tracevault session-start",
491 "timeout": 10,
492 "statusMessage": "TraceVault: session start"
493 }]
494 }],
495 "UserPromptSubmit": [{
496 "matcher": "",
497 "hooks": [{
498 "type": "command",
499 "command": "tracevault user-prompt",
500 "timeout": 10,
501 "statusMessage": "TraceVault: policy reinforcement"
502 }]
503 }]
504 })
505}
506
507const GLOBAL_CLAUDE_MD_MARKER: &str = "<!-- tracevault:workspace-mode -->";
508
509const GLOBAL_CLAUDE_MD_BLOCK: &str = "\
510<!-- tracevault:workspace-mode -->
511## TraceVault (workspace mode)
512You may be running detached from any single repository. Before working on a repo, run
513`tracevault repo switch <path>` to bind tracing and fetch that repo's policies; treat its
514output as binding. Use `--path <path>` on `tracevault repo status` for a one-off. Repos must
515already be registered with TraceVault.
516";
517
518fn safe_join(base: &Path, name: &str) -> io::Result<PathBuf> {
522 let joined = base.join(name);
523 if joined.parent() != Some(base) {
524 return Err(io::Error::new(
525 io::ErrorKind::InvalidInput,
526 format!(
527 "refusing to access path outside {}: {}",
528 base.display(),
529 joined.display()
530 ),
531 ));
532 }
533 Ok(joined)
534}
535
536fn merge_hooks(
549 settings: &mut serde_json::Value,
550 ours: &serde_json::Value,
551 path: &Path,
552) -> io::Result<()> {
553 if settings.is_null() {
554 *settings = serde_json::json!({});
555 }
556 let settings_obj = settings.as_object_mut().ok_or_else(|| {
557 io::Error::new(
558 io::ErrorKind::InvalidData,
559 format!("{} is not a JSON object", path.display()),
560 )
561 })?;
562
563 let hooks_value = settings_obj
564 .entry("hooks")
565 .or_insert_with(|| serde_json::json!({}));
566 let hooks_obj = hooks_value.as_object_mut().ok_or_else(|| {
567 io::Error::new(
568 io::ErrorKind::InvalidData,
569 format!("{} \"hooks\" key is not a JSON object", path.display()),
570 )
571 })?;
572
573 let Some(ours_obj) = ours.as_object() else {
574 return Ok(());
575 };
576
577 for (event, our_array) in ours_obj {
578 let Some(our_entries) = our_array.as_array() else {
579 continue;
580 };
581
582 let existing_value = hooks_obj
583 .entry(event.clone())
584 .or_insert_with(|| serde_json::json!([]));
585 let existing_array = existing_value.as_array_mut().ok_or_else(|| {
586 io::Error::new(
587 io::ErrorKind::InvalidData,
588 format!(
589 "{} \"hooks\".\"{event}\" is not a JSON array",
590 path.display()
591 ),
592 )
593 })?;
594
595 for our_entry in our_entries {
596 let our_command = entry_command(our_entry);
597 let already_present = existing_array
598 .iter()
599 .any(|existing_entry| entry_contains_command(existing_entry, our_command));
600 if !already_present {
601 existing_array.push(our_entry.clone());
602 }
603 }
604 }
605
606 Ok(())
607}
608
609fn entry_command(entry: &serde_json::Value) -> Option<&str> {
612 entry.get("hooks")?.get(0)?.get("command")?.as_str()
613}
614
615fn entry_contains_command(entry: &serde_json::Value, cmd: Option<&str>) -> bool {
620 let Some(hooks) = entry.get("hooks").and_then(|h| h.as_array()) else {
621 return false;
622 };
623 hooks
624 .iter()
625 .any(|hook| hook.get("command").and_then(|c| c.as_str()) == cmd)
626}
627
628pub fn install_global_hooks(claude_dir: &Path) -> io::Result<()> {
634 fs::create_dir_all(claude_dir)?;
635
636 let base = claude_dir.canonicalize()?;
639
640 let settings_path = safe_join(&base, "settings.json")?;
642 let mut settings: serde_json::Value = if settings_path.exists() {
643 let content = fs::read_to_string(&settings_path)?;
644 serde_json::from_str(&content).map_err(|e| {
645 io::Error::new(
646 io::ErrorKind::InvalidData,
647 format!("Failed to parse {}: {e}", settings_path.display()),
648 )
649 })?
650 } else {
651 serde_json::json!({})
652 };
653
654 merge_hooks(&mut settings, &tracevault_hooks(), &settings_path)?;
655
656 let formatted = serde_json::to_string_pretty(&settings)
657 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
658 let tmp_settings_path = settings_path.with_extension("json.tmp");
662 fs::write(&tmp_settings_path, formatted)?;
663 fs::rename(&tmp_settings_path, &settings_path)?;
664
665 let claude_md_path = safe_join(&base, "CLAUDE.md")?;
667 let existing = if claude_md_path.exists() {
668 fs::read_to_string(&claude_md_path)?
669 } else {
670 String::new()
671 };
672
673 if !existing.contains(GLOBAL_CLAUDE_MD_MARKER) {
674 let mut content = existing;
675 if !content.is_empty() && !content.ends_with('\n') {
676 content.push('\n');
677 }
678 if !content.is_empty() {
679 content.push('\n');
680 }
681 content.push_str(GLOBAL_CLAUDE_MD_BLOCK);
682 fs::write(&claude_md_path, content)?;
683 }
684
685 Ok(())
686}
687
688#[cfg(test)]
689mod tests {
690 use super::*;
691
692 #[test]
693 fn linked_worktree_primary_detects_linked_and_primary() {
694 let tmp = tempfile::tempdir().unwrap();
695 let repo = tmp.path().join("repo");
696 let wt = tmp.path().join("linked-wt");
697 std::fs::create_dir_all(&repo).unwrap();
698 crate::test_helpers::init_git_repo(&repo);
699 crate::test_helpers::add_worktree(&repo, &wt);
700
701 assert!(
703 linked_worktree_primary(&repo).is_none(),
704 "primary checkout must not be flagged as a linked worktree"
705 );
706 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
708 assert_eq!(
709 primary.canonicalize().unwrap(),
710 repo.canonicalize().unwrap(),
711 "must resolve to the primary repo root"
712 );
713 }
714
715 #[test]
716 fn linked_worktree_primary_none_for_non_git() {
717 let tmp = tempfile::tempdir().unwrap();
718 assert!(
719 linked_worktree_primary(tmp.path()).is_none(),
720 "a non-git directory is not a linked worktree"
721 );
722 }
723
724 #[test]
725 fn parse_github_org_ssh() {
726 assert_eq!(
727 parse_github_org("git@github.com:myorg/myrepo.git"),
728 Some("myorg".into())
729 );
730 }
731
732 #[test]
733 fn parse_github_org_https() {
734 assert_eq!(
735 parse_github_org("https://github.com/myorg/myrepo"),
736 Some("myorg".into())
737 );
738 }
739
740 #[test]
741 fn parse_github_org_non_github_returns_none() {
742 assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
743 }
744
745 #[test]
746 fn parse_github_org_invalid() {
747 assert_eq!(parse_github_org("not-a-url"), None);
748 }
749
750 #[test]
751 fn merge_hooks_into_empty_settings_adds_all_our_events() {
752 let mut settings = serde_json::json!({});
753 let ours = tracevault_hooks();
754 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
755
756 let hooks = settings.get("hooks").unwrap();
757 for event in [
758 "PreToolUse",
759 "PostToolUse",
760 "Notification",
761 "Stop",
762 "SessionStart",
763 "UserPromptSubmit",
764 ] {
765 assert!(hooks.get(event).is_some(), "missing event {event}");
766 }
767 }
768
769 #[test]
770 fn merge_hooks_preserves_unrelated_user_hook_and_keys() {
771 let mut settings = serde_json::json!({
772 "model": "opus",
773 "hooks": {
774 "PreToolUse": [{
775 "matcher": "",
776 "hooks": [{ "type": "command", "command": "my-own-hook" }]
777 }]
778 }
779 });
780 let ours = tracevault_hooks();
781 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
782
783 assert_eq!(settings.get("model").unwrap(), "opus");
785
786 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
787 assert_eq!(pre_tool_use.len(), 2);
789 let commands: Vec<&str> = pre_tool_use
790 .iter()
791 .map(|e| entry_command(e).unwrap())
792 .collect();
793 assert!(commands.contains(&"my-own-hook"));
794 assert!(commands.contains(&"tracevault stream --event pre-tool-use"));
795
796 assert!(settings["hooks"]["SessionStart"].is_array());
798 }
799
800 #[test]
801 fn merge_hooks_is_idempotent() {
802 let mut settings = serde_json::json!({});
803 let ours = tracevault_hooks();
804 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
805 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
806
807 for event in [
808 "PreToolUse",
809 "PostToolUse",
810 "Notification",
811 "Stop",
812 "SessionStart",
813 "UserPromptSubmit",
814 ] {
815 let arr = settings["hooks"][event].as_array().unwrap();
816 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
817 }
818 }
819
820 #[test]
821 fn merge_hooks_dedupes_command_found_in_non_first_inner_hook() {
822 let mut settings = serde_json::json!({
826 "hooks": {
827 "PreToolUse": [{
828 "matcher": "Write|Edit|Bash",
829 "hooks": [
830 { "type": "command", "command": "other" },
831 { "type": "command", "command": "tracevault stream --event pre-tool-use" }
832 ]
833 }]
834 }
835 });
836 let ours = tracevault_hooks();
837 merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap();
838
839 let pre_tool_use = settings["hooks"]["PreToolUse"].as_array().unwrap();
840 assert_eq!(
841 pre_tool_use.len(),
842 1,
843 "must not append a duplicate PreToolUse entry when our command is present at hooks[1]"
844 );
845 }
846
847 #[test]
848 fn merge_hooks_errors_on_non_object_top_level() {
849 let mut settings = serde_json::json!([1, 2, 3]);
850 let ours = tracevault_hooks();
851 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
852 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
853 assert!(err.to_string().contains("settings.json"));
854 }
855
856 #[test]
857 fn merge_hooks_errors_on_non_object_top_level_number() {
858 let mut settings = serde_json::json!(42);
859 let ours = tracevault_hooks();
860 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
861 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
862 }
863
864 #[test]
865 fn merge_hooks_errors_on_non_object_hooks() {
866 let mut settings = serde_json::json!({ "hooks": "not-an-object" });
867 let ours = tracevault_hooks();
868 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
869 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
870 assert!(err.to_string().contains("hooks"));
871 }
872
873 #[test]
874 fn merge_hooks_errors_on_non_array_event_value() {
875 let mut settings = serde_json::json!({
876 "hooks": {
877 "PreToolUse": "not-an-array"
878 }
879 });
880 let ours = tracevault_hooks();
881 let err = merge_hooks(&mut settings, &ours, Path::new("settings.json")).unwrap_err();
882 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
883 assert!(err.to_string().contains("PreToolUse"));
884 }
885
886 #[test]
887 fn install_global_hooks_writes_settings_and_claude_md() {
888 let tmp = tempfile::tempdir().unwrap();
889 let claude_dir = tmp.path().join(".claude");
890
891 install_global_hooks(&claude_dir).unwrap();
892
893 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
894 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
895 for event in ["SessionStart", "UserPromptSubmit", "PreToolUse"] {
896 assert!(settings["hooks"].get(event).is_some(), "missing {event}");
897 }
898
899 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
900 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
901 }
902
903 #[test]
904 fn install_global_hooks_is_idempotent() {
905 let tmp = tempfile::tempdir().unwrap();
906 let claude_dir = tmp.path().join(".claude");
907
908 install_global_hooks(&claude_dir).unwrap();
909 install_global_hooks(&claude_dir).unwrap();
910
911 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
912 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
913 for event in [
914 "PreToolUse",
915 "PostToolUse",
916 "Notification",
917 "Stop",
918 "SessionStart",
919 "UserPromptSubmit",
920 ] {
921 let arr = settings["hooks"][event].as_array().unwrap();
922 assert_eq!(arr.len(), 1, "event {event} should not be duplicated");
923 }
924
925 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
926 let marker_count = claude_md.matches(GLOBAL_CLAUDE_MD_MARKER).count();
927 assert_eq!(
928 marker_count, 1,
929 "CLAUDE.md marker should appear exactly once"
930 );
931 }
932
933 #[test]
934 fn install_global_hooks_preserves_existing_claude_md_content() {
935 let tmp = tempfile::tempdir().unwrap();
936 let claude_dir = tmp.path().join(".claude");
937 fs::create_dir_all(&claude_dir).unwrap();
938 fs::write(
939 claude_dir.join("CLAUDE.md"),
940 "# My existing notes\nSome content.\n",
941 )
942 .unwrap();
943
944 install_global_hooks(&claude_dir).unwrap();
945
946 let claude_md = fs::read_to_string(claude_dir.join("CLAUDE.md")).unwrap();
947 assert!(claude_md.contains("# My existing notes"));
948 assert!(claude_md.contains(GLOBAL_CLAUDE_MD_MARKER));
949 }
950
951 #[test]
952 fn install_global_hooks_settings_write_is_atomic_no_tmp_leftover() {
953 let tmp = tempfile::tempdir().unwrap();
954 let claude_dir = tmp.path().join(".claude");
955
956 install_global_hooks(&claude_dir).unwrap();
957
958 let settings_content = fs::read_to_string(claude_dir.join("settings.json")).unwrap();
959 let settings: serde_json::Value = serde_json::from_str(&settings_content).unwrap();
960 assert!(settings["hooks"].get("SessionStart").is_some());
961
962 let leftover = fs::read_dir(&claude_dir)
963 .unwrap()
964 .filter_map(|e| e.ok())
965 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
966 assert!(
967 !leftover,
968 "no settings.json.tmp should remain after install"
969 );
970 }
971
972 #[test]
973 fn install_global_hooks_errors_on_non_object_settings_and_does_not_overwrite() {
974 let tmp = tempfile::tempdir().unwrap();
975 let claude_dir = tmp.path().join(".claude");
976 fs::create_dir_all(&claude_dir).unwrap();
977 let settings_path = claude_dir.join("settings.json");
978 let original = "[1, 2, 3]";
979 fs::write(&settings_path, original).unwrap();
980
981 let err = install_global_hooks(&claude_dir).unwrap_err();
982 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
983
984 let after = fs::read_to_string(&settings_path).unwrap();
987 assert_eq!(after, original);
988 let leftover = fs::read_dir(&claude_dir)
989 .unwrap()
990 .filter_map(|e| e.ok())
991 .any(|e| e.file_name().to_string_lossy().ends_with(".tmp"));
992 assert!(!leftover, "no tmp file should be left behind on error");
993 }
994
995 #[test]
996 fn install_global_hooks_errors_on_non_object_hooks_key_and_does_not_overwrite() {
997 let tmp = tempfile::tempdir().unwrap();
998 let claude_dir = tmp.path().join(".claude");
999 fs::create_dir_all(&claude_dir).unwrap();
1000 let settings_path = claude_dir.join("settings.json");
1001 let original = r#"{"hooks": "oops"}"#;
1002 fs::write(&settings_path, original).unwrap();
1003
1004 let err = install_global_hooks(&claude_dir).unwrap_err();
1005 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1006
1007 let after = fs::read_to_string(&settings_path).unwrap();
1008 assert_eq!(after, original);
1009 }
1010
1011 #[test]
1012 fn install_global_hooks_errors_on_non_array_event_and_does_not_overwrite() {
1013 let tmp = tempfile::tempdir().unwrap();
1014 let claude_dir = tmp.path().join(".claude");
1015 fs::create_dir_all(&claude_dir).unwrap();
1016 let settings_path = claude_dir.join("settings.json");
1017 let original = r#"{"hooks": {"PreToolUse": "oops"}}"#;
1018 fs::write(&settings_path, original).unwrap();
1019
1020 let err = install_global_hooks(&claude_dir).unwrap_err();
1021 assert_eq!(err.kind(), io::ErrorKind::InvalidData);
1022
1023 let after = fs::read_to_string(&settings_path).unwrap();
1024 assert_eq!(after, original);
1025 }
1026
1027 #[test]
1028 fn safe_join_allows_direct_child_file() {
1029 let tmp = tempfile::tempdir().unwrap();
1030 let base = tmp.path();
1031 let result = safe_join(base, "settings.json").unwrap();
1032 assert_eq!(result.parent(), Some(base));
1033 assert_eq!(result.file_name().unwrap(), "settings.json");
1034 }
1035
1036 #[test]
1037 fn safe_join_rejects_path_traversal() {
1038 let tmp = tempfile::tempdir().unwrap();
1039 let base = tmp.path();
1040 let result = safe_join(base, "../evil");
1041 assert!(result.is_err());
1042 let err = result.unwrap_err();
1043 assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
1044 assert!(err.to_string().contains("refusing to access path outside"));
1045 }
1046
1047 #[test]
1048 fn safe_join_rejects_absolute_path() {
1049 let tmp = tempfile::tempdir().unwrap();
1050 let base = tmp.path();
1051 let result = safe_join(base, "/etc/passwd");
1052 assert!(result.is_err());
1055 }
1056}