pmat 3.16.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
    /// Test check_duplicates with unique files
    #[tokio::test]
    async fn test_check_duplicates_unique_files() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let file1 = temp_dir.path().join("unique1.rs");
        let file2 = temp_dir.path().join("unique2.rs");

        tokio::fs::write(&file1, "fn unique_function_one() { println!(\"one\"); }").await?;
        tokio::fs::write(&file2, "fn unique_function_two() { println!(\"two\"); }").await?;

        let violations = check_duplicates(temp_dir.path()).await?;

        // Should detect no duplicates
        assert_eq!(violations.len(), 0);

        Ok(())
    }

    /// Test check_duplicates ignores small files
    #[tokio::test]
    async fn test_check_duplicates_ignores_small_files() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        // Create small identical files (should be ignored)
        let small_content = "x";

        let small1 = temp_dir.path().join("small1.rs");
        let small2 = temp_dir.path().join("small2.rs");

        tokio::fs::write(&small1, small_content).await?;
        tokio::fs::write(&small2, small_content).await?;

        let violations = check_duplicates(temp_dir.path()).await?;

        // Should ignore small files
        assert_eq!(violations.len(), 0);

        Ok(())
    }

    /// Test is_build_artifact function excludes build directories
    #[test]
    fn test_is_build_artifact() {
        use std::path::Path;

        // Should exclude target directory files
        assert!(is_build_artifact(Path::new(
            "./target/debug/build/pmat-123/out/tool_registry.rs"
        )));
        assert!(is_build_artifact(Path::new("target/debug/deps/pmat.rs")));

        // Should exclude other build artifacts
        assert!(is_build_artifact(Path::new("./build/generated.rs")));
        assert!(is_build_artifact(Path::new("./out/alias_table.rs")));
        assert!(is_build_artifact(Path::new(
            "./.cargo/registry/src/github.com/file.rs"
        )));
        assert!(is_build_artifact(Path::new(
            "./node_modules/package/lib.js"
        )));
        assert!(is_build_artifact(Path::new("./dist/bundle.js")));
        assert!(is_build_artifact(Path::new("./.git/objects/ab/cd1234")));
        assert!(is_build_artifact(Path::new("./generated/proto.rs")));

        // Should NOT exclude source files
        assert!(!is_build_artifact(Path::new("./server/src/lib.rs")));
        assert!(!is_build_artifact(Path::new("./src/main.rs")));
        assert!(!is_build_artifact(Path::new(
            "./server/src/handlers/tools.rs"
        )));
    }

    /// Test is_excluded_directory function excludes build directories
    #[test]
    fn test_is_excluded_directory() {
        // Should exclude build directories
        assert!(is_excluded_directory("./target"));
        assert!(is_excluded_directory("target"));
        assert!(is_excluded_directory("target/"));
        assert!(is_excluded_directory("./target/"));
        assert!(is_excluded_directory("./build"));
        assert!(is_excluded_directory("build"));
        assert!(is_excluded_directory("./project/target/"));
        assert!(is_excluded_directory("./project/target/debug"));
        assert!(is_excluded_directory("./target/debug/build"));
        assert!(is_excluded_directory("./foo/node_modules/"));
        assert!(is_excluded_directory("./bar/.git/"));
        assert!(is_excluded_directory(
            "./server/target/debug/build/unicode_names2-c78072d37d9beb66/out/generated.rs"
        ));
        assert!(is_excluded_directory(
            "./target/debug/build/rustpython-parser-5d3dfbfd27d1a200/out/keywords.rs"
        ));

        // Should NOT exclude source directories
        assert!(!is_excluded_directory("server"));
        assert!(!is_excluded_directory("src"));
        assert!(!is_excluded_directory("./server/src"));
        assert!(!is_excluded_directory("./server/src/cli"));
    }

    /// Test check_single_file_complexity with high complexity function
    #[tokio::test]
    async fn test_check_single_file_complexity_violations() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        // Create Rust file with high complexity function
        let rust_file = temp_dir.path().join("complex.rs");
        tokio::fs::write(
            &rust_file,
            r#"
fn high_complexity_function(x: i32) -> i32 {
    if x > 10 {
        if x > 20 {
            if x > 30 {
                if x > 40 {
                    if x > 50 {
                        100
                    } else {
                        90
                    }
                } else {
                    80
                }
            } else {
                70
            }
        } else {
            60
        }
    } else {
        50
    }
}
"#,
        )
        .await?;

        let violations = check_single_file_complexity(
            temp_dir.path(),
            &rust_file,
            5, // Low threshold to catch high complexity
        )
        .await?;

        // Should detect complexity violation
        assert!(!violations.is_empty());
        assert!(violations.iter().any(|v| v.check_type == "complexity"));
        assert!(violations.iter().any(|v| v.severity == "error"));

        Ok(())
    }

    /// Test check_single_file_complexity with missing file
    #[tokio::test]
    async fn test_check_single_file_complexity_missing_file() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;
        let missing_file = temp_dir.path().join("missing.rs");

        let result = check_single_file_complexity(temp_dir.path(), &missing_file, 10).await;

        // Should return error for missing file
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("File not found"));

        Ok(())
    }

    /// Test check_single_file_complexity with low complexity function
    #[tokio::test]
    async fn test_check_single_file_complexity_no_violations() -> anyhow::Result<()> {
        let temp_dir = TempDir::new()?;

        let simple_file = temp_dir.path().join("simple.rs");
        tokio::fs::write(
            &simple_file,
            r#"
fn simple_function(x: i32) -> i32 {
    x * 2
}

fn another_simple(y: i32) -> i32 {
    y + 1
}
"#,
        )
        .await?;

        let violations = check_single_file_complexity(
            temp_dir.path(),
            &simple_file,
            10, // High threshold
        )
        .await?;

        // Should detect no violations
        assert_eq!(violations.len(), 0);

        Ok(())
    }

    /// Test write_markdown_summary_table functionality
    #[test]
    fn test_write_markdown_summary_table() -> anyhow::Result<()> {
        use crate::models::churn::ChurnSummary;
        use std::collections::HashMap;

        let mut output = String::new();

        // Create test summary data
        let summary = ChurnSummary {
            total_commits: 42,
            total_files_changed: 15,
            hotspot_files: vec!["file1.rs".into(), "file2.rs".into()],
            stable_files: vec!["lib.rs".into()],
            author_contributions: {
                let mut map = HashMap::new();
                map.insert("alice".to_string(), 5);
                map.insert("bob".to_string(), 3);
                map
            },
            mean_churn_score: 0.0,
            variance_churn_score: 0.0,
            stddev_churn_score: 0.0,
        };

        write_markdown_summary_table(&mut output, &summary)?;

        // Verify table structure
        assert!(output.contains("## Summary Statistics"));
        assert!(output.contains("| Metric | Value |"));
        assert!(output.contains("| Total Commits | 42 |"));
        assert!(output.contains("| Files Changed | 15 |"));
        assert!(output.contains("| Hotspot Files | 2 |"));
        assert!(output.contains("| Stable Files | 1 |"));
        assert!(output.contains("| Contributing Authors | 2 |"));

        Ok(())
    }

    /// Test write_markdown_summary_table with empty data
    #[test]
    fn test_write_markdown_summary_table_empty() -> anyhow::Result<()> {
        use crate::models::churn::ChurnSummary;
        use std::collections::HashMap;

        let mut output = String::new();

        let empty_summary = ChurnSummary {
            total_commits: 0,
            total_files_changed: 0,
            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,
        };

        write_markdown_summary_table(&mut output, &empty_summary)?;

        // Should still create proper table structure
        assert!(output.contains("## Summary Statistics"));
        assert!(output.contains("| Total Commits | 0 |"));
        assert!(output.contains("| Hotspot Files | 0 |"));

        Ok(())
    }

    /// Test write_markdown_summary_table output format
    #[test]
    fn test_write_markdown_summary_table_format() -> anyhow::Result<()> {
        use crate::models::churn::ChurnSummary;
        use std::collections::HashMap;

        let mut output = String::new();
        let summary = ChurnSummary {
            total_commits: 1,
            total_files_changed: 1,
            hotspot_files: vec!["test.rs".into()],
            stable_files: vec!["mod.rs".into()],
            author_contributions: {
                let mut map = HashMap::new();
                map.insert("dev".to_string(), 1);
                map
            },
            mean_churn_score: 0.0,
            variance_churn_score: 0.0,
            stddev_churn_score: 0.0,
        };

        write_markdown_summary_table(&mut output, &summary)?;

        // Check markdown table separator format
        assert!(output.contains("|--------|-------|"));
        // Check all rows have proper pipe separators
        let lines: Vec<&str> = output.lines().collect();
        let table_lines: Vec<&str> = lines
            .iter()
            .filter(|line| line.contains("|"))
            .cloned()
            .collect();

        assert!(table_lines.len() >= 3); // Header, separator, data rows

        Ok(())
    }

    /// Test print_single_check for different check types
    #[test]
    fn test_print_single_check_all_types() {
        use crate::cli::enums::QualityCheckType;

        // Test each check type (output goes to stderr, so we can't easily capture it)
        // But we can verify the function doesn't panic
        print_single_check(&QualityCheckType::Complexity);
        print_single_check(&QualityCheckType::DeadCode);
        print_single_check(&QualityCheckType::Satd);
        print_single_check(&QualityCheckType::Security);
        print_single_check(&QualityCheckType::Entropy);
        print_single_check(&QualityCheckType::Duplicates);
        print_single_check(&QualityCheckType::Coverage);

        // Should complete without panicking
        // Test passes if we reach this point without panicking
    }

    /// Test print_single_check with All type (should be handled by wildcard)
    #[test]
    fn test_print_single_check_all_and_wildcard() {
        use crate::cli::enums::QualityCheckType;

        // Test the wildcard case
        print_single_check(&QualityCheckType::All);

        // Should complete without panicking
        // Test passes if we reach this point without panicking
    }

    #[tokio::test]
    async fn test_handle_analyze_makefile_basic() {
        // Create a temporary directory and Makefile
        let temp_dir = TempDir::new().unwrap();
        let makefile_path = temp_dir.path().join("Makefile");
        let mut file = std::fs::File::create(&makefile_path).unwrap();
        writeln!(file, "all:").unwrap();
        writeln!(file, "\techo 'Hello World'").unwrap();

        // Test basic makefile analysis
        let result = handle_analyze_makefile(
            makefile_path.clone(),
            vec![], // Empty rules vector
            MakefileOutputFormat::Human,
            false,
            None,
            10, // top_files
        )
        .await;

        // Should complete without error
        assert!(
            result.is_ok(),
            "Makefile analysis failed: {:?}",
            result.err()
        );
    }

    #[tokio::test]
    async fn test_handle_analyze_makefile_with_rules() {
        let temp_dir = TempDir::new().unwrap();
        let makefile_path = temp_dir.path().join("Makefile");
        let mut file = std::fs::File::create(&makefile_path).unwrap();
        writeln!(file, "test:").unwrap();
        writeln!(file, "\tcargo test").unwrap();

        // Test with custom rules
        let result = handle_analyze_makefile(
            makefile_path,
            vec!["phonytargets".to_string()],
            MakefileOutputFormat::Json,
            false,
            Some("3.82".to_string()),
            10, // top_files
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_analyze_provability() {
        let temp_dir = TempDir::new().unwrap();
        let project_path = temp_dir.path().to_path_buf();

        // Create a simple Rust file for analysis
        let src_dir = project_path.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        let rust_file = src_dir.join("lib.rs");
        let mut file = std::fs::File::create(&rust_file).unwrap();
        writeln!(file, "pub fn add(a: i32, b: i32) -> i32 {{").unwrap();
        writeln!(file, "    a + b").unwrap();
        writeln!(file, "}}").unwrap();

        // Test provability analysis
        let result = handle_analyze_provability(
            project_path,
            vec!["add".to_string()], // Functions to analyze
            10,                      // Analysis depth
            ProvabilityOutputFormat::Json,
            false, // high_confidence_only
            false, // include_evidence
            None,  // output path
            10,    // top_files
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_analyze_defect_prediction() {
        let temp_dir = TempDir::new().unwrap();
        let project_path = temp_dir.path().to_path_buf();

        // Create test files
        let src_dir = project_path.join("src");
        std::fs::create_dir_all(&src_dir).unwrap();
        let rust_file = src_dir.join("main.rs");
        let mut file = std::fs::File::create(&rust_file).unwrap();
        writeln!(file, "fn main() {{").unwrap();
        writeln!(file, "    println!(\"Hello, world!\");").unwrap();
        writeln!(file, "}}").unwrap();

        // Test defect prediction
        let result = handle_analyze_defect_prediction(
            project_path,
            0.5,   // confidence_threshold
            10,    // min_lines
            false, // include_low_confidence
            DefectPredictionOutputFormat::Summary,
            false, // high_risk_only
            false, // include_recommendations
            None,  // include
            None,  // exclude
            None,  // output
            false, // _perf
            10,    // top_files
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_analyze_proof_annotations() {
        let temp_dir = TempDir::new().unwrap();
        let project_path = temp_dir.path().to_path_buf();

        // Test proof annotation collection
        let result = handle_analyze_proof_annotations(
            project_path,
            ProofAnnotationOutputFormat::Json,
            false, // high_confidence_only
            false, // include_evidence
            None,  // sources
            None,  // confidence_levels
            None,  // output
            false, // _perf
            false, // clear_cache
        )
        .await;

        assert!(result.is_ok());
    }