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