1use crate::api_client::ApiClient;
2use crate::config::TracevaultConfig;
3use std::fs;
4use std::io::{self, BufRead, IsTerminal, Write};
5use std::path::Path;
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
88pub async fn init_in_directory(
89 project_root: &Path,
90 server_url: Option<&str>,
91 claude_settings: Option<ClaudeSettingsTarget>,
92) -> Result<ClaudeSettingsTarget, io::Error> {
93 if !project_root.join(".git").exists() {
95 return Err(io::Error::new(
96 io::ErrorKind::NotFound,
97 "Not a git repository. Run 'git init' first.",
98 ));
99 }
100
101 let target = resolve_claude_target(claude_settings)?;
102
103 let config_dir = TracevaultConfig::config_dir(project_root);
105 fs::create_dir_all(&config_dir)?;
106 fs::create_dir_all(config_dir.join("sessions"))?;
107 fs::create_dir_all(config_dir.join("cache"))?;
108
109 update_root_gitignore(project_root, target)?;
111
112 let remote_url = git_remote_url(project_root);
114 if remote_url.is_none() {
115 eprintln!("Warning: no git remote 'origin' configured. Skipping server registration.");
116 eprintln!("Run 'git remote add origin <url>' then 'tracevault sync' to register.");
117 }
118
119 let org_slug = remote_url.as_deref().and_then(parse_github_org);
121
122 let mut config = TracevaultConfig::default();
124 if let Some(url) = server_url {
125 config.server_url = Some(url.to_string());
126 }
127 config.org_slug = org_slug.clone();
128 fs::write(
129 TracevaultConfig::config_path(project_root),
130 config.to_toml(),
131 )?;
132
133 install_claude_hooks(project_root, target)?;
135
136 install_git_hook(project_root)?;
138 install_post_commit_hook(project_root)?;
139
140 let detected = crate::hooks::detect_tools(project_root);
142 for tool in &detected {
143 println!(" Detected: {}", tool.name());
144 }
145
146 let (resolved_url, resolved_token) = crate::api_client::resolve_credentials(project_root);
147 let effective_url = server_url.map(String::from).or(resolved_url);
148
149 if resolved_token.is_none() {
150 eprintln!("Not logged in. Run 'tracevault login' to register this repo with the server.");
151 } else if let (Some(url), Some(remote), Some(slug)) = (effective_url, remote_url, org_slug) {
152 let client = ApiClient::new(&url, resolved_token.as_deref());
153 let repo_name = git_repo_name(project_root);
154
155 match client
156 .register_repo(
157 &slug,
158 crate::api_client::RegisterRepoRequest {
159 repo_name,
160 github_url: Some(remote),
161 },
162 )
163 .await
164 {
165 Ok(resp) => {
166 println!("Repo registered on server (id: {})", resp.repo_id);
167 if let Some(mut cfg) = TracevaultConfig::load(project_root) {
169 cfg.repo_id = Some(resp.repo_id.to_string());
170 let _ = fs::write(TracevaultConfig::config_path(project_root), cfg.to_toml());
171 }
172 }
173 Err(e) => {
174 let msg = e.to_string();
175 if msg.contains("404") {
176 eprintln!("Warning: organization '{}' not found on the server.", slug);
177 eprintln!(
178 "Create it first at your TraceVault instance, then run 'tracevault sync'."
179 );
180 } else if msg.contains("403") {
181 eprintln!("Warning: you are not a member of organization '{}'.", slug);
182 } else {
183 eprintln!("Warning: could not register repo on server: {e}");
184 }
185 }
186 }
187 }
188
189 Ok(target)
190}
191
192fn update_root_gitignore(
193 project_root: &Path,
194 claude_target: ClaudeSettingsTarget,
195) -> Result<(), io::Error> {
196 let path = project_root.join(".gitignore");
197 let existing = if path.exists() {
198 fs::read_to_string(&path)?
199 } else {
200 String::new()
201 };
202
203 let needed: Vec<&str> = [".tracevault/", claude_target.gitignore_entry()]
204 .iter()
205 .copied()
206 .filter(|entry| !existing.lines().any(|line| line.trim() == *entry))
207 .collect();
208
209 if needed.is_empty() {
210 return Ok(());
211 }
212
213 let mut content = existing;
214 if !content.is_empty() && !content.ends_with('\n') {
215 content.push('\n');
216 }
217 content.push_str("\n# TraceVault — local only, do not commit\n");
218 for entry in needed {
219 content.push_str(entry);
220 content.push('\n');
221 }
222
223 fs::write(path, content)
224}
225
226fn git_repo_name(project_root: &Path) -> String {
227 std::process::Command::new("git")
228 .args(["rev-parse", "--show-toplevel"])
229 .current_dir(project_root)
230 .output()
231 .ok()
232 .filter(|o| o.status.success())
233 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
234 .as_deref()
235 .and_then(|p| p.rsplit('/').next())
236 .map(String::from)
237 .unwrap_or_else(|| "unknown".into())
238}
239
240const HOOK_MARKER: &str = "# tracevault:enforce";
241const OLD_HOOK_MARKER: &str = "# tracevault:auto-push";
242
243fn install_git_hook(project_root: &Path) -> Result<(), io::Error> {
244 let hooks_dir = project_root.join(".git/hooks");
245 fs::create_dir_all(&hooks_dir)?;
246
247 let hook_path = hooks_dir.join("pre-push");
248 let tracevault_block = format!(
249 "{HOOK_MARKER}\ntracevault sync 2>/dev/null || true\ntracevault check || {{ echo \"tracevault: policy check failed\"; exit 1; }}\n"
250 );
251
252 if hook_path.exists() {
253 let existing = fs::read_to_string(&hook_path)?;
254
255 if existing.contains(HOOK_MARKER) {
257 return Ok(());
258 }
259
260 if existing.contains(OLD_HOOK_MARKER) {
262 let mut new_content = String::new();
263 let mut skip = false;
264 for line in existing.lines() {
265 if line.contains(OLD_HOOK_MARKER) {
266 skip = true;
267 continue;
268 }
269 if skip {
270 if line.starts_with("tracevault ") {
272 continue;
273 }
274 skip = false;
275 }
276 new_content.push_str(line);
277 new_content.push('\n');
278 }
279 if !new_content.ends_with('\n') {
280 new_content.push('\n');
281 }
282 new_content.push_str(&tracevault_block);
283 fs::write(&hook_path, new_content)?;
284 } else {
285 let mut content = existing;
287 if !content.ends_with('\n') {
288 content.push('\n');
289 }
290 content.push_str(&tracevault_block);
291 fs::write(&hook_path, content)?;
292 }
293 } else {
294 let content = format!("#!/bin/sh\n{tracevault_block}");
295 fs::write(&hook_path, content)?;
296 }
297
298 #[cfg(unix)]
300 {
301 use std::os::unix::fs::PermissionsExt;
302 let mut perms = fs::metadata(&hook_path)?.permissions();
303 perms.set_mode(0o755);
304 fs::set_permissions(&hook_path, perms)?;
305 }
306
307 Ok(())
308}
309
310const POST_COMMIT_MARKER: &str = "# tracevault:post-commit";
311
312fn install_post_commit_hook(project_root: &Path) -> Result<(), io::Error> {
313 let hooks_dir = project_root.join(".git/hooks");
314 fs::create_dir_all(&hooks_dir)?;
315
316 let hook_path = hooks_dir.join("post-commit");
317 let tracevault_block = format!("{POST_COMMIT_MARKER}\ntracevault commit-push 2>/dev/null &\n");
318
319 if hook_path.exists() {
320 let existing = fs::read_to_string(&hook_path)?;
321
322 if existing.contains(POST_COMMIT_MARKER) {
323 return Ok(());
324 }
325
326 let mut content = existing;
327 if !content.ends_with('\n') {
328 content.push('\n');
329 }
330 content.push_str(&tracevault_block);
331 fs::write(&hook_path, content)?;
332 } else {
333 let content = format!("#!/bin/sh\n{tracevault_block}");
334 fs::write(&hook_path, content)?;
335 }
336
337 #[cfg(unix)]
338 {
339 use std::os::unix::fs::PermissionsExt;
340 let mut perms = fs::metadata(&hook_path)?.permissions();
341 perms.set_mode(0o755);
342 fs::set_permissions(&hook_path, perms)?;
343 }
344
345 Ok(())
346}
347
348fn install_claude_hooks(
349 project_root: &Path,
350 target: ClaudeSettingsTarget,
351) -> Result<(), io::Error> {
352 let claude_dir = project_root.join(".claude");
353 fs::create_dir_all(&claude_dir)?;
354
355 let filename = target.filename();
356 let settings_path = claude_dir.join(filename);
357 let mut settings: serde_json::Value = if settings_path.exists() {
358 let content = fs::read_to_string(&settings_path)?;
359 serde_json::from_str(&content).map_err(|e| {
360 io::Error::new(
361 io::ErrorKind::InvalidData,
362 format!("Failed to parse .claude/{filename}: {e}"),
363 )
364 })?
365 } else {
366 serde_json::json!({})
367 };
368
369 let hooks = tracevault_hooks();
370
371 let settings_obj = settings.as_object_mut().ok_or_else(|| {
373 io::Error::new(
374 io::ErrorKind::InvalidData,
375 format!(".claude/{filename} is not a JSON object"),
376 )
377 })?;
378
379 settings_obj.insert("hooks".to_string(), hooks);
380
381 let formatted = serde_json::to_string_pretty(&settings)
382 .map_err(|e| io::Error::other(format!("Failed to serialize settings: {e}")))?;
383 fs::write(&settings_path, formatted)?;
384
385 Ok(())
386}
387
388pub fn tracevault_hooks() -> serde_json::Value {
389 serde_json::json!({
390 "PreToolUse": [{
391 "matcher": "Write|Edit|Bash",
392 "hooks": [{
393 "type": "command",
394 "command": "tracevault stream --event pre-tool-use",
395 "timeout": 10,
396 "statusMessage": "TraceVault: streaming pre-tool event"
397 }]
398 }],
399 "PostToolUse": [{
400 "matcher": "",
401 "hooks": [{
402 "type": "command",
403 "command": "tracevault stream --event post-tool-use",
404 "timeout": 10,
405 "statusMessage": "TraceVault: streaming post-tool event"
406 }]
407 }],
408 "Notification": [{
409 "matcher": "",
410 "hooks": [{
411 "type": "command",
412 "command": "tracevault stream --event notification",
413 "timeout": 10,
414 "statusMessage": "TraceVault: streaming notification"
415 }]
416 }],
417 "Stop": [{
418 "matcher": "",
419 "hooks": [{
420 "type": "command",
421 "command": "tracevault stream --event stop",
422 "timeout": 10,
423 "statusMessage": "TraceVault: finalizing session"
424 }]
425 }]
426 })
427}
428
429#[cfg(test)]
430mod tests {
431 use super::*;
432
433 #[test]
434 fn parse_github_org_ssh() {
435 assert_eq!(
436 parse_github_org("git@github.com:myorg/myrepo.git"),
437 Some("myorg".into())
438 );
439 }
440
441 #[test]
442 fn parse_github_org_https() {
443 assert_eq!(
444 parse_github_org("https://github.com/myorg/myrepo"),
445 Some("myorg".into())
446 );
447 }
448
449 #[test]
450 fn parse_github_org_non_github_returns_none() {
451 assert_eq!(parse_github_org("https://gitlab.com/org/repo"), None);
452 }
453
454 #[test]
455 fn parse_github_org_invalid() {
456 assert_eq!(parse_github_org("not-a-url"), None);
457 }
458}