codetree 0.2.0

AI-native version control system for autonomous agents
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
//! CodeTree - An AI-native version control system for autonomous agents.
//!
//! CodeTree is a standalone VCS: it owns its object store, refs, commits, and
//! trees in `.codetree/` and does not depend on Git. History is exposed through
//! an operation-centric model so AI agents reason in tasks, not branches.
//!
//! The native VCS engine lives in `src/vcs/` and provides content-addressable
//! object storage, refs, index, and a full `VcsManager` API.
//!
//! ## Features
//!
//! - **cli** (default): Command-line interface support
//! - **mcp** (default): Model Context Protocol server for AI assistant integration
//!
//! ## Library Usage
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! codetree = "0.1"
//! ```
//!
//! ### Example
//!
//! ```rust,no_run
//! use codetree::{Config, BranchManager, VcsManager};
//! use codetree::error::Result;
//!
//! #[tokio::main]
//! async fn main() -> Result<()> {
//!     // Load configuration
//!     let config = Config::load(std::path::Path::new("codetree.toml")).await?;
//!
//!     // Create VCS manager
//!     let vcs = VcsManager::new(std::env::current_dir()?)?;
//!
//!     // Create branch manager
//!     let mut branch_manager = BranchManager::new(
//!         std::path::PathBuf::from(".codetree/branches.json")
//!     ).await?;
//!
//!     // Register a new branch for a mini-operation
//!     branch_manager.register_branch(
//!         "feature-example",
//!         vec!["src/main.rs".to_string()],
//!         "Example feature".to_string()
//!     ).await?;
//!
//!     Ok(())
//! }
//! ```

macro_rules! debug {
    ($($arg:tt)*) => {
        if cfg!(debug_assertions) {
            eprintln!("[DEBUG] {}", format!($($arg)*));
        }
    };
}

macro_rules! info {
    ($($arg:tt)*) => {
        eprintln!("[INFO]  {}", format!($($arg)*));
    };
}

macro_rules! warn {
    ($($arg:tt)*) => {
        eprintln!("[WARN]  {}", format!($($arg)*));
    };
}

macro_rules! bail {
    ($($arg:tt)*) => {
        return Err(format!($($arg)*).into())
    };
}

pub mod atomic;
pub mod branch;
pub mod bisect;
pub mod candidates;
pub mod config;
pub mod evolog;
pub mod hidden;
pub mod freeze;
pub mod error;
pub mod lock;
pub mod megamerge;
pub mod ops;
pub mod provenance;
pub mod resolution;
pub mod snapshot;
pub mod vcs;

#[cfg(feature = "cli")]
pub mod commands;

#[cfg(feature = "mcp")]
pub mod mcp;

// Re-export commonly used types
pub use branch::{BranchInfo, BranchManager, BranchStatus, ChangeGroup};
pub use config::Config;
pub use vcs::VcsManager;

#[cfg(feature = "mcp")]
pub use mcp::CodetreeServer;

/// Version information
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const NAME: &str = env!("CARGO_PKG_NAME");
pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION");

/// Default configuration values
pub mod defaults {
    /// Default cleanup days for old branches
    pub const CLEANUP_DAYS: u32 = 30;
}

/// Common error types
pub mod errors {
    use std::fmt;

    #[derive(Debug)]
    pub enum CodetreeError {
        GitError(String),
        ConfigError(String),
        FileSystemError(String),
        BranchNotFound(String),
        InvalidOperation(String),
    }

    impl fmt::Display for CodetreeError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            match self {
                CodetreeError::GitError(msg) => write!(f, "Git operation failed: {msg}"),
                CodetreeError::ConfigError(msg) => write!(f, "Configuration error: {msg}"),
                CodetreeError::FileSystemError(msg) => write!(f, "File system error: {msg}"),
                CodetreeError::BranchNotFound(name) => write!(f, "Branch not found: {name}"),
                CodetreeError::InvalidOperation(msg) => write!(f, "Invalid operation: {msg}"),
            }
        }
    }

    impl std::error::Error for CodetreeError {}
}

/// Utility functions
pub mod utils {
    use std::path::Path;
    
    /// Check if a path should be ignored based on common patterns
    pub fn should_ignore_path(path: &Path) -> bool {
        let path_str = path.to_string_lossy();
        
        // Common ignore patterns
        let ignore_patterns = [
            ".git/",
            ".codetree/",
            "target/",
            "node_modules/",
            ".DS_Store",
            "*.tmp",
            "*.log",
            "*.swp",
            "*.swo",
            "*~",
        ];
        
        for pattern in &ignore_patterns {
            if pattern.ends_with('/') {
                // Directory pattern
                if path_str.contains(pattern) {
                    return true;
                }
            } else if pattern.contains('*') {
                // Glob pattern: *.suffix or prefix*
                if let Some(suffix) = pattern.strip_prefix('*') {
                    if path_str.ends_with(suffix) {
                        return true;
                    }
                } else if let Some(prefix) = pattern.strip_suffix('*') {
                    if path_str.starts_with(prefix) {
                        return true;
                    }
                } else {
                    let pattern_without_star = pattern.replace('*', "");
                    if path_str.contains(&pattern_without_star) {
                        return true;
                    }
                }
            } else {
                // Exact match
                if path_str.contains(pattern) {
                    return true;
                }
            }
        }
        
        false
    }
    
    /// Convert a description into a URL-friendly slug (lowercase, alnum-only, max 4 words)
    pub fn slugify(s: &str) -> String {
        s.to_lowercase()
            .replace(|c: char| !c.is_alphanumeric() && c != ' ', " ")
            .split_whitespace()
            .take(4)
            .collect::<Vec<_>>()
            .join("_")
    }
    
    /// Generate a unique branch name based on timestamp and content
    pub fn generate_branch_name(prefix: &str, timestamp: u64) -> String {
        format!("{}_{}", prefix, timestamp)
    }
    
    /// Calculate similarity between two strings using simple algorithm
    pub fn calculate_similarity(a: &str, b: &str) -> f64 {
        if a == b {
            return 1.0;
        }
        
        if a.is_empty() || b.is_empty() {
            return 0.0;
        }
        
        // Simple Jaccard similarity based on words
        let words_a: std::collections::HashSet<&str> = a.split_whitespace().collect();
        let words_b: std::collections::HashSet<&str> = b.split_whitespace().collect();
        
        let intersection = words_a.intersection(&words_b).count();
        let union = words_a.union(&words_b).count();
        
        if union == 0 {
            0.0
        } else {
            intersection as f64 / union as f64
        }
    }
    
    /// Format file size in human-readable format
    pub fn format_file_size(size: u64) -> String {
        const UNITS: &[&str] = &["B", "KB", "MB", "GB", "TB"];
        let mut size = size as f64;
        let mut unit_index = 0;
        
        while size >= 1024.0 && unit_index < UNITS.len() - 1 {
            size /= 1024.0;
            unit_index += 1;
        }
        
        if unit_index == 0 {
            format!("{} {}", size as u64, UNITS[unit_index])
        } else {
            format!("{:.1} {}", size, UNITS[unit_index])
        }
    }
    
    /// Truncate string to specified length with ellipsis
    pub fn truncate_string(s: &str, max_len: usize) -> String {
        if s.len() <= max_len {
            s.to_string()
        } else if max_len <= 3 {
            "...".to_string()
        } else {
            format!("{}...", &s[..max_len - 3])
        }
    }
    
    /// Extract file extension from path
    pub fn get_file_extension(path: &Path) -> Option<String> {
        path.extension()
            .and_then(|ext| ext.to_str())
            .map(|ext| ext.to_lowercase())
    }
    
    /// Check if file is a source code file
    pub fn is_source_file(path: &Path) -> bool {
        if let Some(ext) = get_file_extension(path) {
            matches!(ext.as_str(), 
                "rs" | "py" | "js" | "ts" | "jsx" | "tsx" | "java" | "c" | "cpp" | "h" | "hpp" |
                "go" | "rb" | "php" | "cs" | "swift" | "kt" | "scala" | "clj" | "hs" | "ml" |
                "elm" | "dart" | "r" | "jl" | "nim" | "zig" | "v" | "cr" | "ex" | "exs"
            )
        } else {
            false
        }
    }
    
    /// Check if file is a configuration file
    pub fn is_config_file(path: &Path) -> bool {
        if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
            matches!(name,
                "Cargo.toml" | "package.json" | "requirements.txt" | "Pipfile" | "pyproject.toml" |
                "pom.xml" | "build.gradle" | "Makefile" | "CMakeLists.txt" | "Dockerfile" |
                ".gitignore" | ".dockerignore" | "README.md" | "LICENSE" | "CHANGELOG.md"
            ) || name.ends_with(".toml") || name.ends_with(".yaml") || name.ends_with(".yml") ||
               name.ends_with(".json") || name.ends_with(".xml") || name.ends_with(".ini") ||
               name.starts_with(".env")
        } else {
            false
        }
    }
    
    /// Check if file is a test file
    pub fn is_test_file(path: &Path) -> bool {
        let path_str = path.to_string_lossy().to_lowercase();
        path_str.contains("test") || path_str.contains("spec") || 
        path_str.ends_with("_test.rs") || path_str.ends_with(".test.js") ||
        path_str.ends_with(".spec.js") || path_str.ends_with("_test.py") ||
        path_str.contains("/tests/") || path_str.contains("/test/")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    
    #[test]
    fn test_should_ignore_path() {
        use std::path::Path;
        
        assert!(utils::should_ignore_path(Path::new(".git/config")));
        assert!(utils::should_ignore_path(Path::new("target/debug/main")));
        assert!(utils::should_ignore_path(Path::new("node_modules/package/index.js")));
        assert!(utils::should_ignore_path(Path::new(".DS_Store")));
        assert!(utils::should_ignore_path(Path::new("file.tmp")));
        
        assert!(!utils::should_ignore_path(Path::new("src/main.rs")));
        assert!(!utils::should_ignore_path(Path::new("README.md")));
    }

    #[test]
    fn test_should_ignore_path_glob_false_positive() {
        use std::path::Path;

        // Regression: *.tmp should not match files that merely contain ".tmp" as substring
        assert!(!utils::should_ignore_path(Path::new("my.template")));
        assert!(!utils::should_ignore_path(Path::new("document.temporary")));
        assert!(!utils::should_ignore_path(Path::new("tmpfile")));

        // But it should still match actual .tmp files
        assert!(utils::should_ignore_path(Path::new("file.tmp")));
        assert!(utils::should_ignore_path(Path::new("dir/file.tmp")));
    }
    
    #[test]
    fn test_calculate_similarity() {
        assert_eq!(utils::calculate_similarity("hello world", "hello world"), 1.0);
        assert_eq!(utils::calculate_similarity("", ""), 1.0);
        assert_eq!(utils::calculate_similarity("hello", ""), 0.0);
        
        let sim = utils::calculate_similarity("hello world", "world hello");
        assert!(sim > 0.8); // Should be high similarity
        
        let sim = utils::calculate_similarity("hello world", "goodbye moon");
        assert!(sim < 0.5); // Should be low similarity
    }
    
    #[test]
    fn test_format_file_size() {
        assert_eq!(utils::format_file_size(0), "0 B");
        assert_eq!(utils::format_file_size(1023), "1023 B");
        assert_eq!(utils::format_file_size(1024), "1.0 KB");
        assert_eq!(utils::format_file_size(1536), "1.5 KB");
        assert_eq!(utils::format_file_size(1048576), "1.0 MB");
    }
    
    #[test]
    fn test_truncate_string() {
        assert_eq!(utils::truncate_string("hello", 10), "hello");
        assert_eq!(utils::truncate_string("hello world", 8), "hello...");
        assert_eq!(utils::truncate_string("hi", 2), "hi");
        assert_eq!(utils::truncate_string("hello", 3), "...");
    }
    
    #[test]
    fn test_is_source_file() {
        use std::path::Path;
        
        assert!(utils::is_source_file(Path::new("main.rs")));
        assert!(utils::is_source_file(Path::new("script.py")));
        assert!(utils::is_source_file(Path::new("app.js")));
        assert!(utils::is_source_file(Path::new("Component.tsx")));
        
        assert!(!utils::is_source_file(Path::new("README.md")));
        assert!(!utils::is_source_file(Path::new("data.json")));
        assert!(!utils::is_source_file(Path::new("image.png")));
    }
    
    #[test]
    fn test_is_config_file() {
        use std::path::Path;
        
        assert!(utils::is_config_file(Path::new("Cargo.toml")));
        assert!(utils::is_config_file(Path::new("package.json")));
        assert!(utils::is_config_file(Path::new("config.yaml")));
        assert!(utils::is_config_file(Path::new(".env")));
        assert!(utils::is_config_file(Path::new(".gitignore")));
        
        assert!(!utils::is_config_file(Path::new("main.rs")));
        assert!(!utils::is_config_file(Path::new("data.txt")));
    }
    
    #[test]
    fn test_is_test_file() {
        use std::path::Path;
        
        assert!(utils::is_test_file(Path::new("main_test.rs")));
        assert!(utils::is_test_file(Path::new("app.test.js")));
        assert!(utils::is_test_file(Path::new("component.spec.ts")));
        assert!(utils::is_test_file(Path::new("tests/integration.py")));
        assert!(utils::is_test_file(Path::new("test/unit.py")));
        
        assert!(!utils::is_test_file(Path::new("main.rs")));
        assert!(!utils::is_test_file(Path::new("README.md")));
    }

    #[test]
    fn test_generate_branch_name() {
        let ts = 1700000000u64;
        let branch = utils::generate_branch_name("codetree", ts);
        assert!(branch.starts_with("codetree_"));
        assert!(branch.len() > 10);

        let branch = utils::generate_branch_name("prefix", ts);
        assert!(branch.starts_with("prefix_"));
        assert!(!branch.is_empty());
    }

    #[test]
    fn test_format_file_size_edge_cases() {
        assert_eq!(utils::format_file_size(1), "1 B");
        assert_eq!(utils::format_file_size(1073741824), "1.0 GB");
    }

    #[test]
    fn test_get_file_extension() {
        use std::path::Path;
        
        assert_eq!(utils::get_file_extension(Path::new("main.rs")), Some("rs".to_string()));
        assert_eq!(utils::get_file_extension(Path::new(".gitignore")), None);
        assert_eq!(utils::get_file_extension(Path::new("data.tar.gz")), Some("gz".to_string()));
        assert_eq!(utils::get_file_extension(Path::new("noextension")), None);
        assert_eq!(utils::get_file_extension(Path::new("README.MD")), Some("md".to_string()));
    }

    #[test]
    fn test_is_source_file_edge_cases() {
        use std::path::Path;
        
        assert!(!utils::is_source_file(Path::new("Makefile"))); // No extension, not recognized as source
        assert!(!utils::is_source_file(Path::new(".env")));
        assert!(!utils::is_source_file(Path::new("Dockerfile")));
    }

    #[test]
    fn test_is_config_file_edge_cases() {
        use std::path::Path;
        
        assert!(utils::is_config_file(Path::new("tsconfig.json")));
        assert!(!utils::is_config_file(Path::new("main.rs")));
        assert!(!utils::is_config_file(Path::new("app.js")));
    }

    #[test]
    fn test_slugify_basic() {
        assert_eq!(utils::slugify("Fix login bug"), "fix_login_bug");
    }

    #[test]
    fn test_slugify_with_punctuation() {
        assert_eq!(utils::slugify("Bug: critical error!"), "bug_critical_error");
    }

    #[test]
    fn test_slugify_truncate() {
        let long = "This is a very long description with many words";
        let result = utils::slugify(long);
        let parts: Vec<&str> = result.split('_').collect();
        assert!(parts.len() <= 4);
    }

    #[test]
    fn test_slugify_empty() {
        assert_eq!(utils::slugify(""), "");
    }

    #[test]
    fn test_slugify_numbers() {
        assert_eq!(utils::slugify("Feature 123 with numbers"), "feature_123_with_numbers");
    }
}