pmat 3.15.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
#![cfg_attr(coverage_nightly, coverage(off))]
use crate::cli::DagType;
use crate::models::churn::{ChurnSummary, CodeChurnAnalysis};
use crate::models::dag::DependencyGraph;
use crate::models::template::{
    ParameterSpec, ParameterType, TemplateCategory, TemplateResource, Toolchain,
};
use crate::services::cache::{
    strategies::TemplateCacheStrategy, CacheConfig, ContentCache, SessionCacheManager,
};
use crate::services::context::{AstItem, FileContext};
use chrono::Utc;
use rustc_hash::FxHashMap;
use semver::Version;
use std::collections::HashMap;
use std::path::PathBuf;

#[tokio::test]
async fn test_session_cache_manager() {
    let config = CacheConfig::default();
    let manager = SessionCacheManager::new(config);

    // Test manager's diagnostics - check memory usage instead
    let diagnostics = manager.get_diagnostics();
    assert!(diagnostics.memory_usage_mb >= 0.0);
}

#[tokio::test]
async fn test_ast_cache() {
    // Create a custom test strategy that doesn't check file existence
    #[derive(Clone)]
    struct TestAstCacheStrategy;

    impl crate::services::cache::base::CacheStrategy for TestAstCacheStrategy {
        type Key = PathBuf;
        type Value = FileContext;

        fn cache_key(&self, path: &PathBuf) -> String {
            format!("test_ast:{}", path.display())
        }

        fn validate(&self, _path: &PathBuf, _cached: &FileContext) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(300))
        }

        fn max_size(&self) -> usize {
            100
        }
    }

    let strategy = TestAstCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Create a test FileContext
    let file_context = FileContext {
        path: "/test/file.rs".to_string(),
        language: "rust".to_string(),
        items: vec![AstItem::Function {
            name: "main".to_string(),
            visibility: "pub".to_string(),
            is_async: false,
            line: 1,
        }],
        complexity_metrics: None,
    };

    let key = PathBuf::from("/test/file.rs");

    // Cache miss initially
    assert!(cache.get(&key).is_none());

    // Put value in cache (ContentCache wraps in Arc internally)
    cache.put(key.clone(), file_context.clone());

    // Cache hit
    let cached = cache.get(&key);
    assert!(cached.is_some());
    assert_eq!(cached.unwrap().path, file_context.path);
}

#[tokio::test]
async fn test_template_cache() {
    let strategy = TemplateCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Create a test TemplateResource
    let template = TemplateResource {
        uri: "template://makefile/rust/cli".to_string(),
        name: "Rust CLI Makefile".to_string(),
        description: "Makefile for Rust CLI projects".to_string(),
        toolchain: Toolchain::RustCli {
            cargo_features: vec![],
        },
        category: TemplateCategory::Makefile,
        parameters: vec![ParameterSpec {
            name: "project_name".to_string(),
            param_type: ParameterType::ProjectName,
            required: true,
            default_value: None,
            validation_pattern: None,
            description: "Name of the project".to_string(),
        }],
        s3_object_key: "templates/makefile/rust/cli.hbs".to_string(),
        content_hash: "abc123".to_string(),
        semantic_version: Version::new(1, 0, 0),
        dependency_graph: vec![],
    };

    let key = "template://makefile/rust/cli".to_string();

    // Cache and retrieve
    cache.put(key.clone(), template.clone());
    let cached = cache.get(&key);

    assert!(cached.is_some());
    assert_eq!(cached.unwrap().uri, template.uri);
}

#[tokio::test]
async fn test_dag_cache() {
    // Create a custom test strategy that doesn't check path existence
    #[derive(Clone)]
    struct TestDagCacheStrategy;

    impl crate::services::cache::base::CacheStrategy for TestDagCacheStrategy {
        type Key = (PathBuf, DagType);
        type Value = DependencyGraph;

        fn cache_key(&self, (path, dag_type): &(PathBuf, DagType)) -> String {
            format!("test_dag:{}:{:?}", path.display(), dag_type)
        }

        fn validate(&self, _key: &(PathBuf, DagType), _cached: &DependencyGraph) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(180))
        }

        fn max_size(&self) -> usize {
            20
        }
    }

    let strategy = TestDagCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Create a test DependencyGraph
    let graph = DependencyGraph {
        nodes: FxHashMap::default(),
        edges: vec![],
    };

    let key = (PathBuf::from("/test/project"), DagType::CallGraph);

    // Cache and retrieve
    cache.put(key.clone(), graph.clone());
    let cached = cache.get(&key);

    assert!(cached.is_some());
}

#[tokio::test]
async fn test_churn_cache() {
    // Create a custom test strategy that doesn't check repo existence
    #[derive(Clone)]
    struct TestChurnCacheStrategy;

    impl crate::services::cache::base::CacheStrategy for TestChurnCacheStrategy {
        type Key = (PathBuf, u32);
        type Value = CodeChurnAnalysis;

        fn cache_key(&self, (repo, period_days): &(PathBuf, u32)) -> String {
            format!("test_churn:{}:{}", repo.display(), period_days)
        }

        fn validate(&self, _key: &(PathBuf, u32), _cached: &CodeChurnAnalysis) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(1800))
        }

        fn max_size(&self) -> usize {
            20
        }
    }

    let strategy = TestChurnCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Create test CodeChurnAnalysis
    let churn = CodeChurnAnalysis {
        generated_at: Utc::now(),
        period_days: 30,
        repository_root: PathBuf::from("/test/repo"),
        files: vec![],
        summary: ChurnSummary {
            total_commits: 100,
            total_files_changed: 10,
            hotspot_files: vec![],
            stable_files: vec![],
            author_contributions: HashMap::new(),
            mean_churn_score: 0.0,
            variance_churn_score: 0.0,
            stddev_churn_score: 0.0,
        },
    };

    let key = (PathBuf::from("/test/repo"), 30u32);

    // Cache and retrieve
    cache.put(key.clone(), churn.clone());
    let cached = cache.get(&key);

    assert!(cached.is_some());
    assert_eq!(cached.unwrap().period_days, churn.period_days);
}

#[tokio::test]
async fn test_git_stats_cache() {
    use crate::services::cache::strategies::GitStats;

    // Create a custom test strategy that doesn't check git repo
    #[derive(Clone)]
    struct TestGitStatsCacheStrategy;

    impl crate::services::cache::base::CacheStrategy for TestGitStatsCacheStrategy {
        type Key = PathBuf;
        type Value = GitStats;

        fn cache_key(&self, repo: &PathBuf) -> String {
            format!("test_git_stats:{}", repo.display())
        }

        fn validate(&self, _repo: &PathBuf, _cached: &GitStats) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(900))
        }

        fn max_size(&self) -> usize {
            10
        }
    }

    let strategy = TestGitStatsCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Create test GitStats
    let stats = GitStats {
        total_commits: 100,
        authors: vec!["Alice".to_string(), "Bob".to_string()],
        branch: "main".to_string(),
        head_commit: "abc123".to_string(),
    };

    let key = PathBuf::from("/test/repo");

    // Cache and retrieve
    cache.put(key.clone(), stats.clone());
    let cached = cache.get(&key);

    assert!(cached.is_some());
    assert_eq!(cached.unwrap().total_commits, stats.total_commits);
}

#[tokio::test]
async fn test_cache_eviction() {
    // Create a custom test strategy with max size 2
    #[derive(Clone)]
    struct SmallCacheStrategy;

    impl crate::services::cache::base::CacheStrategy for SmallCacheStrategy {
        type Key = PathBuf;
        type Value = FileContext;

        fn cache_key(&self, path: &PathBuf) -> String {
            format!("test_small:{}", path.display())
        }

        fn validate(&self, _path: &PathBuf, _cached: &FileContext) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(300))
        }

        fn max_size(&self) -> usize {
            2 // Small cache for eviction testing
        }
    }

    let strategy = SmallCacheStrategy;
    let cache = ContentCache::new(strategy);

    // Test eviction with small cache
    let file1 = FileContext {
        path: "/test/file1.rs".to_string(),
        language: "rust".to_string(),
        items: vec![],
        complexity_metrics: None,
    };

    let file2 = FileContext {
        path: "/test/file2.rs".to_string(),
        language: "rust".to_string(),
        items: vec![],
        complexity_metrics: None,
    };

    let file3 = FileContext {
        path: "/test/file3.rs".to_string(),
        language: "rust".to_string(),
        items: vec![],
        complexity_metrics: None,
    };

    // Add first two files
    cache.put(PathBuf::from("/test/file1.rs"), file1);
    cache.put(PathBuf::from("/test/file2.rs"), file2);

    // Both should be cached
    assert!(cache.get(&PathBuf::from("/test/file1.rs")).is_some());
    assert!(cache.get(&PathBuf::from("/test/file2.rs")).is_some());

    // Add third file - should evict the least recently used (file1)
    cache.put(PathBuf::from("/test/file3.rs"), file3);

    // File1 should be evicted, file2 and file3 should remain
    assert!(cache.get(&PathBuf::from("/test/file1.rs")).is_none());
    assert!(cache.get(&PathBuf::from("/test/file2.rs")).is_some());
    assert!(cache.get(&PathBuf::from("/test/file3.rs")).is_some());
}

#[tokio::test]
async fn test_cache_clear() {
    // Create a custom test strategy that doesn't check file existence
    #[derive(Clone)]
    struct TestClearStrategy;

    impl crate::services::cache::base::CacheStrategy for TestClearStrategy {
        type Key = PathBuf;
        type Value = FileContext;

        fn cache_key(&self, path: &PathBuf) -> String {
            format!("test_clear:{}", path.display())
        }

        fn validate(&self, _path: &PathBuf, _cached: &FileContext) -> bool {
            // Always valid for tests
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_secs(300))
        }

        fn max_size(&self) -> usize {
            100
        }
    }

    let strategy = TestClearStrategy;
    let cache = ContentCache::new(strategy);

    // Add some items
    for i in 0..5 {
        let file = FileContext {
            path: format!("/test/file{i}.rs"),
            language: "rust".to_string(),
            items: vec![],
            complexity_metrics: None,
        };
        cache.put(PathBuf::from(format!("/test/file{i}.rs")), file);
    }

    // Verify items are cached
    assert!(cache.get(&PathBuf::from("/test/file0.rs")).is_some());
    assert!(cache.get(&PathBuf::from("/test/file4.rs")).is_some());

    // Clear cache
    cache.clear();

    // All items should be gone
    for i in 0..5 {
        assert!(cache
            .get(&PathBuf::from(format!("/test/file{i}.rs")))
            .is_none());
    }
}

#[tokio::test]
async fn test_cache_ttl() {
    // Create a custom strategy with very short TTL
    #[derive(Clone)]
    struct ShortTtlStrategy;

    impl crate::services::cache::base::CacheStrategy for ShortTtlStrategy {
        type Key = String;
        type Value = String;

        fn cache_key(&self, key: &String) -> String {
            key.clone()
        }

        fn validate(&self, _key: &String, _cached: &String) -> bool {
            true
        }

        fn ttl(&self) -> Option<std::time::Duration> {
            Some(std::time::Duration::from_millis(100))
        }

        fn max_size(&self) -> usize {
            10
        }
    }

    let strategy = ShortTtlStrategy;
    let cache = ContentCache::new(strategy);

    // Add item
    cache.put("test_key".to_string(), "test_value".to_string());

    // Should be cached immediately
    assert!(cache.get(&"test_key".to_string()).is_some());

    // Wait for TTL to expire
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;

    // Should be expired
    assert!(cache.get(&"test_key".to_string()).is_none());
}