pmat 3.11.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
449
450
451
452
453
454
#![cfg_attr(coverage_nightly, coverage(off))]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RepositoryRecommendation {
    pub repository: String,
    pub reason: String,
    pub confidence: f64,
    pub framework_detected: Option<String>,
    pub complexity_tier: ComplexityTier,
    pub learning_focus: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ComplexityTier {
    Beginner,
    Intermediate,
    Advanced,
    Expert,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FrameworkSignature {
    pub name: String,
    pub files: Vec<String>,
    pub imports: Vec<String>,
    pub dependencies: Vec<String>,
    pub confidence_threshold: f64,
}

pub struct RecommendationEngine {
    framework_signatures: HashMap<String, Vec<FrameworkSignature>>,
    curated_repositories: HashMap<String, Vec<RepositoryRecommendation>>,
}

impl RecommendationEngine {
    #[must_use]
    pub fn new() -> Self {
        let mut engine = Self {
            framework_signatures: HashMap::new(),
            curated_repositories: HashMap::new(),
        };
        engine.initialize_framework_signatures();
        engine.initialize_curated_repositories();
        engine
    }

    fn initialize_framework_signatures(&mut self) {
        let rust_frameworks = vec![
            FrameworkSignature {
                name: "Actix Web".to_string(),
                files: vec!["Cargo.toml".to_string()],
                imports: vec!["actix_web".to_string(), "actix".to_string()],
                dependencies: vec!["actix-web".to_string()],
                confidence_threshold: 0.8,
            },
            FrameworkSignature {
                name: "Tokio".to_string(),
                files: vec!["Cargo.toml".to_string()],
                imports: vec!["tokio".to_string()],
                dependencies: vec!["tokio".to_string()],
                confidence_threshold: 0.7,
            },
            FrameworkSignature {
                name: "Serde".to_string(),
                files: vec!["Cargo.toml".to_string()],
                imports: vec!["serde".to_string()],
                dependencies: vec!["serde".to_string()],
                confidence_threshold: 0.6,
            },
        ];

        let python_frameworks = vec![
            FrameworkSignature {
                name: "Django".to_string(),
                files: vec!["manage.py".to_string(), "settings.py".to_string()],
                imports: vec!["django".to_string()],
                dependencies: vec!["Django".to_string()],
                confidence_threshold: 0.9,
            },
            FrameworkSignature {
                name: "FastAPI".to_string(),
                files: vec!["requirements.txt".to_string(), "pyproject.toml".to_string()],
                imports: vec!["fastapi".to_string()],
                dependencies: vec!["fastapi".to_string()],
                confidence_threshold: 0.8,
            },
            FrameworkSignature {
                name: "Flask".to_string(),
                files: vec!["app.py".to_string(), "requirements.txt".to_string()],
                imports: vec!["flask".to_string()],
                dependencies: vec!["Flask".to_string()],
                confidence_threshold: 0.7,
            },
        ];

        let typescript_frameworks = vec![
            FrameworkSignature {
                name: "React".to_string(),
                files: vec!["package.json".to_string()],
                imports: vec!["react".to_string()],
                dependencies: vec!["react".to_string()],
                confidence_threshold: 0.8,
            },
            FrameworkSignature {
                name: "Next.js".to_string(),
                files: vec!["next.config.js".to_string(), "package.json".to_string()],
                imports: vec!["next".to_string()],
                dependencies: vec!["next".to_string()],
                confidence_threshold: 0.9,
            },
            FrameworkSignature {
                name: "Express".to_string(),
                files: vec!["package.json".to_string()],
                imports: vec!["express".to_string()],
                dependencies: vec!["express".to_string()],
                confidence_threshold: 0.7,
            },
        ];

        self.framework_signatures
            .insert("rust".to_string(), rust_frameworks);
        self.framework_signatures
            .insert("python".to_string(), python_frameworks);
        self.framework_signatures
            .insert("typescript".to_string(), typescript_frameworks.clone());
        self.framework_signatures
            .insert("javascript".to_string(), typescript_frameworks);
    }

    fn initialize_curated_repositories(&mut self) {
        let rust_repos = vec![
            RepositoryRecommendation {
                repository: "tokio-rs/tokio".to_string(),
                reason: "Excellent async runtime showcasing advanced Rust patterns".to_string(),
                confidence: 0.95,
                framework_detected: Some("Tokio".to_string()),
                complexity_tier: ComplexityTier::Advanced,
                learning_focus: vec![
                    "async programming".to_string(),
                    "runtime design".to_string(),
                ],
            },
            RepositoryRecommendation {
                repository: "actix/actix-web".to_string(),
                reason: "High-performance web framework with clean architecture".to_string(),
                confidence: 0.90,
                framework_detected: Some("Actix Web".to_string()),
                complexity_tier: ComplexityTier::Intermediate,
                learning_focus: vec!["web development".to_string(), "performance".to_string()],
            },
            RepositoryRecommendation {
                repository: "clap-rs/clap".to_string(),
                reason: "Well-documented CLI library with excellent API design".to_string(),
                confidence: 0.85,
                framework_detected: None,
                complexity_tier: ComplexityTier::Beginner,
                learning_focus: vec!["CLI design".to_string(), "API ergonomics".to_string()],
            },
        ];

        let python_repos = vec![
            RepositoryRecommendation {
                repository: "tiangolo/fastapi".to_string(),
                reason: "Modern, fast web framework with excellent type hints".to_string(),
                confidence: 0.95,
                framework_detected: Some("FastAPI".to_string()),
                complexity_tier: ComplexityTier::Intermediate,
                learning_focus: vec!["API design".to_string(), "type hints".to_string()],
            },
            RepositoryRecommendation {
                repository: "pallets/flask".to_string(),
                reason: "Lightweight web framework perfect for learning".to_string(),
                confidence: 0.85,
                framework_detected: Some("Flask".to_string()),
                complexity_tier: ComplexityTier::Beginner,
                learning_focus: vec!["web basics".to_string(), "microframework".to_string()],
            },
            RepositoryRecommendation {
                repository: "encode/starlette".to_string(),
                reason: "ASGI framework demonstrating async patterns".to_string(),
                confidence: 0.80,
                framework_detected: None,
                complexity_tier: ComplexityTier::Advanced,
                learning_focus: vec!["ASGI".to_string(), "async patterns".to_string()],
            },
        ];

        let typescript_repos = vec![
            RepositoryRecommendation {
                repository: "facebook/react".to_string(),
                reason: "Industry-standard UI library with excellent patterns".to_string(),
                confidence: 0.95,
                framework_detected: Some("React".to_string()),
                complexity_tier: ComplexityTier::Intermediate,
                learning_focus: vec!["UI patterns".to_string(), "component design".to_string()],
            },
            RepositoryRecommendation {
                repository: "vercel/next.js".to_string(),
                reason: "Full-stack React framework with modern features".to_string(),
                confidence: 0.90,
                framework_detected: Some("Next.js".to_string()),
                complexity_tier: ComplexityTier::Advanced,
                learning_focus: vec!["full-stack".to_string(), "SSR".to_string()],
            },
            RepositoryRecommendation {
                repository: "expressjs/express".to_string(),
                reason: "Minimal web framework for Node.js".to_string(),
                confidence: 0.85,
                framework_detected: Some("Express".to_string()),
                complexity_tier: ComplexityTier::Beginner,
                learning_focus: vec!["Node.js".to_string(), "web server".to_string()],
            },
        ];

        self.curated_repositories
            .insert("rust".to_string(), rust_repos);
        self.curated_repositories
            .insert("python".to_string(), python_repos);
        self.curated_repositories
            .insert("typescript".to_string(), typescript_repos.clone());
        self.curated_repositories
            .insert("javascript".to_string(), typescript_repos);
    }

    pub fn analyze_repository(
        &self,
        path: &str,
    ) -> Result<Vec<String>, Box<dyn std::error::Error>> {
        let mut detected_frameworks = Vec::new();

        for (language, signatures) in &self.framework_signatures {
            for signature in signatures {
                let confidence = self.calculate_framework_confidence(path, signature)?;
                if confidence >= signature.confidence_threshold {
                    detected_frameworks.push(format!(
                        "{}: {} (confidence: {:.2})",
                        language, signature.name, confidence
                    ));
                }
            }
        }

        Ok(detected_frameworks)
    }

    fn calculate_framework_confidence(
        &self,
        _path: &str,
        signature: &FrameworkSignature,
    ) -> Result<f64, Box<dyn std::error::Error>> {
        let confidence = 0.0;
        let mut total_checks = 0.0;

        total_checks += signature.files.len() as f64;
        total_checks += signature.imports.len() as f64;
        total_checks += signature.dependencies.len() as f64;

        if total_checks == 0.0 {
            return Ok(0.0);
        }

        Ok(confidence / total_checks)
    }

    #[must_use]
    pub fn get_recommendations(
        &self,
        detected_language: &str,
        complexity_preference: Option<ComplexityTier>,
    ) -> Vec<RepositoryRecommendation> {
        let language_key = detected_language.to_lowercase();

        if let Some(repos) = self.curated_repositories.get(&language_key) {
            let mut recommendations = repos.clone();

            if let Some(pref) = complexity_preference {
                recommendations.retain(|repo| {
                    matches!(
                        (&repo.complexity_tier, &pref),
                        (ComplexityTier::Beginner, ComplexityTier::Beginner)
                            | (ComplexityTier::Intermediate, ComplexityTier::Intermediate)
                            | (ComplexityTier::Advanced, ComplexityTier::Advanced)
                            | (ComplexityTier::Expert, ComplexityTier::Expert)
                    )
                });
            }

            recommendations.sort_by(|a, b| {
                b.confidence
                    .partial_cmp(&a.confidence)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            recommendations
        } else {
            Vec::new()
        }
    }

    #[must_use]
    pub fn get_framework_specific_recommendations(
        &self,
        framework: &str,
    ) -> Vec<RepositoryRecommendation> {
        let mut recommendations = Vec::new();

        for repos in self.curated_repositories.values() {
            for repo in repos {
                if let Some(detected_framework) = &repo.framework_detected {
                    if detected_framework
                        .to_lowercase()
                        .contains(&framework.to_lowercase())
                    {
                        recommendations.push(repo.clone());
                    }
                }
            }
        }

        recommendations.sort_by(|a, b| {
            b.confidence
                .partial_cmp(&a.confidence)
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        recommendations
    }

    #[must_use]
    pub fn generate_learning_path(
        &self,
        language: &str,
        detected_frameworks: &[String],
    ) -> Vec<String> {
        let mut learning_path = Vec::new();

        learning_path.push(format!("Start with basic {language} syntax and concepts"));

        for framework_info in detected_frameworks {
            if let Some(colon_pos) = framework_info.find(':') {
                let framework = framework_info[colon_pos + 1..]
                    .split(" (")
                    .next()
                    .unwrap_or("")
                    .trim();
                learning_path.push(format!("Study {framework} framework patterns"));
            }
        }

        learning_path.push("Explore advanced patterns and best practices".to_string());
        learning_path.push("Contribute to open source projects".to_string());

        learning_path
    }
}

impl Default for RecommendationEngine {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_framework_signature_creation() {
        let signature = FrameworkSignature {
            name: "Test Framework".to_string(),
            files: vec!["test.config".to_string()],
            imports: vec!["test_lib".to_string()],
            dependencies: vec!["test-dep".to_string()],
            confidence_threshold: 0.8,
        };

        assert_eq!(signature.name, "Test Framework");
        assert_eq!(signature.confidence_threshold, 0.8);
    }

    #[test]
    fn test_recommendation_engine_initialization() {
        let engine = RecommendationEngine::new();
        assert!(!engine.framework_signatures.is_empty());
        assert!(!engine.curated_repositories.is_empty());
    }

    #[test]
    fn test_get_rust_recommendations() {
        let engine = RecommendationEngine::new();
        let recommendations = engine.get_recommendations("rust", None);
        assert!(!recommendations.is_empty());

        let has_tokio = recommendations
            .iter()
            .any(|r| r.repository.contains("tokio"));
        assert!(has_tokio);
    }

    #[test]
    fn test_complexity_tier_filtering() {
        let engine = RecommendationEngine::new();
        let beginner_recs = engine.get_recommendations("rust", Some(ComplexityTier::Beginner));

        for rec in beginner_recs {
            assert!(matches!(rec.complexity_tier, ComplexityTier::Beginner));
        }
    }

    #[test]
    fn test_framework_specific_recommendations() {
        let engine = RecommendationEngine::new();
        let react_recs = engine.get_framework_specific_recommendations("React");

        assert!(!react_recs.is_empty());
        for rec in react_recs {
            if let Some(framework) = &rec.framework_detected {
                assert!(framework.to_lowercase().contains("react"));
            }
        }
    }

    #[test]
    fn test_learning_path_generation() {
        let engine = RecommendationEngine::new();
        let detected_frameworks = vec!["rust: Tokio (confidence: 0.85)".to_string()];
        let learning_path = engine.generate_learning_path("rust", &detected_frameworks);

        assert!(!learning_path.is_empty());
        assert!(learning_path[0].contains("basic rust"));
        assert!(learning_path.iter().any(|step| step.contains("Tokio")));
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod property_tests {
    use proptest::prelude::*;

    proptest! {
        #[test]
        fn basic_property_stability(_input in ".*") {
            // Basic property test for coverage
            prop_assert!(true);
        }

        #[test]
        fn module_consistency_check(_x in 0u32..1000) {
            // Module consistency verification
            prop_assert!(_x < 1001);
        }
    }
}