1use crate::api_client::ApiClient;
2use crate::config::TracevaultConfig;
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) -> Result<ClaudeSettingsTarget, io::Error> {
127 if !project_root.join(".git").exists() {
129 return Err(io::Error::new(
130 io::ErrorKind::NotFound,
131 "Not a git repository. Run 'git init' first.",
132 ));
133 }
134
135 if let Some(primary) = linked_worktree_primary(project_root) {
141 return Err(io::Error::new(
142 io::ErrorKind::Unsupported,
143 format!(
144 "Run `tracevault init` from the primary checkout ({}), not a linked worktree. \
145 cd there and run it again — all worktrees share the primary's .tracevault/.",
146 primary.display()
147 ),
148 ));
149 }
150
151 let target = resolve_claude_target(claude_settings)?;
152
153 let config_dir = TracevaultConfig::config_dir(project_root);
155 fs::create_dir_all(&config_dir)?;
156 fs::create_dir_all(config_dir.join("sessions"))?;
157 fs::create_dir_all(config_dir.join("cache"))?;
158 TracevaultConfig::ensure_gitignore(&config_dir)?;
161
162 if !no_gitignore {
164 update_root_gitignore(project_root, target)?;
165 }
166
167 let remote_url = git_remote_url(project_root);
169 if remote_url.is_none() {
170 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
171 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
172 }
173
174 let org_slug = remote_url.as_deref().and_then(parse_github_org);
176
177 let mut config = TracevaultConfig::default();
179 if let Some(url) = server_url {
180 config.server_url = Some(url.to_string());
181 }
182 config.org_slug = org_slug.clone();
183 fs::write(
184 TracevaultConfig::config_path(project_root),
185 config.to_toml(),
186 )?;
187
188 install_claude_hooks(project_root, target)?;
190
191 install_git_hook(project_root)?;
193 install_post_commit_hook(project_root)?;
194
195 let detected = crate::hooks::detect_tools(project_root);
197 for tool in &detected {
198 println!(" Detected: {}", tool.name());
199 }
200
201 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
202 let effective_url = server_url.map(String::from).or(resolved_url);
203
204 if resolved_token.is_none() {
205 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
206 } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
207 let client = ApiClient::new(&url, resolved_token.as_deref());
208 let repo_name = git_repo_name(project_root);
209
210 match client
211 .register_repo(
212 &slug,
213 crate::api_client::RegisterRepoRequest {
214 repo_name,
215 github_url: Some(remote),
216 },
217 )
218 .await
219 {
220 Ok(resp) => {
221 println!("Repo registered on server (id: {})", resp.repo_id);
222 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
224 cfg.repo_id = Some(resp.repo_id.to_string());
225 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
226 }
227 }
228 Err(e) => {
229 let msg = e.to_string();
230 if msg.contains("404") {
231 eprintln!("Warning: organization '{}' not found on the server.", slug);
232 eprintln!(
233 "Create it first at your TraceVault instance, then run 'tracevault sync'."
234 );
235 } else if msg.contains("403") {
236 eprintln!("Warning: you are not a member of organization '{}'.", slug);
237 } else {
238 eprintln!("Warning: could not register repo on server: {e}");
239 }
240 }
241 }
242 }
243
244 Ok(target)
245}
246
247fn update_root_gitignore(
248 project_root: &Path,
249 target: ClaudeSettingsTarget,
250) -> Result<(), io::Error> {
251 let path = project_root.join(".gitignore");
252 let existing = if path.exists() {
253 fs::read_to_string(&path)?
254 } else {
255 String::new()
256 };
257
258 let needed: Vec<&str> = [".tracevault/", target.gitignore_entry()]
262 .iter()
263 .copied()
264 .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
265 .collect();
266
267 if needed.is_empty() {
268 return Ok(());
269 }
270
271 let mut content = existing;
272 if !content.is_empty() && !content.ends_with('\n') {
273 content.push('\n');
274 }
275 content.push_str("\n# TraceVault — local only, do not commit\n");
276 for entry in needed {
277 content.push_str(entry);
278 content.push('\n');
279 }
280
281 fs::write(path, content)
282}
283
284fn git_repo_name(project_root: &Path) -> String {
285 std::process::Command::new("git")
286 .args(["rev-parse", "--show-toplevel"])
287 .current_dir(project_root)
288 .output()
289 .ok()
290 .filter(|o| o.status.success())
291 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
292 .as_deref()
293 .and_then(|p| p.rsplit('/').next())
294 .map(String::from)
295 .unwrap_or_else(|| "unknown".into())
296}
297
298const HOOK_MARKER: &str = "# tracevault:enforce";
299const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
300
301fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
302 let hooks_dir = project_root.join(".git/hooks");
303 fs::create_dir_all(&hooks_dir)?;
304
305 let hook_path = hooks_dir.join("pre-push");
306 let tracevault_block = format!(
307 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
308 );
309
310 if hook_path.exists() {
311 let existing = fs::read_to_string(&hook_path)?;
312
313 if existing.contains(HOOK_MARKER) {
315 return Ok(());
316 }
317
318 if existing.contains(OLD_HOOK_MARKER) {
320 let mut new_content = String::new();
321 let mut skip = false;
322 for line in existing.lines() {
323 if line.contains(OLD_HOOK_MARKER) {
324 skip = true;
325 continue;
326 }
327 if skip {
328 if line.starts_with("tracevault ") {
330 continue;
331 }
332 skip = false;
333 }
334 new_content.push_str(line);
335 new_content.push('\n');
336 }
337 if !new_content.ends_with('\n') {
338 new_content.push('\n');
339 }
340 new_content.push_str(&tracevault_block);
341 fs::write(&hook_path, new_content)?;
342 } else {
343 let mut content = existing;
345 if !content.ends_with('\n') {
346 content.push('\n');
347 }
348 content.push_str(&tracevault_block);
349 fs::write(&hook_path, content)?;
350 }
351 } else {
352 let content = format!("#!/bin/sh\n{tracevault_block}");
353 fs::write(&hook_path, content)?;
354 }
355
356 #[cfg(unix)]
358 {
359 use std::os::unix::fs::PermissionsExt;
360 let mut perms = fs::metadata(&hook_path)?.permissions();
361 perms.set_mode(0o755);
362 fs::set_permissions(&hook_path, perms)?;
363 }
364
365 Ok(())
366}
367
368const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
369
370fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
371 let hooks_dir = project_root.join(".git/hooks");
372 fs::create_dir_all(&hooks_dir)?;
373
374 let hook_path = hooks_dir.join("post-commit");
375 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
376
377 if hook_path.exists() {
378 let existing = fs::read_to_string(&hook_path)?;
379
380 if existing.contains(POST_COMMIT_MARKER) {
381 return Ok(());
382 }
383
384 let mut content = existing;
385 if !content.ends_with('\n') {
386 content.push('\n');
387 }
388 content.push_str(&tracevault_block);
389 fs::write(&hook_path, content)?;
390 } else {
391 let content = format!("#!/bin/sh\n{tracevault_block}");
392 fs::write(&hook_path, content)?;
393 }
394
395 #[cfg(unix)]
396 {
397 use std::os::unix::fs::PermissionsExt;
398 let mut perms = fs::metadata(&hook_path)?.permissions();
399 perms.set_mode(0o755);
400 fs::set_permissions(&hook_path, perms)?;
401 }
402
403 Ok(())
404}
405
406fn install_claude_hooks(
407 project_root: &Path,
408 target: ClaudeSettingsTarget,
409) -> Result<(), io::Error> {
410 let claude_dir = project_root.join(".claude");
411 fs::create_dir_all(&claude_dir)?;
412
413 let filename = target.filename();
414 let settings_path = claude_dir.join(filename);
415 let mut settings: serde_json::Value = if settings_path.exists() {
416 let content = fs::read_to_string(&settings_path)?;
417 serde_json::from_str(&content).map_err(|e| {
418 io::Error::new(
419 io::ErrorKind::InvalidData,
420 format!("Failed to parse .claude/{filename}: {e}"),
421 )
422 })?
423 } else {
424 serde_json::json!({})
425 };
426
427 let hooks = tracevault_hooks();
428
429 let settings_obj = settings.as_object_mut().ok_or_else(|| {
431 io::Error::new(
432 io::ErrorKind::InvalidData,
433 format!(".claude/{filename} is not a JSON object"),
434 )
435 })?;
436
437 settings_obj.insert("hooks".to_string(), hooks);
438
439 let formatted = serde_json::to_string_pretty(&settings)
440 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
441 fs::write(&settings_path, formatted)?;
442
443 Ok(())
444}
445
446pub fn tracevault_hooks() -> serde_json::Value {
447 serde_json::json!({
448 "PreToolUse": [{
449 "matcher": "Write|Edit|Bash",
450 "hooks": [{
451 "type": "command",
452 "command": "tracevault stream --event pre-tool-use",
453 "timeout": 10,
454 "statusMessage": "TraceVault: streaming pre-tool event"
455 }]
456 }],
457 "PostToolUse": [{
458 "matcher": "",
459 "hooks": [{
460 "type": "command",
461 "command": "tracevault stream --event post-tool-use",
462 "timeout": 10,
463 "statusMessage": "TraceVault: streaming post-tool event"
464 }]
465 }],
466 "Notification": [{
467 "matcher": "",
468 "hooks": [{
469 "type": "command",
470 "command": "tracevault stream --event notification",
471 "timeout": 10,
472 "statusMessage": "TraceVault: streaming notification"
473 }]
474 }],
475 "Stop": [{
476 "matcher": "",
477 "hooks": [{
478 "type": "command",
479 "command": "tracevault stream --event stop",
480 "timeout": 10,
481 "statusMessage": "TraceVault: finalizing session"
482 }]
483 }]
484 })
485}
486
487#[cfg(test)]
488mod tests {
489 use super::*;
490
491 #[test]
492 fn linked_worktree_primary_detects_linked_and_primary() {
493 let tmp = tempfile::tempdir().unwrap();
494 let repo = tmp.path().join("repo");
495 let wt = tmp.path().join("linked-wt");
496 std::fs::create_dir_all(&repo).unwrap();
497 crate::test_helpers::init_git_repo(&repo);
498 crate::test_helpers::add_worktree(&repo, &wt);
499
500 assert!(
502 linked_worktree_primary(&repo).is_none(),
503 "primary checkout must not be flagged as a linked worktree"
504 );
505 let primary = linked_worktree_primary(&wt).expect("linked worktree must be detected");
507 assert_eq!(
508 primary.canonicalize().unwrap(),
509 repo.canonicalize().unwrap(),
510 "must resolve to the primary repo root"
511 );
512 }
513
514 #[test]
515 fn linked_worktree_primary_none_for_non_git() {
516 let tmp = tempfile::tempdir().unwrap();
517 assert!(
518 linked_worktree_primary(tmp.path()).is_none(),
519 "a non-git directory is not a linked worktree"
520 );
521 }
522
523 #[test]
524 fn parse_github_org_ssh() {
525 assert_eq!(
526 parse_github_org("git@github.com:myorg/myrepo.git"),
527 Some("myorg".into())
528 );
529 }
530
531 #[test]
532 fn parse_github_org_https() {
533 assert_eq!(
534 parse_github_org("https://github.com/myorg/myrepo"),
535 Some("myorg".into())
536 );
537 }
538
539 #[test]
540 fn parse_github_org_non_github_returns_none() {
541 assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
542 }
543
544 #[test]
545 fn parse_github_org_invalid() {
546 assert_eq!(parse_github_org("not-a-url"), None);
547 }
548}