1use std::fs;
7use std::io::Write as IoWrite;
8use std::path::{Path, PathBuf};
9use std::process::{Command, Stdio};
10
11use crate::error::{DotAgentError, Result};
12use crate::profile::{Profile, ProfileManager};
13
14const RULES_DIR: &str = "rules";
15
16#[derive(Debug)]
22pub struct Rule {
23 pub name: String,
24 pub path: PathBuf,
25 pub content: String,
26}
27
28impl Rule {
29 pub fn load(path: &Path) -> Result<Self> {
31 if !path.exists() {
32 return Err(DotAgentError::RuleNotFound {
33 name: path
34 .file_stem()
35 .map(|s| s.to_string_lossy().to_string())
36 .unwrap_or_default(),
37 });
38 }
39
40 let content = fs::read_to_string(path)?;
41 let name = path
42 .file_stem()
43 .map(|s| s.to_string_lossy().to_string())
44 .unwrap_or_default();
45
46 Ok(Self {
47 name,
48 path: path.to_path_buf(),
49 content,
50 })
51 }
52
53 pub fn summary(&self) -> String {
55 self.content
56 .lines()
57 .find(|line| !line.is_empty() && !line.starts_with('#'))
58 .unwrap_or("(no description)")
59 .chars()
60 .take(60)
61 .collect()
62 }
63}
64
65pub struct RuleManager {
71 base_dir: PathBuf,
72}
73
74impl RuleManager {
75 pub fn new(base_dir: PathBuf) -> Self {
76 Self { base_dir }
77 }
78
79 pub fn rules_dir(&self) -> PathBuf {
80 self.base_dir.join(RULES_DIR)
81 }
82
83 fn rule_path(&self, name: &str) -> PathBuf {
84 self.rules_dir().join(format!("{}.md", name))
85 }
86
87 pub fn list(&self) -> Result<Vec<Rule>> {
89 let dir = self.rules_dir();
90 if !dir.exists() {
91 return Ok(Vec::new());
92 }
93
94 let mut rules = Vec::new();
95 for entry in fs::read_dir(&dir)? {
96 let entry = entry?;
97 let path = entry.path();
98 if path.extension().is_some_and(|ext| ext == "md") {
99 if let Ok(rule) = Rule::load(&path) {
100 rules.push(rule);
101 }
102 }
103 }
104
105 rules.sort_by(|a, b| a.name.cmp(&b.name));
106 Ok(rules)
107 }
108
109 pub fn get(&self, name: &str) -> Result<Rule> {
111 let path = self.rule_path(name);
112 Rule::load(&path)
113 }
114
115 pub fn create(&self, name: &str) -> Result<Rule> {
117 validate_name(name)?;
118
119 let path = self.rule_path(name);
120 if path.exists() {
121 return Err(DotAgentError::RuleAlreadyExists {
122 name: name.to_string(),
123 });
124 }
125
126 fs::create_dir_all(self.rules_dir())?;
127
128 let template = generate_rule_template(name);
129 fs::write(&path, &template)?;
130
131 Rule::load(&path)
132 }
133
134 pub fn import(&self, name: &str, source_file: &Path) -> Result<Rule> {
136 validate_name(name)?;
137
138 let path = self.rule_path(name);
139 if path.exists() {
140 return Err(DotAgentError::RuleAlreadyExists {
141 name: name.to_string(),
142 });
143 }
144
145 fs::create_dir_all(self.rules_dir())?;
146 fs::copy(source_file, &path)?;
147
148 Rule::load(&path)
149 }
150
151 pub fn remove(&self, name: &str) -> Result<()> {
153 let rule = self.get(name)?;
154 fs::remove_file(&rule.path)?;
155 Ok(())
156 }
157
158 pub fn rename(&self, name: &str, new_name: &str) -> Result<Rule> {
160 validate_name(new_name)?;
161
162 let old_path = self.rule_path(name);
163 if !old_path.exists() {
164 return Err(DotAgentError::RuleNotFound {
165 name: name.to_string(),
166 });
167 }
168
169 let new_path = self.rule_path(new_name);
170 if new_path.exists() {
171 return Err(DotAgentError::RuleAlreadyExists {
172 name: new_name.to_string(),
173 });
174 }
175
176 fs::rename(&old_path, &new_path)?;
177 Rule::load(&new_path)
178 }
179
180 pub fn update(&self, name: &str, content: &str) -> Result<Rule> {
182 let path = self.rule_path(name);
183 if !path.exists() {
184 return Err(DotAgentError::RuleNotFound {
185 name: name.to_string(),
186 });
187 }
188
189 fs::write(&path, content)?;
190 Rule::load(&path)
191 }
192}
193
194#[derive(Debug)]
200pub struct ApplyResult {
201 pub new_profile_name: String,
202 pub new_profile_path: PathBuf,
203 pub files_modified: usize,
204}
205
206pub struct RuleExecutor<'a> {
208 rule: &'a Rule,
209 profile_manager: &'a ProfileManager,
210}
211
212impl<'a> RuleExecutor<'a> {
213 pub fn new(rule: &'a Rule, profile_manager: &'a ProfileManager) -> Self {
214 Self {
215 rule,
216 profile_manager,
217 }
218 }
219
220 pub fn generate_prompt(&self, profile: &Profile) -> Result<String> {
222 let mut files_content = String::new();
224 for entry in walkdir::WalkDir::new(&profile.path)
225 .into_iter()
226 .filter_map(|e| e.ok())
227 .filter(|e| e.path().is_file())
228 .filter(|e| {
229 e.path()
230 .extension()
231 .is_some_and(|ext| ext == "md" || ext == "toml")
232 })
233 {
234 if let Ok(content) = fs::read_to_string(entry.path()) {
235 let relative = entry
236 .path()
237 .strip_prefix(&profile.path)
238 .unwrap_or(entry.path());
239 files_content.push_str(&format!(
240 "### {}\n```\n{}\n```\n\n",
241 relative.display(),
242 content
243 ));
244 }
245 }
246
247 Ok(format!(
248 r#"You are customizing a Claude Code configuration profile.
249
250## Source Profile: {}
251
252### Current Files
253{}
254
255## Customization Rule
256
257{}
258
259## Your Task
260
261Apply the customization rule to the profile. Output the changes in this format:
262
263```
264ACTION: CREATE|MODIFY|DELETE
265FILE: <relative path>
266CONTENT:
267<file content>
268```
269
270Only output file changes. No explanations needed.
271"#,
272 profile.name, files_content, self.rule.content
273 ))
274 }
275
276 pub fn apply(
278 &self,
279 profile: &Profile,
280 new_name: Option<&str>,
281 dry_run: bool,
282 ) -> Result<ApplyResult> {
283 if !check_claude_cli() {
284 return Err(DotAgentError::ClaudeNotFound);
285 }
286
287 let new_profile_name = new_name
289 .map(|s| s.to_string())
290 .unwrap_or_else(|| format!("{}-{}", profile.name, self.rule.name));
291
292 let new_profile_path = self.profile_manager.profiles_dir().join(&new_profile_name);
293
294 if dry_run {
295 return Ok(ApplyResult {
296 new_profile_name,
297 new_profile_path,
298 files_modified: 0,
299 });
300 }
301
302 let new_profile =
304 self.profile_manager
305 .import_profile(&profile.path, &new_profile_name, false)?;
306
307 let prompt = self.generate_prompt(profile)?;
309 let output = execute_claude(&new_profile.path, &prompt)?;
310
311 let files_modified = apply_ai_output(&new_profile.path, &output)?;
313
314 Ok(ApplyResult {
315 new_profile_name,
316 new_profile_path: new_profile.path,
317 files_modified,
318 })
319 }
320}
321
322pub fn extract_rule(profile: &Profile, rule_name: &str, manager: &RuleManager) -> Result<Rule> {
328 if !check_claude_cli() {
329 return Err(DotAgentError::ClaudeNotFound);
330 }
331
332 let mut files_content = String::new();
334 for entry in walkdir::WalkDir::new(&profile.path)
335 .into_iter()
336 .filter_map(|e| e.ok())
337 .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
338 {
339 if let Ok(content) = fs::read_to_string(entry.path()) {
340 let relative = entry
341 .path()
342 .strip_prefix(&profile.path)
343 .unwrap_or(entry.path());
344 files_content.push_str(&format!(
345 "### {}\n```\n{}\n```\n\n",
346 relative.display(),
347 content
348 ));
349 }
350 }
351
352 let extract_prompt = format!(
353 r#"Analyze this profile and extract the key customization patterns as a reusable rule.
354
355## Profile: {}
356
357{}
358
359## Task
360
361Create a markdown rule that captures:
3621. Language/framework specific patterns
3632. Coding style preferences
3643. Tool configurations
3654. Recommended libraries/crates
366
367Output ONLY the rule content in markdown format. Start with a heading.
368"#,
369 profile.name, files_content
370 );
371
372 let rules_dir = manager.rules_dir();
373 fs::create_dir_all(&rules_dir)?;
374
375 let generated_content = execute_claude(&rules_dir, &extract_prompt)?;
376
377 let rule_path = manager.rules_dir().join(format!("{}.md", rule_name));
379 fs::write(&rule_path, &generated_content)?;
380
381 Rule::load(&rule_path)
382}
383
384pub fn generate_rule(
387 instruction: &str,
388 rule_name: Option<&str>,
389 manager: &RuleManager,
390) -> Result<Rule> {
391 if !check_claude_cli() {
392 return Err(DotAgentError::ClaudeNotFound);
393 }
394
395 let rules_dir = manager.rules_dir();
396 fs::create_dir_all(&rules_dir)?;
397
398 let (final_name, generated_content) = match rule_name {
399 Some(name) => {
400 let prompt = format!(
401 r##"Create a customization rule based on this instruction:
402
403"{}"
404
405The rule will be used to customize Claude Code configuration profiles.
406
407Output a markdown document that includes:
4081. Clear section headings
4092. Specific patterns or conventions to follow
4103. Any recommended libraries, tools, or configurations
411
412Start with a heading like "# {} Customization Rule"
413"##,
414 instruction, name
415 );
416 let content = execute_claude(&rules_dir, &prompt)?;
417 (name.to_string(), content)
418 }
419 None => {
420 let prompt = format!(
421 r##"Create a customization rule based on this instruction:
422
423"{}"
424
425The rule will be used to customize Claude Code configuration profiles.
426
427IMPORTANT: On the FIRST line, output a suggested rule name in this exact format:
428NAME: <kebab-case-name>
429
430The name should be:
431- Lowercase kebab-case (e.g., "rust-optimization", "python-style")
432- Short and descriptive (2-4 words)
433- Based on the instruction content
434
435Then output a markdown document that includes:
4361. Clear section headings
4372. Specific patterns or conventions to follow
4383. Any recommended libraries, tools, or configurations
439"##,
440 instruction
441 );
442 let content = execute_claude(&rules_dir, &prompt)?;
443 let (name, content) = parse_name_from_output(&content)?;
444 (name, content)
445 }
446 };
447
448 let rule_path = rules_dir.join(format!("{}.md", final_name));
449 fs::write(&rule_path, &generated_content)?;
450
451 Rule::load(&rule_path)
452}
453
454fn parse_name_from_output(output: &str) -> Result<(String, String)> {
456 let mut lines = output.lines();
457
458 for line in lines.by_ref() {
460 let trimmed = line.trim();
461 if let Some(name) = trimmed.strip_prefix("NAME:") {
462 let name = name.trim().to_lowercase().replace(' ', "-");
463 if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
465 return Err(DotAgentError::RuleNotFound {
466 name: "AI generated invalid rule name".to_string(),
467 });
468 }
469 let remaining: String = lines.collect::<Vec<_>>().join("\n");
471 let content = remaining.trim_start().to_string();
472 return Ok((name, content));
473 }
474 }
475
476 Err(DotAgentError::RuleNotFound {
477 name: "AI did not generate NAME: line".to_string(),
478 })
479}
480
481fn check_claude_cli() -> bool {
486 Command::new("claude")
487 .arg("--version")
488 .stdout(Stdio::null())
489 .stderr(Stdio::null())
490 .status()
491 .map(|s| s.success())
492 .unwrap_or(false)
493}
494
495fn execute_claude(working_dir: &Path, prompt: &str) -> Result<String> {
496 let mut cmd = Command::new("claude");
497 cmd.arg("--print");
498 cmd.arg("--dangerously-skip-permissions");
499 cmd.current_dir(working_dir);
500 cmd.stdin(Stdio::piped());
501 cmd.stdout(Stdio::piped());
502 cmd.stderr(Stdio::piped());
503
504 let mut child = cmd
505 .spawn()
506 .map_err(|e| DotAgentError::ClaudeExecutionFailed {
507 message: format!("Failed to spawn claude: {}", e),
508 })?;
509
510 if let Some(mut stdin) = child.stdin.take() {
511 stdin
512 .write_all(prompt.as_bytes())
513 .map_err(|e| DotAgentError::ClaudeExecutionFailed {
514 message: format!("Failed to write prompt: {}", e),
515 })?;
516 }
517
518 let output = child
519 .wait_with_output()
520 .map_err(|e| DotAgentError::ClaudeExecutionFailed {
521 message: format!("Execution failed: {}", e),
522 })?;
523
524 if !output.status.success() {
525 let stderr = String::from_utf8_lossy(&output.stderr);
526 return Err(DotAgentError::ClaudeExecutionFailed {
527 message: format!("Claude exited with error: {}", stderr),
528 });
529 }
530
531 Ok(String::from_utf8_lossy(&output.stdout).to_string())
532}
533
534fn apply_ai_output(profile_path: &Path, output: &str) -> Result<usize> {
535 let mut files_modified = 0;
536
537 let mut lines = output.lines().peekable();
538 while let Some(line) = lines.next() {
539 if line.starts_with("ACTION:") {
540 let action = line.trim_start_matches("ACTION:").trim();
541
542 let file_line = lines.next().unwrap_or("");
543 if !file_line.starts_with("FILE:") {
544 continue;
545 }
546 let file_path = file_line.trim_start_matches("FILE:").trim();
547
548 let content_line = lines.next().unwrap_or("");
549 if !content_line.starts_with("CONTENT:") {
550 continue;
551 }
552
553 let mut content = String::new();
554 while let Some(line) = lines.peek() {
555 if line.starts_with("ACTION:") {
556 break;
557 }
558 content.push_str(lines.next().unwrap_or(""));
559 content.push('\n');
560 }
561
562 let target_path = profile_path.join(file_path);
563
564 match action {
565 "CREATE" | "MODIFY" => {
566 if let Some(parent) = target_path.parent() {
567 fs::create_dir_all(parent)?;
568 }
569 fs::write(&target_path, content.trim())?;
570 files_modified += 1;
571 }
572 "DELETE" => {
573 if target_path.exists() {
574 fs::remove_file(&target_path)?;
575 files_modified += 1;
576 }
577 }
578 _ => {}
579 }
580 }
581 }
582
583 Ok(files_modified)
584}
585
586fn validate_name(name: &str) -> Result<()> {
587 if name.is_empty() || name.len() > 64 {
588 return Err(DotAgentError::InvalidRuleName {
589 name: name.to_string(),
590 });
591 }
592
593 let first = name.chars().next().unwrap();
594 if !first.is_ascii_alphabetic() {
595 return Err(DotAgentError::InvalidRuleName {
596 name: name.to_string(),
597 });
598 }
599
600 for c in name.chars() {
601 if !c.is_ascii_alphanumeric() && c != '-' && c != '_' {
602 return Err(DotAgentError::InvalidRuleName {
603 name: name.to_string(),
604 });
605 }
606 }
607
608 Ok(())
609}
610
611fn generate_rule_template(name: &str) -> String {
612 format!(
613 r#"# {} Customization Rule
614
615## Language
616(e.g., Rust, Kotlin, TypeScript)
617
618## Recommended Libraries
619- library1
620- library2
621
622## Coding Style
623- Style guideline 1
624- Style guideline 2
625
626## Replace Sections
627(Describe what sections to replace and with what content)
628
629## Additional Rules
630(Any other customization instructions)
631"#,
632 name
633 )
634}
635
636#[cfg(test)]
637mod tests {
638 use super::*;
639 use tempfile::TempDir;
640
641 #[test]
642 fn test_validate_name_valid() {
643 assert!(validate_name("rust").is_ok());
644 assert!(validate_name("my-rule").is_ok());
645 assert!(validate_name("python_3").is_ok());
646 }
647
648 #[test]
649 fn test_validate_name_invalid() {
650 assert!(validate_name("").is_err());
651 assert!(validate_name("123start").is_err());
652 assert!(validate_name("has space").is_err());
653 assert!(validate_name("has.dot").is_err());
654 }
655
656 #[test]
657 fn test_create_rule() {
658 let temp = TempDir::new().unwrap();
659 let manager = RuleManager::new(temp.path().to_path_buf());
660
661 let rule = manager.create("test").unwrap();
662 assert_eq!(rule.name, "test");
663 assert!(rule.path.exists());
664 assert!(rule.content.contains("# test Customization Rule"));
665 }
666
667 #[test]
668 fn test_list_rules() {
669 let temp = TempDir::new().unwrap();
670 let manager = RuleManager::new(temp.path().to_path_buf());
671
672 manager.create("alpha").unwrap();
673 manager.create("beta").unwrap();
674
675 let list = manager.list().unwrap();
676 assert_eq!(list.len(), 2);
677 assert_eq!(list[0].name, "alpha");
678 assert_eq!(list[1].name, "beta");
679 }
680
681 #[test]
682 fn test_remove_rule() {
683 let temp = TempDir::new().unwrap();
684 let manager = RuleManager::new(temp.path().to_path_buf());
685
686 manager.create("test").unwrap();
687 assert!(manager.get("test").is_ok());
688
689 manager.remove("test").unwrap();
690 assert!(manager.get("test").is_err());
691 }
692
693 #[test]
694 fn test_rule_already_exists() {
695 let temp = TempDir::new().unwrap();
696 let manager = RuleManager::new(temp.path().to_path_buf());
697
698 manager.create("test").unwrap();
699 let result = manager.create("test");
700 assert!(matches!(
701 result,
702 Err(DotAgentError::RuleAlreadyExists { .. })
703 ));
704 }
705}