dot-agent-core 0.4.2

Core library for dot-agent profile management
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Rule module for profile customization.
//!
//! Rules are simple markdown files that describe how to customize a profile.
//! They are applied to base profiles to create new customized profiles.

use std::fs;
use std::io::Write as IoWrite;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};

use crate::error::{DotAgentError, Result};
use crate::profile::{Profile, ProfileManager};

const RULES_DIR: &str = "rules";

// ============================================================================
// Rule Entity
// ============================================================================

/// A customization rule (single markdown file).
#[derive(Debug)]
pub struct Rule {
    pub name: String,
    pub path: PathBuf,
    pub content: String,
}

impl Rule {
    /// Load a rule from its file path.
    pub fn load(path: &Path) -> Result<Self> {
        if !path.exists() {
            return Err(DotAgentError::RuleNotFound {
                name: path
                    .file_stem()
                    .map(|s| s.to_string_lossy().to_string())
                    .unwrap_or_default(),
            });
        }

        let content = fs::read_to_string(path)?;
        let name = path
            .file_stem()
            .map(|s| s.to_string_lossy().to_string())
            .unwrap_or_default();

        Ok(Self {
            name,
            path: path.to_path_buf(),
            content,
        })
    }

    /// Get a short summary (first non-empty, non-heading line).
    pub fn summary(&self) -> String {
        self.content
            .lines()
            .find(|line| !line.is_empty() && !line.starts_with('#'))
            .unwrap_or("(no description)")
            .chars()
            .take(60)
            .collect()
    }
}

// ============================================================================
// RuleManager
// ============================================================================

/// Manages rule CRUD operations.
pub struct RuleManager {
    base_dir: PathBuf,
}

impl RuleManager {
    pub fn new(base_dir: PathBuf) -> Self {
        Self { base_dir }
    }

    pub fn rules_dir(&self) -> PathBuf {
        self.base_dir.join(RULES_DIR)
    }

    fn rule_path(&self, name: &str) -> PathBuf {
        self.rules_dir().join(format!("{}.md", name))
    }

    /// List all registered rules.
    pub fn list(&self) -> Result<Vec<Rule>> {
        let dir = self.rules_dir();
        if !dir.exists() {
            return Ok(Vec::new());
        }

        let mut rules = Vec::new();
        for entry in fs::read_dir(&dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "md") {
                if let Ok(rule) = Rule::load(&path) {
                    rules.push(rule);
                }
            }
        }

        rules.sort_by(|a, b| a.name.cmp(&b.name));
        Ok(rules)
    }

    /// Get a specific rule by name.
    pub fn get(&self, name: &str) -> Result<Rule> {
        let path = self.rule_path(name);
        Rule::load(&path)
    }

    /// Create a new rule with template content.
    pub fn create(&self, name: &str) -> Result<Rule> {
        validate_name(name)?;

        let path = self.rule_path(name);
        if path.exists() {
            return Err(DotAgentError::RuleAlreadyExists {
                name: name.to_string(),
            });
        }

        fs::create_dir_all(self.rules_dir())?;

        let template = generate_rule_template(name);
        fs::write(&path, &template)?;

        Rule::load(&path)
    }

    /// Import a rule from an existing markdown file.
    pub fn import(&self, name: &str, source_file: &Path) -> Result<Rule> {
        validate_name(name)?;

        let path = self.rule_path(name);
        if path.exists() {
            return Err(DotAgentError::RuleAlreadyExists {
                name: name.to_string(),
            });
        }

        fs::create_dir_all(self.rules_dir())?;
        fs::copy(source_file, &path)?;

        Rule::load(&path)
    }

    /// Remove a rule.
    pub fn remove(&self, name: &str) -> Result<()> {
        let rule = self.get(name)?;
        fs::remove_file(&rule.path)?;
        Ok(())
    }

    /// Rename a rule.
    pub fn rename(&self, name: &str, new_name: &str) -> Result<Rule> {
        validate_name(new_name)?;

        let old_path = self.rule_path(name);
        if !old_path.exists() {
            return Err(DotAgentError::RuleNotFound {
                name: name.to_string(),
            });
        }

        let new_path = self.rule_path(new_name);
        if new_path.exists() {
            return Err(DotAgentError::RuleAlreadyExists {
                name: new_name.to_string(),
            });
        }

        fs::rename(&old_path, &new_path)?;
        Rule::load(&new_path)
    }

    /// Update rule content.
    pub fn update(&self, name: &str, content: &str) -> Result<Rule> {
        let path = self.rule_path(name);
        if !path.exists() {
            return Err(DotAgentError::RuleNotFound {
                name: name.to_string(),
            });
        }

        fs::write(&path, content)?;
        Rule::load(&path)
    }
}

// ============================================================================
// RuleExecutor - Applies rule to profile
// ============================================================================

/// Result of rule application.
#[derive(Debug)]
pub struct ApplyResult {
    pub new_profile_name: String,
    pub new_profile_path: PathBuf,
    pub files_modified: usize,
}

/// Executes a rule against a profile to create a new customized profile.
pub struct RuleExecutor<'a> {
    rule: &'a Rule,
    profile_manager: &'a ProfileManager,
}

impl<'a> RuleExecutor<'a> {
    pub fn new(rule: &'a Rule, profile_manager: &'a ProfileManager) -> Self {
        Self {
            rule,
            profile_manager,
        }
    }

    /// Generate the full prompt for AI.
    pub fn generate_prompt(&self, profile: &Profile) -> Result<String> {
        // Collect profile files for context
        let mut files_content = String::new();
        for entry in walkdir::WalkDir::new(&profile.path)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.path().is_file())
            .filter(|e| {
                e.path()
                    .extension()
                    .is_some_and(|ext| ext == "md" || ext == "toml")
            })
        {
            if let Ok(content) = fs::read_to_string(entry.path()) {
                let relative = entry
                    .path()
                    .strip_prefix(&profile.path)
                    .unwrap_or(entry.path());
                files_content.push_str(&format!(
                    "### {}\n```\n{}\n```\n\n",
                    relative.display(),
                    content
                ));
            }
        }

        Ok(format!(
            r#"You are customizing a Claude Code configuration profile.

## Source Profile: {}

### Current Files
{}

## Customization Rule

{}

## Your Task

Apply the customization rule to the profile. Output the changes in this format:

```
ACTION: CREATE|MODIFY|DELETE
FILE: <relative path>
CONTENT:
<file content>
```

Only output file changes. No explanations needed.
"#,
            profile.name, files_content, self.rule.content
        ))
    }

    /// Apply the rule to create a new profile.
    pub fn apply(
        &self,
        profile: &Profile,
        new_name: Option<&str>,
        dry_run: bool,
    ) -> Result<ApplyResult> {
        if !check_claude_cli() {
            return Err(DotAgentError::ClaudeNotFound);
        }

        // Determine new profile name
        let new_profile_name = new_name
            .map(|s| s.to_string())
            .unwrap_or_else(|| format!("{}-{}", profile.name, self.rule.name));

        let new_profile_path = self.profile_manager.profiles_dir().join(&new_profile_name);

        if dry_run {
            return Ok(ApplyResult {
                new_profile_name,
                new_profile_path,
                files_modified: 0,
            });
        }

        // Copy base profile to new location
        let new_profile =
            self.profile_manager
                .import_profile(&profile.path, &new_profile_name, false)?;

        // Generate prompt and execute AI
        let prompt = self.generate_prompt(profile)?;
        let output = execute_claude(&new_profile.path, &prompt)?;

        // Apply changes
        let files_modified = apply_ai_output(&new_profile.path, &output)?;

        Ok(ApplyResult {
            new_profile_name,
            new_profile_path: new_profile.path,
            files_modified,
        })
    }
}

// ============================================================================
// AI Operations
// ============================================================================

/// Extract a rule from an existing profile using AI.
pub fn extract_rule(profile: &Profile, rule_name: &str, manager: &RuleManager) -> Result<Rule> {
    if !check_claude_cli() {
        return Err(DotAgentError::ClaudeNotFound);
    }

    // Collect profile files
    let mut files_content = String::new();
    for entry in walkdir::WalkDir::new(&profile.path)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.path().extension().is_some_and(|ext| ext == "md"))
    {
        if let Ok(content) = fs::read_to_string(entry.path()) {
            let relative = entry
                .path()
                .strip_prefix(&profile.path)
                .unwrap_or(entry.path());
            files_content.push_str(&format!(
                "### {}\n```\n{}\n```\n\n",
                relative.display(),
                content
            ));
        }
    }

    let extract_prompt = format!(
        r#"Analyze this profile and extract the key customization patterns as a reusable rule.

## Profile: {}

{}

## Task

Create a markdown rule that captures:
1. Language/framework specific patterns
2. Coding style preferences
3. Tool configurations
4. Recommended libraries/crates

Output ONLY the rule content in markdown format. Start with a heading.
"#,
        profile.name, files_content
    );

    let rules_dir = manager.rules_dir();
    fs::create_dir_all(&rules_dir)?;

    let generated_content = execute_claude(&rules_dir, &extract_prompt)?;

    // Create the rule file
    let rule_path = manager.rules_dir().join(format!("{}.md", rule_name));
    fs::write(&rule_path, &generated_content)?;

    Rule::load(&rule_path)
}

/// Generate a rule from natural language instruction.
/// If `rule_name` is None, the AI will generate a suitable name.
pub fn generate_rule(
    instruction: &str,
    rule_name: Option<&str>,
    manager: &RuleManager,
) -> Result<Rule> {
    if !check_claude_cli() {
        return Err(DotAgentError::ClaudeNotFound);
    }

    let rules_dir = manager.rules_dir();
    fs::create_dir_all(&rules_dir)?;

    let (final_name, generated_content) = match rule_name {
        Some(name) => {
            let prompt = format!(
                r##"Create a customization rule based on this instruction:

"{}"

The rule will be used to customize Claude Code configuration profiles.

Output a markdown document that includes:
1. Clear section headings
2. Specific patterns or conventions to follow
3. Any recommended libraries, tools, or configurations

Start with a heading like "# {} Customization Rule"
"##,
                instruction, name
            );
            let content = execute_claude(&rules_dir, &prompt)?;
            (name.to_string(), content)
        }
        None => {
            let prompt = format!(
                r##"Create a customization rule based on this instruction:

"{}"

The rule will be used to customize Claude Code configuration profiles.

IMPORTANT: On the FIRST line, output a suggested rule name in this exact format:
NAME: <kebab-case-name>

The name should be:
- Lowercase kebab-case (e.g., "rust-optimization", "python-style")
- Short and descriptive (2-4 words)
- Based on the instruction content

Then output a markdown document that includes:
1. Clear section headings
2. Specific patterns or conventions to follow
3. Any recommended libraries, tools, or configurations
"##,
                instruction
            );
            let content = execute_claude(&rules_dir, &prompt)?;
            let (name, content) = parse_name_from_output(&content)?;
            (name, content)
        }
    };

    let rule_path = rules_dir.join(format!("{}.md", final_name));
    fs::write(&rule_path, &generated_content)?;

    Rule::load(&rule_path)
}

/// Parse NAME: line from AI output and return (name, remaining_content)
fn parse_name_from_output(output: &str) -> Result<(String, String)> {
    let mut lines = output.lines();

    // Find NAME: line
    for line in lines.by_ref() {
        let trimmed = line.trim();
        if let Some(name) = trimmed.strip_prefix("NAME:") {
            let name = name.trim().to_lowercase().replace(' ', "-");
            // Validate name
            if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-') {
                return Err(DotAgentError::RuleNotFound {
                    name: "AI generated invalid rule name".to_string(),
                });
            }
            // Collect remaining content
            let remaining: String = lines.collect::<Vec<_>>().join("\n");
            let content = remaining.trim_start().to_string();
            return Ok((name, content));
        }
    }

    Err(DotAgentError::RuleNotFound {
        name: "AI did not generate NAME: line".to_string(),
    })
}

// ============================================================================
// Helpers
// ============================================================================

fn check_claude_cli() -> bool {
    Command::new("claude")
        .arg("--version")
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .map(|s| s.success())
        .unwrap_or(false)
}

fn execute_claude(working_dir: &Path, prompt: &str) -> Result<String> {
    let mut cmd = Command::new("claude");
    cmd.arg("--print");
    cmd.arg("--dangerously-skip-permissions");
    cmd.current_dir(working_dir);
    cmd.stdin(Stdio::piped());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    let mut child = cmd
        .spawn()
        .map_err(|e| DotAgentError::ClaudeExecutionFailed {
            message: format!("Failed to spawn claude: {}", e),
        })?;

    if let Some(mut stdin) = child.stdin.take() {
        stdin
            .write_all(prompt.as_bytes())
            .map_err(|e| DotAgentError::ClaudeExecutionFailed {
                message: format!("Failed to write prompt: {}", e),
            })?;
    }

    let output = child
        .wait_with_output()
        .map_err(|e| DotAgentError::ClaudeExecutionFailed {
            message: format!("Execution failed: {}", e),
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(DotAgentError::ClaudeExecutionFailed {
            message: format!("Claude exited with error: {}", stderr),
        });
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

fn apply_ai_output(profile_path: &Path, output: &str) -> Result<usize> {
    let mut files_modified = 0;

    let mut lines = output.lines().peekable();
    while let Some(line) = lines.next() {
        if line.starts_with("ACTION:") {
            let action = line.trim_start_matches("ACTION:").trim();

            let file_line = lines.next().unwrap_or("");
            if !file_line.starts_with("FILE:") {
                continue;
            }
            let file_path = file_line.trim_start_matches("FILE:").trim();

            let content_line = lines.next().unwrap_or("");
            if !content_line.starts_with("CONTENT:") {
                continue;
            }

            let mut content = String::new();
            while let Some(line) = lines.peek() {
                if line.starts_with("ACTION:") {
                    break;
                }
                content.push_str(lines.next().unwrap_or(""));
                content.push('\n');
            }

            let target_path = profile_path.join(file_path);

            match action {
                "CREATE" | "MODIFY" => {
                    if let Some(parent) = target_path.parent() {
                        fs::create_dir_all(parent)?;
                    }
                    fs::write(&target_path, content.trim())?;
                    files_modified += 1;
                }
                "DELETE" => {
                    if target_path.exists() {
                        fs::remove_file(&target_path)?;
                        files_modified += 1;
                    }
                }
                _ => {}
            }
        }
    }

    Ok(files_modified)
}

fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() || name.len() > 64 {
        return Err(DotAgentError::InvalidRuleName {
            name: name.to_string(),
        });
    }

    let first = name.chars().next().unwrap();
    if !first.is_ascii_alphabetic() {
        return Err(DotAgentError::InvalidRuleName {
            name: name.to_string(),
        });
    }

    for c in name.chars() {
        if !c.is_ascii_alphanumeric() && c != '-' && c != '_' {
            return Err(DotAgentError::InvalidRuleName {
                name: name.to_string(),
            });
        }
    }

    Ok(())
}

fn generate_rule_template(name: &str) -> String {
    format!(
        r#"# {} Customization Rule

## Language
(e.g., Rust, Kotlin, TypeScript)

## Recommended Libraries
- library1
- library2

## Coding Style
- Style guideline 1
- Style guideline 2

## Replace Sections
(Describe what sections to replace and with what content)

## Additional Rules
(Any other customization instructions)
"#,
        name
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_validate_name_valid() {
        assert!(validate_name("rust").is_ok());
        assert!(validate_name("my-rule").is_ok());
        assert!(validate_name("python_3").is_ok());
    }

    #[test]
    fn test_validate_name_invalid() {
        assert!(validate_name("").is_err());
        assert!(validate_name("123start").is_err());
        assert!(validate_name("has space").is_err());
        assert!(validate_name("has.dot").is_err());
    }

    #[test]
    fn test_create_rule() {
        let temp = TempDir::new().unwrap();
        let manager = RuleManager::new(temp.path().to_path_buf());

        let rule = manager.create("test").unwrap();
        assert_eq!(rule.name, "test");
        assert!(rule.path.exists());
        assert!(rule.content.contains("# test Customization Rule"));
    }

    #[test]
    fn test_list_rules() {
        let temp = TempDir::new().unwrap();
        let manager = RuleManager::new(temp.path().to_path_buf());

        manager.create("alpha").unwrap();
        manager.create("beta").unwrap();

        let list = manager.list().unwrap();
        assert_eq!(list.len(), 2);
        assert_eq!(list[0].name, "alpha");
        assert_eq!(list[1].name, "beta");
    }

    #[test]
    fn test_remove_rule() {
        let temp = TempDir::new().unwrap();
        let manager = RuleManager::new(temp.path().to_path_buf());

        manager.create("test").unwrap();
        assert!(manager.get("test").is_ok());

        manager.remove("test").unwrap();
        assert!(manager.get("test").is_err());
    }

    #[test]
    fn test_rule_already_exists() {
        let temp = TempDir::new().unwrap();
        let manager = RuleManager::new(temp.path().to_path_buf());

        manager.create("test").unwrap();
        let result = manager.create("test");
        assert!(matches!(
            result,
            Err(DotAgentError::RuleAlreadyExists { .. })
        ));
    }
}