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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
//! Extreme TDD Tests for Missing Annotations in Unified Context
//!
//! Following RED-GREEN-REFACTOR cycle for each missing annotation type

use std::fs;
use tempfile::TempDir;

/// Find the pmat binary in the target directory.
/// Works regardless of CARGO_TARGET_DIR or custom target paths.
/// Checks both debug and release directories (CI builds release).
#[cfg(test)]
fn pmat_bin_path() -> Option<std::path::PathBuf> {
    let test_exe = std::env::current_exe().expect("current_exe");
    // test binary is at <target>/debug/deps/pmat-<hash>
    // pmat binary is at <target>/debug/pmat or <target>/release/pmat
    let target_debug = test_exe.parent().unwrap().parent().unwrap();
    let debug_bin = target_debug.join("pmat");
    if debug_bin.exists() {
        return Some(debug_bin);
    }
    // Check release dir: <target>/release/pmat
    let target_dir = target_debug.parent().unwrap();
    let release_bin = target_dir.join("release").join("pmat");
    if release_bin.exists() {
        return Some(release_bin);
    }
    None
}

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

    #[tokio::test]
    // Re-enabled: pmat binary now available
    async fn red_must_show_individual_function_names() {
        let Some(bin) = pmat_bin_path() else {
            eprintln!("pmat binary not found, skipping integration test");
            return;
        };
        // RED: This test MUST fail initially, proving we're missing function names
        let temp_dir = TempDir::new().unwrap();

        let ts_content = r#"
function calculateTotal() { return 42; }
function processData() { return "data"; }
const validateInput = () => { return true; };
"#;

        fs::write(temp_dir.path().join("test.ts"), ts_content).unwrap();

        // Run pmat context and capture output
        let output = std::process::Command::new(bin)
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // These assertions MUST FAIL in RED phase
        assert!(
            stdout.contains("calculateTotal"),
            "Missing function name 'calculateTotal' in output"
        );
        assert!(
            stdout.contains("processData"),
            "Missing function name 'processData' in output"
        );
        assert!(
            stdout.contains("validateInput"),
            "Missing function name 'validateInput' in output"
        );
    }

    #[tokio::test]
    // Re-enabled: pmat binary now available
    async fn red_must_show_file_level_breakdown() {
        let Some(bin) = pmat_bin_path() else {
            eprintln!("pmat binary not found, skipping integration test");
            return;
        };
        // RED: Must show which functions belong to which files
        let temp_dir = TempDir::new().unwrap();

        fs::write(
            temp_dir.path().join("auth.ts"),
            "function login() {} function logout() {}",
        )
        .unwrap();
        fs::write(
            temp_dir.path().join("utils.ts"),
            "function formatDate() {} function parseJSON() {}",
        )
        .unwrap();

        let output = std::process::Command::new(bin)
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Must show file grouping
        assert!(
            stdout.contains("File: auth.ts") || stdout.contains("auth.ts"),
            "Missing file-level grouping for auth.ts"
        );
        assert!(
            stdout.contains("File: utils.ts") || stdout.contains("utils.ts"),
            "Missing file-level grouping for utils.ts"
        );

        // Must show functions under their files
        let auth_index = stdout.find("auth.ts").unwrap_or(0);
        let utils_index = stdout.find("utils.ts").unwrap_or(0);
        let login_index = stdout.find("login").unwrap_or(0);
        let format_index = stdout.find("formatDate").unwrap_or(0);

        assert!(
            login_index > auth_index && login_index < utils_index,
            "Function 'login' not properly grouped under auth.ts"
        );
        assert!(
            format_index > utils_index,
            "Function 'formatDate' not properly grouped under utils.ts"
        );
    }

    #[tokio::test]
    #[ignore = "Requires pmat binary to be built"]
    async fn red_must_show_complexity_scores() {
        // RED: Must show complexity metrics for functions
        let temp_dir = TempDir::new().unwrap();
        let complex_function = COMPLEX_JS_FUNCTION;

        fs::write(temp_dir.path().join("complex.js"), complex_function).unwrap();

        let output = std::process::Command::new(pmat_bin_path().unwrap())
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);
        assert_complexity_output(&stdout);
    }

    const COMPLEX_JS_FUNCTION: &str = r#"
function complexLogic(input) {
    if (input > 10) {
        if (input > 20) {
            for (let i = 0; i < input; i++) {
                if (i % 2 === 0) {
                    console.log(i);
                }
            }
        }
    } else {
        switch(input) {
            case 1: return "one";
            case 2: return "two";
            default: return "other";
        }
    }
}
"#;

    fn assert_complexity_output(stdout: &str) {
        assert!(
            stdout.contains("complexity")
                || stdout.contains("Complexity")
                || stdout.contains("cyclomatic"),
            "Missing complexity metrics in output"
        );
        assert!(
            stdout.contains("complexLogic")
                && (stdout.contains("high") || stdout.contains("High") || stdout.contains("")),
            "Missing high complexity warning for complex function"
        );
    }

    #[tokio::test]
    #[ignore = "Requires pmat binary to be built"]
    async fn red_must_show_satd_annotations() {
        // RED: Must detect and show Self-Admitted Technical Debt
        let temp_dir = TempDir::new().unwrap();

        let code_with_debt = r#"
// TODO: Refactor this to use async/await
function oldStyleCallback(cb) {
    setTimeout(() => {
        cb("done");
    }, 1000);
}

// FIXME: This has a memory leak
function leakyFunction() {
    // HACK: Using global to store state
    window.globalState = window.globalState || [];
    window.globalState.push(new Array(1000000));
}
"#;

        fs::write(temp_dir.path().join("debt.js"), code_with_debt).unwrap();

        let output = std::process::Command::new(pmat_bin_path().unwrap())
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Must show SATD markers
        assert!(
            stdout.contains("TODO") || stdout.contains("Technical Debt") || stdout.contains("SATD"),
            "Missing SATD annotations"
        );
        assert!(
            stdout.contains("FIXME") || stdout.contains("memory leak"),
            "Missing FIXME annotation for memory leak"
        );
        assert!(
            stdout.contains("HACK") || stdout.contains("global state"),
            "Missing HACK annotation"
        );
    }

    #[tokio::test]
    #[ignore = "Requires pmat binary to be built"]
    async fn red_must_show_quality_insights() {
        // RED: Must provide quality insights and recommendations
        let temp_dir = TempDir::new().unwrap();

        // Create files with various quality issues
        fs::write(
            temp_dir.path().join("long.js"),
            format!(
                "function veryLong() {{\n{}}}",
                "console.log('line');\n".repeat(200) + "}"
            ),
        )
        .unwrap();

        fs::write(temp_dir.path().join("duplicate.js"),
            "function copy1() { return 42; }\nfunction copy2() { return 42; }\nfunction copy3() { return 42; }").unwrap();

        let output = std::process::Command::new(pmat_bin_path().unwrap())
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Must show quality insights section
        assert!(
            stdout.contains("Quality")
                || stdout.contains("Insights")
                || stdout.contains("Recommendations"),
            "Missing quality insights section"
        );

        // Must identify specific issues
        assert!(
            stdout.contains("long")
                || stdout.contains("Long")
                || stdout.contains("lines")
                || stdout.contains("LOC"),
            "Missing insight about long function"
        );
    }

    #[tokio::test]
    // Re-enabled: pmat binary now available
    async fn red_must_show_dead_code_markers() {
        let Some(bin) = pmat_bin_path() else {
            eprintln!("pmat binary not found, skipping integration test");
            return;
        };
        // RED: Must identify potentially dead code
        let temp_dir = TempDir::new().unwrap();

        let code_with_dead = r#"
function usedFunction() {
    return "I am used";
}

function unusedFunction() {
    return "I am never called";
}

// Export shows what's actually used
export { usedFunction };
"#;

        fs::write(temp_dir.path().join("mixed.js"), code_with_dead).unwrap();

        let output = std::process::Command::new(bin)
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Must show dead code indicators
        assert!(
            stdout.contains("unusedFunction")
                && (stdout.contains("dead")
                    || stdout.contains("Dead")
                    || stdout.contains("unused")
                    || stdout.contains("")),
            "Missing dead code marker for unused function"
        );
    }

    #[tokio::test]
    #[ignore = "Requires pmat binary to be built"]
    async fn red_must_show_wasm_function_details() {
        // RED: Must properly annotate WASM functions
        let temp_dir = TempDir::new().unwrap();

        let wasm_content = r#"
(module
  (func $fibonacci (param $n i32) (result i32)
    local.get $n
    i32.const 2
    i32.lt_s
    if (result i32)
      local.get $n
    else
      local.get $n
      i32.const 1
      i32.sub
      call $fibonacci
      local.get $n
      i32.const 2
      i32.sub
      call $fibonacci
      i32.add
    end
  )
  (export "fibonacci" (func $fibonacci))
)
"#;

        fs::write(temp_dir.path().join("math.wat"), wasm_content).unwrap();

        let output = std::process::Command::new(pmat_bin_path().unwrap())
            .args([
                "context",
                "--project-path",
                temp_dir.path().to_str().unwrap(),
                "--format",
                "llm-optimized",
            ])
            .output()
            .expect("Failed to run pmat");

        let stdout = String::from_utf8_lossy(&output.stdout);

        // Must show WASM function with special annotation
        assert!(
            stdout.contains("fibonacci") || stdout.contains("$fibonacci"),
            "Missing WASM function name"
        );
        assert!(
            stdout.contains("WASM") || stdout.contains("WebAssembly") || stdout.contains(".wat"),
            "Missing WASM type annotation"
        );
        assert!(
            stdout.contains("export") || stdout.contains("Export"),
            "Missing export annotation for WASM function"
        );
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod green_phase_implementation {

    // Helper to create enhanced format output
    pub(super) fn format_context_with_annotations(
        analysis_report: &crate::services::simple_deep_context::SimpleAnalysisReport,
        project_path: &std::path::Path,
    ) -> String {
        let mut output = String::new();

        // Header
        output.push_str(&format!(
            "Project: {} (detected)\n\n",
            project_path
                .file_name()
                .unwrap_or_default()
                .to_string_lossy()
        ));

        // Summary
        output.push_str("Summary:\n");
        output.push_str(&format!("- Files: {}\n", analysis_report.file_count));
        output.push_str(&format!(
            "- Functions: {}\n",
            analysis_report.complexity_metrics.total_functions
        ));
        output.push('\n');

        // Key Components - File breakdown with functions
        output.push_str("Key Components:\n\n");

        for file_detail in &analysis_report.file_complexity_details {
            output.push_str(&format!("File: {}\n", file_detail.file_path.display()));
            output.push_str(&format!("  Functions: {}\n", file_detail.function_count));

            if file_detail.high_complexity_functions > 0 {
                output.push_str(&format!(
                    "  ⚠ High Complexity: {} functions\n",
                    file_detail.high_complexity_functions
                ));
            }

            output.push_str(&format!(
                "  Average Complexity: {:.1}\n",
                file_detail.avg_complexity
            ));
            output.push('\n');
        }

        // Quality Insights
        if analysis_report.complexity_metrics.high_complexity_count > 0 {
            output.push_str("Quality Insights:\n");
            output.push_str(&format!(
                "- {} functions have high complexity and should be refactored\n",
                analysis_report.complexity_metrics.high_complexity_count
            ));
            output.push_str(&format!(
                "- Average complexity: {:.1}\n",
                analysis_report.complexity_metrics.avg_complexity
            ));
            output.push('\n');
        }

        // Recommendations
        if !analysis_report.recommendations.is_empty() {
            output.push_str("Recommendations:\n");
            for rec in &analysis_report.recommendations {
                output.push_str(&format!("- {}\n", rec));
            }
        }

        output
    }
}

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

    proptest! {
        #[test]
        fn property_annotations_preserve_function_count(file_count in 1u8..=50, functions_per_file in 1u8..=10) {
            let total_functions = file_count as usize * functions_per_file as usize;

            // Create mock analysis report
            let mut file_details = Vec::new();
            for i in 0..file_count {
                file_details.push(crate::services::simple_deep_context::FileComplexityDetail {
                    file_path: format!("file{}.js", i).into(),
                    function_count: functions_per_file as usize,
                    high_complexity_functions: 0,
                    avg_complexity: 1.0,
                    complexity_score: 1.0,
                    function_names: vec![format!("function{}", i)],
                });
            }

            let report = crate::services::simple_deep_context::SimpleAnalysisReport {
                file_count: file_count as usize,
                analysis_duration: std::time::Duration::from_secs(1),
                complexity_metrics: crate::services::simple_deep_context::ComplexityMetrics {
                    total_functions,
                    high_complexity_count: 0,
                    avg_complexity: 1.0,
                },
                recommendations: vec![],
                file_complexity_details: file_details,
            };

            let output = green_phase_implementation::format_context_with_annotations(
                &report,
                std::path::Path::new("test"),
            );

            // Property: Output must mention the total function count
            let expected = format!("Functions: {}", total_functions);
            prop_assert!(output.contains(&expected));
        }

        #[test]
        fn property_all_files_appear_in_output(file_names in proptest::collection::vec("[a-zA-Z][a-zA-Z0-9]{0,10}", 1..10)) {
            let mut file_details = Vec::new();
            for name in &file_names {
                file_details.push(crate::services::simple_deep_context::FileComplexityDetail {
                    file_path: format!("{}.js", name).into(),
                    function_count: 1,
                    high_complexity_functions: 0,
                    avg_complexity: 1.0,
                    complexity_score: 1.0,
                    function_names: vec![format!("function_{}", name)],
                });
            }

            let report = crate::services::simple_deep_context::SimpleAnalysisReport {
                file_count: file_names.len(),
                analysis_duration: std::time::Duration::from_secs(1),
                complexity_metrics: crate::services::simple_deep_context::ComplexityMetrics {
                    total_functions: file_names.len(),
                    high_complexity_count: 0,
                    avg_complexity: 1.0,
                },
                recommendations: vec![],
                file_complexity_details: file_details,
            };

            let output = green_phase_implementation::format_context_with_annotations(
                &report,
                std::path::Path::new("test"),
            );

            // Property: All file names must appear in the output
            for name in &file_names {
                let expected = format!("{}.js", name);
                prop_assert!(output.contains(&expected));
            }
        }

        #[test]
        fn property_high_complexity_triggers_warning(high_complexity_count in 0u8..=10) {
            let has_high_complexity = high_complexity_count > 0;

            let report = crate::services::simple_deep_context::SimpleAnalysisReport {
                file_count: 1,
                analysis_duration: std::time::Duration::from_secs(1),
                complexity_metrics: crate::services::simple_deep_context::ComplexityMetrics {
                    total_functions: 10,
                    high_complexity_count: high_complexity_count as usize,
                    avg_complexity: if has_high_complexity { 15.0 } else { 3.0 },
                },
                recommendations: if has_high_complexity {
                    vec!["Refactor high complexity functions".to_string()]
                } else {
                    vec![]
                },
                file_complexity_details: vec![
                    crate::services::simple_deep_context::FileComplexityDetail {
                        file_path: "test.js".into(),
                        function_count: 10,
                        high_complexity_functions: high_complexity_count as usize,
                        avg_complexity: if has_high_complexity { 15.0 } else { 3.0 },
                        complexity_score: if has_high_complexity { 15.0 } else { 3.0 },
                        function_names: vec!["testFunction".to_string()],
                    },
                ],
            };

            let output = green_phase_implementation::format_context_with_annotations(
                &report,
                std::path::Path::new("test"),
            );

            // Property: High complexity must trigger warnings
            if has_high_complexity {
                prop_assert!(
                    output.contains("")
                        || output.contains("High Complexity")
                        || output.contains("high complexity"),
                );
            } else {
                prop_assert!(!output.contains(""));
            }
        }
    }
}