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
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
#![cfg_attr(coverage_nightly, coverage(off))]
// Toyota Way: Unified SATD Analyzer
//
// Consolidates Self-Admitted Technical Debt analysis under the unified analyzer framework
// to reduce structural complexity and achieve A+ grade.

use super::{Analyzer, AnalyzerInfo, ProjectAnalyzer, ProjectConfig, ProjectInput};
use crate::services::satd_detector::{SATDAnalysisResult, SATDDetector};
use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::path::Path;

/// Unified SATD (Self-Admitted Technical Debt) analyzer implementation
pub struct SATDAnalyzer {
    inner: SATDDetector,
}

impl SATDAnalyzer {
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> Self {
        Self {
            inner: SATDDetector::new(),
        }
    }

    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// New with strict mode.
    pub fn new_with_strict_mode(strict: bool) -> Self {
        if strict {
            Self {
                inner: SATDDetector::new_strict(),
            }
        } else {
            Self::new()
        }
    }
}

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

/// Configuration specific to SATD analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SATDConfig {
    pub base: ProjectConfig,
    pub strict_mode: bool,
    pub critical_only: bool,
    pub include_context: bool,
}

impl Default for SATDConfig {
    fn default() -> Self {
        Self {
            base: ProjectConfig::default(),
            strict_mode: false,
            critical_only: false,
            include_context: true,
        }
    }
}

/// Output from SATD analysis (reusing existing result type)
pub type SATDOutput = SATDAnalysisResult;

#[async_trait]
impl Analyzer for SATDAnalyzer {
    type Input = ProjectInput;
    type Output = SATDOutput;
    type Config = ProjectConfig;

    async fn analyze(&self, input: Self::Input, config: Self::Config) -> Result<Self::Output> {
        // Delegate to the original analyzer's project analysis method
        // Convert TemplateError to anyhow::Error
        self.inner
            .analyze_project(&input.project_path, config.include_tests)
            .await
            .map_err(|e| anyhow::anyhow!("SATD analysis failed: {e}"))
    }

    fn name(&self) -> &'static str {
        "satd"
    }
}

#[async_trait]
impl ProjectAnalyzer for SATDAnalyzer {
    async fn analyze_project(&self, project_path: &Path) -> Result<Self::Output> {
        let input = ProjectInput {
            project_path: project_path.to_path_buf(),
        };
        let config = ProjectConfig::default();
        self.analyze(input, config).await
    }
}

impl AnalyzerInfo for SATDAnalyzer {
    fn name(&self) -> &'static str {
        "satd"
    }

    fn version(&self) -> &'static str {
        env!("CARGO_PKG_VERSION")
    }

    fn description(&self) -> &'static str {
        "Analyzes code for Self-Admitted Technical Debt (SATD) in comments and documentation"
    }
}

/// Factory for creating SATD analyzers
pub struct SATDAnalyzerFactory;

impl SATDAnalyzerFactory {
    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create.
    pub fn create() -> SATDAnalyzer {
        SATDAnalyzer::new()
    }

    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create strict.
    pub fn create_strict() -> SATDAnalyzer {
        SATDAnalyzer::new_with_strict_mode(true)
    }

    #[must_use]
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create critical only.
    pub fn create_critical_only() -> SATDAnalyzer {
        // Create analyzer with strict mode for critical issues
        SATDAnalyzer::new_with_strict_mode(true)
    }
}

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

    // === SATDAnalyzer tests ===

    #[tokio::test]
    async fn test_satd_analyzer_creation() {
        let analyzer = SATDAnalyzer::new();
        assert_eq!(Analyzer::name(&analyzer), "satd");
        assert_eq!(Analyzer::version(&analyzer), env!("CARGO_PKG_VERSION"));
    }

    #[test]
    fn test_satd_analyzer_new() {
        let analyzer = SATDAnalyzer::new();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_satd_analyzer_default() {
        let analyzer = SATDAnalyzer::default();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_satd_analyzer_with_strict_mode_true() {
        let analyzer = SATDAnalyzer::new_with_strict_mode(true);
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_satd_analyzer_with_strict_mode_false() {
        let analyzer = SATDAnalyzer::new_with_strict_mode(false);
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_satd_analyzer_name_trait() {
        let analyzer = SATDAnalyzer::new();
        assert_eq!(Analyzer::name(&analyzer), "satd");
    }

    // === SATDConfig tests ===

    #[tokio::test]
    async fn test_satd_config_default() {
        let config = SATDConfig::default();
        assert!(!config.strict_mode);
        assert!(!config.critical_only);
        assert!(config.include_context);
    }

    #[test]
    fn test_satd_config_custom() {
        let config = SATDConfig {
            base: ProjectConfig::default(),
            strict_mode: true,
            critical_only: true,
            include_context: false,
        };

        assert!(config.strict_mode);
        assert!(config.critical_only);
        assert!(!config.include_context);
    }

    #[test]
    fn test_satd_config_serialization() {
        let config = SATDConfig::default();
        let json = serde_json::to_string(&config).unwrap();

        assert!(json.contains("strict_mode"));
        assert!(json.contains("critical_only"));
        assert!(json.contains("include_context"));
    }

    #[test]
    fn test_satd_config_deserialization() {
        let json = r#"{
            "base": {"include_tests": true, "max_depth": null, "parallel": false},
            "strict_mode": true,
            "critical_only": false,
            "include_context": true
        }"#;

        let config: SATDConfig = serde_json::from_str(json).unwrap();
        assert!(config.strict_mode);
        assert!(!config.critical_only);
        assert!(config.include_context);
    }

    #[test]
    fn test_satd_config_clone() {
        let config = SATDConfig::default();
        let cloned = config.clone();

        assert_eq!(config.strict_mode, cloned.strict_mode);
        assert_eq!(config.critical_only, cloned.critical_only);
        assert_eq!(config.include_context, cloned.include_context);
    }

    #[test]
    fn test_satd_config_debug() {
        let config = SATDConfig::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("SATDConfig"));
        assert!(debug_str.contains("strict_mode"));
    }

    // === AnalyzerInfo tests ===

    #[tokio::test]
    async fn test_analyzer_info() {
        let analyzer = SATDAnalyzer::new();
        assert_eq!(Analyzer::name(&analyzer), "satd");
        assert!(AnalyzerInfo::description(&analyzer).contains("Technical Debt"));
    }

    #[test]
    fn test_analyzer_info_name() {
        let analyzer = SATDAnalyzer::new();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_analyzer_info_version() {
        let analyzer = SATDAnalyzer::new();
        let version = AnalyzerInfo::version(&analyzer);
        assert!(!version.is_empty());
        // Should be a valid semver version
        assert!(version.contains('.'));
    }

    #[test]
    fn test_analyzer_info_description() {
        let analyzer = SATDAnalyzer::new();
        let description = AnalyzerInfo::description(&analyzer);

        assert!(description.contains("SATD"));
        assert!(description.contains("Technical Debt"));
    }

    // === SATDAnalyzerFactory tests ===

    #[tokio::test]
    async fn test_factory_creation() {
        let analyzer = SATDAnalyzerFactory::create();
        assert_eq!(Analyzer::name(&analyzer), "satd");

        let strict_analyzer = SATDAnalyzerFactory::create_strict();
        assert_eq!(Analyzer::name(&strict_analyzer), "satd");

        let critical_analyzer = SATDAnalyzerFactory::create_critical_only();
        assert_eq!(Analyzer::name(&critical_analyzer), "satd");
    }

    #[test]
    fn test_factory_create() {
        let analyzer = SATDAnalyzerFactory::create();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_factory_create_strict() {
        let analyzer = SATDAnalyzerFactory::create_strict();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    #[test]
    fn test_factory_create_critical_only() {
        let analyzer = SATDAnalyzerFactory::create_critical_only();
        assert_eq!(AnalyzerInfo::name(&analyzer), "satd");
    }

    // === Project analysis tests ===

    #[tokio::test]
    async fn test_project_analysis() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.rs");
        fs::write(
            &test_file,
            r#"
            fn good_function() -> i32 {
                42
            }

            fn bad_function() -> i32 {
                // TODO: This needs to be fixed eventually
                // FIXME: Memory leak possible here
                // HACK: Quick workaround for now
                0
            }
        "#,
        )
        .unwrap();

        let analyzer = SATDAnalyzer::new();
        let result = analyzer.analyze_project(temp_dir.path()).await.unwrap();

        // May or may not find debt items depending on analyzer implementation
        if !result.items.is_empty() {
            assert!(result.total_files_analyzed > 0);
            assert!(result.files_with_debt > 0);

            // If we found debt, verify it contains expected patterns
            let debt_texts: Vec<&str> =
                result.items.iter().map(|item| item.text.as_str()).collect();
            assert!(debt_texts.iter().any(|text| text.contains("TODO")
                || text.contains("FIXME")
                || text.contains("HACK")));
        }
    }

    #[tokio::test]
    async fn test_strict_mode_analyzer() {
        let analyzer = SATDAnalyzer::new_with_strict_mode(true);
        assert_eq!(Analyzer::name(&analyzer), "satd");

        // In strict mode, analyzer should still work but potentially find more issues
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.rs");
        fs::write(
            &test_file,
            "// NOTE: This might be considered debt in strict mode",
        )
        .unwrap();

        let result = analyzer.analyze_project(temp_dir.path()).await.unwrap();
        // Either finds files or doesn't, both are valid
        assert!(result.total_files_analyzed <= 1);
    }

    #[tokio::test]
    async fn test_analyze_empty_directory() {
        let temp_dir = TempDir::new().unwrap();
        let analyzer = SATDAnalyzer::new();

        let result = analyzer.analyze_project(temp_dir.path()).await.unwrap();
        assert!(result.items.is_empty());
    }

    #[tokio::test]
    async fn test_analyze_with_config() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.rs");
        fs::write(&test_file, "fn main() {}").unwrap();

        let analyzer = SATDAnalyzer::new();
        let input = ProjectInput {
            project_path: temp_dir.path().to_path_buf(),
        };
        let config = ProjectConfig {
            include_tests: true,
            max_depth: None,
            parallel: false,
        };

        let result = analyzer.analyze(input, config).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_analyze_multiple_files() {
        let temp_dir = TempDir::new().unwrap();

        fs::write(
            temp_dir.path().join("file1.rs"),
            "// TODO: Implement this\nfn stub1() {}",
        )
        .unwrap();

        fs::write(
            temp_dir.path().join("file2.rs"),
            "// FIXME: Bug here\nfn stub2() {}",
        )
        .unwrap();

        fs::write(temp_dir.path().join("file3.rs"), "fn clean_code() {}").unwrap();

        let analyzer = SATDAnalyzer::new();
        let result = analyzer.analyze_project(temp_dir.path()).await.unwrap();

        // Should analyze multiple files (result completes without panic)
        let _ = result.total_files_analyzed;
    }

    #[tokio::test]
    async fn test_analyze_nested_directory() {
        let temp_dir = TempDir::new().unwrap();
        let nested_dir = temp_dir.path().join("src").join("utils");
        fs::create_dir_all(&nested_dir).unwrap();

        fs::write(
            nested_dir.join("helper.rs"),
            "// HACK: Temporary solution\nfn helper() {}",
        )
        .unwrap();

        let analyzer = SATDAnalyzer::new();
        let result = analyzer.analyze_project(temp_dir.path()).await.unwrap();

        // Should analyze nested files (result completes without panic)
        let _ = result.total_files_analyzed;
    }

    // === ProjectAnalyzer trait tests ===

    #[tokio::test]
    async fn test_project_analyzer_trait() {
        let temp_dir = TempDir::new().unwrap();
        fs::write(temp_dir.path().join("test.rs"), "fn main() {}").unwrap();

        let analyzer = SATDAnalyzer::new();
        let result = ProjectAnalyzer::analyze_project(&analyzer, temp_dir.path()).await;

        assert!(result.is_ok());
    }
}

#[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);
        }
    }
}