dot-agent-core 0.4.1

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
use std::fs;
use std::path::{Path, PathBuf};

use walkdir::WalkDir;

use crate::error::{DotAgentError, Result};
use crate::profile_metadata::{ProfileIndexEntry, ProfileMetadata, ProfileSource, ProfilesIndex};

const PROFILES_DIR: &str = "profiles";
const IGNORED_FILES: &[&str] = &[".DS_Store", ".gitignore", ".gitkeep"];
const IGNORED_EXTENSIONS: &[&str] = &[];

/// Default directories to exclude from profile operations
pub const DEFAULT_EXCLUDED_DIRS: &[&str] = &[
    ".git",
    // Test directories
    "tests",
    "test",
    "__tests__",
    // Build/cache directories
    "__pycache__",
    ".pytest_cache",
    "node_modules",
    "target",
    // IDE/editor directories
    ".vscode",
    ".idea",
    // CI/CD directories
    ".github",
    ".gitlab",
];

/// Configuration for file ignore/include behavior
#[derive(Debug, Clone, Default)]
pub struct IgnoreConfig {
    /// Directories to exclude (checked against path components)
    pub excluded_dirs: Vec<String>,
    /// Directories to explicitly include (overrides default exclusions)
    pub included_dirs: Vec<String>,
}

impl IgnoreConfig {
    /// Create with default exclusions (.git)
    pub fn with_defaults() -> Self {
        Self {
            excluded_dirs: DEFAULT_EXCLUDED_DIRS
                .iter()
                .map(|s| s.to_string())
                .collect(),
            included_dirs: Vec::new(),
        }
    }

    /// Add a directory to exclude
    pub fn exclude(mut self, dir: impl Into<String>) -> Self {
        self.excluded_dirs.push(dir.into());
        self
    }

    /// Add a directory to include (overrides default exclusion)
    pub fn include(mut self, dir: impl Into<String>) -> Self {
        self.included_dirs.push(dir.into());
        self
    }

    /// Check if a path should be ignored based on this config
    pub fn should_ignore(&self, path: &Path) -> bool {
        // Check static file ignores first
        if should_ignore_file(path) {
            return true;
        }

        // Check path components against excluded directories
        for component in path.components() {
            if let std::path::Component::Normal(name) = component {
                let name_str = name.to_string_lossy();

                // Check if explicitly included (overrides exclusion)
                if self.included_dirs.iter().any(|d| d == name_str.as_ref()) {
                    continue;
                }

                // Check if excluded
                if self.excluded_dirs.iter().any(|d| d == name_str.as_ref()) {
                    return true;
                }
            }
        }

        false
    }
}

/// Check if a file should be ignored (static rules, not directory-based)
fn should_ignore_file(path: &Path) -> bool {
    if let Some(name) = path.file_name() {
        let name = name.to_string_lossy();
        if IGNORED_FILES.contains(&name.as_ref()) {
            return true;
        }
    }

    if let Some(ext) = path.extension() {
        let ext = ext.to_string_lossy();
        if IGNORED_EXTENSIONS.contains(&ext.as_ref()) {
            return true;
        }
    }

    false
}

pub struct Profile {
    pub name: String,
    pub path: PathBuf,
}

impl Profile {
    pub fn new(name: String, path: PathBuf) -> Self {
        Self { name, path }
    }

    /// List all files in the profile directory (relative paths) with default ignore config
    pub fn list_files(&self) -> Result<Vec<PathBuf>> {
        self.list_files_with_config(&IgnoreConfig::with_defaults())
    }

    /// List all files in the profile directory (relative paths) with custom ignore config
    pub fn list_files_with_config(&self, config: &IgnoreConfig) -> Result<Vec<PathBuf>> {
        let mut files = Vec::new();

        for entry in WalkDir::new(&self.path).into_iter().filter_map(|e| e.ok()) {
            let path = entry.path();
            if path.is_file() {
                if let Ok(relative) = path.strip_prefix(&self.path) {
                    if !config.should_ignore(relative) {
                        files.push(relative.to_path_buf());
                    }
                }
            }
        }

        files.sort();
        Ok(files)
    }

    /// Get contents summary (e.g., "skills (5), commands (3)")
    pub fn contents_summary(&self) -> String {
        self.contents_summary_with_config(&IgnoreConfig::with_defaults())
    }

    /// Get contents summary with custom ignore config
    pub fn contents_summary_with_config(&self, config: &IgnoreConfig) -> String {
        let mut summary = Vec::new();

        if let Ok(entries) = fs::read_dir(&self.path) {
            for entry in entries.filter_map(|e| e.ok()) {
                let path = entry.path();
                if path.is_dir() {
                    let name = path.file_name().unwrap().to_string_lossy().to_string();
                    let count = WalkDir::new(&path)
                        .into_iter()
                        .filter_map(|e| e.ok())
                        .filter(|e| {
                            if !e.path().is_file() {
                                return false;
                            }
                            if let Ok(relative) = e.path().strip_prefix(&self.path) {
                                !config.should_ignore(relative)
                            } else {
                                false
                            }
                        })
                        .count();
                    if count > 0 {
                        summary.push(format!("{} ({})", name, count));
                    }
                } else if path.is_file() {
                    let name = path.file_name().unwrap().to_string_lossy().to_string();
                    if let Ok(relative) = path.strip_prefix(&self.path) {
                        if !config.should_ignore(relative) {
                            summary.push(name);
                        }
                    }
                }
            }
        }

        if summary.is_empty() {
            "(empty)".to_string()
        } else {
            summary.join(", ")
        }
    }
}

pub struct ProfileManager {
    base_dir: PathBuf,
}

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

    pub fn profiles_dir(&self) -> PathBuf {
        self.base_dir.join(PROFILES_DIR)
    }

    /// Discover all profiles
    pub fn list_profiles(&self) -> Result<Vec<Profile>> {
        let profiles_dir = self.profiles_dir();
        if !profiles_dir.exists() {
            return Ok(Vec::new());
        }

        let mut profiles = Vec::new();
        for entry in fs::read_dir(&profiles_dir)? {
            let entry = entry?;
            let path = entry.path();
            if path.is_dir() {
                let name = path.file_name().unwrap().to_string_lossy().to_string();
                profiles.push(Profile::new(name, path));
            }
        }

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

    /// Get a specific profile
    pub fn get_profile(&self, name: &str) -> Result<Profile> {
        let path = self.profiles_dir().join(name);
        if !path.exists() {
            return Err(DotAgentError::ProfileNotFound {
                name: name.to_string(),
            });
        }
        Ok(Profile::new(name.to_string(), path))
    }

    /// Create a new profile with scaffolding
    pub fn create_profile(&self, name: &str) -> Result<Profile> {
        validate_profile_name(name)?;

        let path = self.profiles_dir().join(name);
        if path.exists() {
            return Err(DotAgentError::ProfileAlreadyExists {
                name: name.to_string(),
            });
        }

        // Create directory structure
        fs::create_dir_all(&path)?;
        fs::create_dir_all(path.join("agents"))?;
        fs::create_dir_all(path.join("commands"))?;
        fs::create_dir_all(path.join("hooks"))?;
        fs::create_dir_all(path.join("plugins"))?;
        fs::create_dir_all(path.join("rules"))?;
        fs::create_dir_all(path.join("skills"))?;

        // Create CLAUDE.md template
        let claude_md = format!(
            r#"# {} Profile

## Overview

<!-- Describe what this profile is for -->

## Usage

```bash
dot-agent install {}
```

## Customization

<!-- Add project-specific instructions here -->
"#,
            name, name
        );
        fs::write(path.join("CLAUDE.md"), claude_md)?;

        // Create profile metadata
        let metadata = ProfileMetadata::new_local(name);
        metadata.save(&path)?;

        // Update profiles index
        let mut index = ProfilesIndex::load(&self.base_dir)?;
        index.upsert(name, ProfileIndexEntry::new_local(name));
        index.save(&self.base_dir)?;

        Ok(Profile::new(name.to_string(), path))
    }

    /// Remove a profile
    pub fn remove_profile(&self, name: &str) -> Result<()> {
        let profile = self.get_profile(name)?;
        fs::remove_dir_all(&profile.path)?;

        // Update profiles index
        let mut index = ProfilesIndex::load(&self.base_dir)?;
        index.remove(name);
        index.save(&self.base_dir)?;

        Ok(())
    }

    /// Copy an existing profile to a new name
    pub fn copy_profile(&self, source_name: &str, dest_name: &str, force: bool) -> Result<Profile> {
        let source = self.get_profile(source_name)?;
        validate_profile_name(dest_name)?;

        let dest_path = self.profiles_dir().join(dest_name);

        if dest_path.exists() {
            if !force {
                return Err(DotAgentError::ProfileAlreadyExists {
                    name: dest_name.to_string(),
                });
            }
            fs::remove_dir_all(&dest_path)?;
        }

        copy_dir_recursive(&source.path, &dest_path)?;

        // Update metadata with new name
        if let Some(mut metadata) = ProfileMetadata::load(&dest_path)? {
            metadata.profile.name = dest_name.to_string();
            metadata.save(&dest_path)?;
        } else {
            let metadata = ProfileMetadata::new_local(dest_name);
            metadata.save(&dest_path)?;
        }

        // Update profiles index
        let mut index = ProfilesIndex::load(&self.base_dir)?;
        index.upsert(dest_name, ProfileIndexEntry::new_local(dest_name));
        index.save(&self.base_dir)?;

        Ok(Profile::new(dest_name.to_string(), dest_path))
    }

    /// Import a directory as a profile (local source)
    pub fn import_profile(&self, source: &Path, name: &str, force: bool) -> Result<Profile> {
        self.import_profile_with_source(source, name, force, ProfileSource::Local)
    }

    /// Import a directory as a profile from git
    #[allow(clippy::too_many_arguments)]
    pub fn import_profile_from_git(
        &self,
        source: &Path,
        name: &str,
        force: bool,
        url: &str,
        branch: Option<&str>,
        commit: Option<&str>,
        subpath: Option<&str>,
    ) -> Result<Profile> {
        let source_info = ProfileSource::Git {
            url: url.to_string(),
            branch: branch.map(|s| s.to_string()),
            commit: commit.map(|s| s.to_string()),
            path: subpath.map(|s| s.to_string()),
        };
        self.import_profile_with_source(source, name, force, source_info)
    }

    /// Import a directory as a profile from marketplace
    pub fn import_profile_from_marketplace(
        &self,
        source: &Path,
        name: &str,
        force: bool,
        channel: &str,
        plugin: &str,
        version: &str,
    ) -> Result<Profile> {
        let source_info = ProfileSource::Marketplace {
            channel: channel.to_string(),
            plugin: plugin.to_string(),
            version: version.to_string(),
        };
        self.import_profile_with_source(source, name, force, source_info)
    }

    /// Import a directory as a profile with source information
    fn import_profile_with_source(
        &self,
        source: &Path,
        name: &str,
        force: bool,
        source_info: ProfileSource,
    ) -> Result<Profile> {
        validate_profile_name(name)?;

        if !source.exists() {
            return Err(DotAgentError::TargetNotFound {
                path: source.to_path_buf(),
            });
        }

        let dest = self.profiles_dir().join(name);

        if dest.exists() {
            if !force {
                return Err(DotAgentError::ProfileAlreadyExists {
                    name: name.to_string(),
                });
            }
            fs::remove_dir_all(&dest)?;
        }

        // Ensure profiles directory exists
        fs::create_dir_all(self.profiles_dir())?;

        // Copy directory recursively
        copy_dir_recursive(source, &dest)?;

        // Create or update profile metadata
        let metadata = match &source_info {
            ProfileSource::Local => ProfileMetadata::new_local(name),
            ProfileSource::Git {
                url,
                branch,
                commit,
                path,
            } => ProfileMetadata::new_git(
                name,
                url,
                branch.as_deref(),
                commit.as_deref(),
                path.as_deref(),
            ),
            ProfileSource::Marketplace {
                channel,
                plugin,
                version,
            } => ProfileMetadata::new_marketplace(name, channel, plugin, version),
        };
        metadata.save(&dest)?;

        // Update profiles index
        let mut index = ProfilesIndex::load(&self.base_dir)?;
        let entry = match &source_info {
            ProfileSource::Local => ProfileIndexEntry::new_local(name),
            ProfileSource::Git {
                url,
                branch,
                commit,
                path,
            } => ProfileIndexEntry::new_git(
                name,
                url,
                branch.as_deref(),
                commit.as_deref(),
                path.as_deref(),
            ),
            ProfileSource::Marketplace {
                channel,
                plugin,
                version,
            } => ProfileIndexEntry::new_marketplace(name, channel, plugin, version),
        };
        index.upsert(name, entry);
        index.save(&self.base_dir)?;

        Ok(Profile::new(name.to_string(), dest))
    }

    /// Get metadata for a profile
    pub fn get_profile_metadata(&self, name: &str) -> Result<Option<ProfileMetadata>> {
        let profile = self.get_profile(name)?;
        ProfileMetadata::load(&profile.path)
    }

    /// Get profile source from index
    pub fn get_profile_source(&self, name: &str) -> Result<Option<ProfileSource>> {
        let index = ProfilesIndex::load(&self.base_dir)?;
        Ok(index.get(name).map(|e| e.source.clone()))
    }
}

fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    copy_dir_recursive_with_config(src, dst, &IgnoreConfig::with_defaults())
}

fn copy_dir_recursive_with_config(src: &Path, dst: &Path, config: &IgnoreConfig) -> Result<()> {
    fs::create_dir_all(dst)?;

    for entry in WalkDir::new(src).into_iter().filter_map(|e| e.ok()) {
        let src_path = entry.path();
        let relative = src_path.strip_prefix(src).unwrap();
        let dst_path = dst.join(relative);

        // Skip ignored directories/files
        if config.should_ignore(relative) {
            continue;
        }

        if src_path.is_dir() {
            fs::create_dir_all(&dst_path)?;
        } else if src_path.is_file() {
            if let Some(parent) = dst_path.parent() {
                fs::create_dir_all(parent)?;
            }
            fs::copy(src_path, &dst_path)?;
        }
    }

    Ok(())
}

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

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

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

    Ok(())
}

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

    #[test]
    fn ignore_config_default_excludes_git() {
        let config = IgnoreConfig::with_defaults();
        assert!(config.excluded_dirs.contains(&".git".to_string()));
    }

    #[test]
    fn ignore_config_default_excludes_tests() {
        let config = IgnoreConfig::with_defaults();
        assert!(config.excluded_dirs.contains(&"tests".to_string()));
        assert!(config.excluded_dirs.contains(&"test".to_string()));
        assert!(config.excluded_dirs.contains(&"__tests__".to_string()));
    }

    #[test]
    fn ignore_config_default_excludes_build_dirs() {
        let config = IgnoreConfig::with_defaults();
        assert!(config.excluded_dirs.contains(&"__pycache__".to_string()));
        assert!(config.excluded_dirs.contains(&".pytest_cache".to_string()));
        assert!(config.excluded_dirs.contains(&"node_modules".to_string()));
        assert!(config.excluded_dirs.contains(&"target".to_string()));
    }

    #[test]
    fn ignore_config_should_ignore_tests_dir() {
        let config = IgnoreConfig::with_defaults();

        assert!(config.should_ignore(Path::new("tests")));
        assert!(config.should_ignore(Path::new("tests/unit/test_parser.py")));
        assert!(config.should_ignore(Path::new("tests/claude-code/analyze-token-usage.py")));
    }

    #[test]
    fn ignore_config_should_ignore_git_files() {
        let config = IgnoreConfig::with_defaults();

        // .git directory itself
        assert!(config.should_ignore(Path::new(".git")));

        // Files inside .git
        assert!(config.should_ignore(Path::new(".git/HEAD")));
        assert!(config.should_ignore(Path::new(".git/config")));
        assert!(config.should_ignore(Path::new(".git/objects/pack/something.pack")));
    }

    #[test]
    fn ignore_config_should_not_ignore_regular_files() {
        let config = IgnoreConfig::with_defaults();

        assert!(!config.should_ignore(Path::new("README.md")));
        assert!(!config.should_ignore(Path::new("src/main.rs")));
        assert!(!config.should_ignore(Path::new("skills/my-skill/SKILL.md")));
    }

    #[test]
    fn ignore_config_include_overrides_exclude() {
        let config = IgnoreConfig::with_defaults().include(".git");

        // .git should no longer be ignored because it's included
        assert!(!config.should_ignore(Path::new(".git")));
        assert!(!config.should_ignore(Path::new(".git/HEAD")));
    }

    #[test]
    fn ignore_config_additional_exclusions() {
        let config = IgnoreConfig::with_defaults().exclude("node_modules");

        // Both .git and node_modules should be ignored
        assert!(config.should_ignore(Path::new(".git/HEAD")));
        assert!(config.should_ignore(Path::new("node_modules/package/index.js")));
    }

    #[test]
    fn ignore_config_static_file_ignores() {
        let config = IgnoreConfig::with_defaults();

        // Static file ignores should still work
        assert!(config.should_ignore(Path::new(".DS_Store")));
        assert!(config.should_ignore(Path::new(".gitignore")));
        assert!(config.should_ignore(Path::new(".gitkeep")));
        assert!(config.should_ignore(Path::new("some/path/.DS_Store")));
    }

    #[test]
    fn ignore_config_empty_allows_all() {
        let config = IgnoreConfig::default();

        // With no exclusions, nothing directory-related is ignored
        // (but static file ignores still apply)
        assert!(!config.should_ignore(Path::new(".git/HEAD")));
        assert!(!config.should_ignore(Path::new("node_modules/index.js")));

        // Static ignores still work
        assert!(config.should_ignore(Path::new(".DS_Store")));
    }
}