pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
Documentation
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
619
620
//! Advanced analysis route handlers
//!
//! Handles: DeepContext, Tdg, BuildTdg, LintHotspot, Comprehensive,
//! Duplicates, DefectPrediction, Provability, Clippy

use crate::cli::{self, AnalyzeCommands};
use anyhow::Result;
use std::path::Path;

/// Route deep context analysis command
pub(super) async fn route_deep_context_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::DeepContext {
        path,
        project_path,
        output,
        format,
        full,
        include,
        exclude,
        period_days,
        dag_type,
        max_depth,
        include_patterns,
        exclude_patterns,
        cache_strategy,
        parallel,
        verbose,
        top_files,
    } = cmd
    {
        let path = project_path.unwrap_or(path);
        // `Option` all the way through: the handler refuses both flags, and a
        // refusal must fire only when the USER passed one. They used to carry
        // clap defaults, so the handler could not distinguish that from a
        // default and dropped them silently instead.
        let converted_dag_type = dag_type.map(convert_deep_context_dag_type);
        let converted_cache_strategy = cache_strategy.map(convert_cache_strategy);

        crate::cli::handlers::advanced_analysis_handlers::handle_analyze_deep_context(
            path,
            output,
            format,
            full,
            include,
            exclude,
            period_days,
            converted_dag_type,
            max_depth,
            include_patterns,
            exclude_patterns,
            converted_cache_strategy,
            parallel.is_some(),
            verbose,
            top_files,
        )
        .await
    } else {
        unreachable!("Expected DeepContext command")
    }
}

/// Convert deep context DAG type to standard DAG type
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub(crate) fn convert_deep_context_dag_type(dag_type: cli::DeepContextDagType) -> cli::DagType {
    match dag_type {
        cli::DeepContextDagType::CallGraph => cli::DagType::CallGraph,
        cli::DeepContextDagType::ImportGraph => cli::DagType::ImportGraph,
        cli::DeepContextDagType::Inheritance => cli::DagType::Inheritance,
        cli::DeepContextDagType::FullDependency => cli::DagType::FullDependency,
    }
}

/// Convert cache strategy to string
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub(crate) fn convert_cache_strategy(strategy: cli::DeepContextCacheStrategy) -> String {
    match strategy {
        cli::DeepContextCacheStrategy::Normal => "normal".to_string(),
        cli::DeepContextCacheStrategy::ForceRefresh => "force-refresh".to_string(),
        cli::DeepContextCacheStrategy::Offline => "offline".to_string(),
    }
}
/// Route TDG analysis command
pub(super) async fn route_tdg_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::Tdg {
        path,
        threshold,
        top_files,
        format,
        include_components,
        output,
        critical_only,
        verbose,
        ml,
    } = cmd
    {
        // GH-97, same defect and same refusal as `analyze complexity --ml`:
        // `ml: _` threw the flag away and `TdgAnalysisConfig` was built without
        // it, so `analyze tdg --ml` printed the heuristic weighted-sum scores
        // while --help promised "trained ML models instead of heuristic
        // weighted sums". Refuse rather than relabel.
        super::reject_unimplemented_ml(ml, "analyze tdg", "TDG scores")?;

        use crate::cli::handlers::new_tdg_handler::TdgAnalysisConfig;

        let config = TdgAnalysisConfig {
            path,
            threshold: Some(threshold),
            top_files: Some(top_files),
            format,
            include_components,
            output,
            critical_only,
            verbose,
        };

        crate::cli::handlers::new_tdg_handler::handle_analyze_tdg(config).await
    } else {
        unreachable!("Expected Tdg command")
    }
}

/// Run cargo build step for build-tdg command
fn run_cargo_build(path: &Path, release: bool) -> Result<()> {
    use std::process::Command;
    println!("\u{1f4e6} Building project...");
    let mut build_cmd = Command::new("cargo");
    build_cmd.arg("build");
    if release {
        build_cmd.arg("--release");
    }
    build_cmd.current_dir(path);
    let status = build_cmd.status()?;
    if !status.success() {
        anyhow::bail!("Build failed with exit code: {:?}", status.code());
    }
    println!("\u{2705} Build successful\n");
    Ok(())
}

/// Check for quality regressions against baseline
fn check_quality_regression(path: &Path) -> Result<()> {
    let baseline_path = path.join(".pmat/baseline.json");
    if !baseline_path.exists() {
        println!(
            "\u{26a0}\u{fe0f}  No baseline found at {}, skipping regression check",
            baseline_path.display()
        );
        println!("   Run 'pmat tdg baseline create' to create a baseline");
        return Ok(());
    }
    println!("\u{1f50d} Checking for quality regressions...");
    let status = std::process::Command::new("pmat")
        .args([
            "tdg",
            "check-regression",
            "--baseline",
            baseline_path.to_str().unwrap_or(".pmat/baseline.json"),
            "--path",
            path.to_str().unwrap_or("."),
            "--fail-on-regression",
        ])
        .status();
    match status {
        Ok(s) if s.success() => println!("\u{2705} No regressions detected"),
        Ok(_) => anyhow::bail!("Quality regression detected"),
        Err(e) => println!("\u{26a0}\u{fe0f}  Could not run regression check: {}", e),
    }
    Ok(())
}

/// Route build-tdg analysis command (build + TDG quality gate)
pub(super) async fn route_build_tdg_analysis(cmd: AnalyzeCommands) -> Result<()> {
    let AnalyzeCommands::BuildTdg {
        path,
        release,
        threshold,
        fail_on_regression,
        tdg_only,
        top_files,
        format,
        output,
    } = cmd
    else {
        unreachable!("Expected BuildTdg command")
    };

    use crate::cli::handlers::new_tdg_handler::TdgAnalysisConfig;

    if !tdg_only {
        run_cargo_build(&path, release)?;
    }

    // This banner was the one progress line on stdout (every sibling line in
    // new_tdg_handler uses eprintln!), so it landed ahead of the JSON/SARIF
    // document and `analyze build-tdg -f json | jq` failed to parse for
    // everyone. Progress belongs on stderr; stdout carries the document only.
    eprintln!("\u{1f4ca} Running TDG analysis...");
    let config = TdgAnalysisConfig {
        path: path.clone(),
        threshold: Some(threshold),
        top_files: Some(top_files),
        format,
        include_components: false,
        output,
        critical_only: false,
        verbose: false,
    };

    // `build-tdg` is the gated entry point: its --threshold used to be
    // discarded, so the documented "fails fast if TDG score exceeds threshold"
    // gate exited 0 for every threshold from 0.0 to 1000.
    let result = crate::cli::handlers::new_tdg_handler::handle_analyze_tdg_gated(config).await;

    if fail_on_regression {
        check_quality_regression(&path)?;
    }

    result
}

/// Route lint hotspot analysis command
pub(super) async fn route_lint_hotspot_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::LintHotspot {
        path,
        project_path,
        file,
        format,
        max_density,
        min_confidence,
        enforce,
        dry_run,
        enforcement_metadata,
        output,
        perf,
        clippy_flags,
        top_files,
        include,
        exclude,
    } = cmd
    {
        let path = project_path.unwrap_or(path);
        crate::cli::handlers::lint_hotspot_handlers::handle_analyze_lint_hotspot(
            path,
            file,
            format,
            max_density,
            min_confidence,
            enforce,
            dry_run,
            enforcement_metadata,
            output,
            perf,
            clippy_flags,
            top_files,
            include,
            exclude,
        )
        .await
    } else {
        unreachable!("Expected LintHotspot command")
    }
}

/// Route comprehensive analysis command
pub(super) async fn route_comprehensive_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::Comprehensive {
        path,
        project_path,
        file,
        files,
        format,
        include_duplicates,
        include_dead_code,
        include_defects,
        include_complexity,
        include_tdg,
        confidence_threshold,
        min_lines,
        include,
        exclude,
        output,
        perf,
        executive_summary,
        top_files,
    } = cmd
    {
        let path = project_path.unwrap_or(path);
        // `top_files: _` here plus a hardcoded `top_files: 20` in the wrapper
        // below made `--top-files` unobservable twice over: the flag was
        // dropped at the route, and the value the config carried was a literal.
        crate::cli::handlers::advanced_analysis_handlers::handle_analyze_comprehensive(
            path,
            file,
            files,
            format,
            include_duplicates,
            include_dead_code,
            include_defects,
            include_complexity,
            include_tdg,
            confidence_threshold,
            min_lines,
            include,
            exclude,
            output,
            perf,
            executive_summary,
            top_files,
        )
        .await
    } else {
        unreachable!("Expected Comprehensive command")
    }
}

/// Route duplicates analysis command
pub(super) async fn route_duplicates_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::Duplicates {
        path,
        project_path,
        detection_type,
        threshold,
        min_lines,
        max_tokens,
        format,
        perf,
        include,
        exclude,
        output,
        top_files,
    } = cmd
    {
        let path = project_path.unwrap_or(path);
        let config = crate::cli::handlers::duplication_analysis::DuplicateAnalysisConfig {
            project_path: path,
            detection_type,
            threshold: f64::from(threshold),
            min_lines,
            max_tokens,
            format,
            perf,
            include,
            exclude,
            output,
            top_files,
        };
        crate::cli::handlers::duplication_analysis::handle_analyze_duplicates(config).await
    } else {
        unreachable!("Expected Duplicates command")
    }
}

/// Route defect prediction analysis command
pub(super) async fn route_defect_prediction_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::DefectPrediction {
        path,
        project_path,
        confidence_threshold,
        min_lines,
        include_low_confidence,
        format,
        high_risk_only,
        include_recommendations,
        include,
        exclude,
        output,
        perf,
        top_files,
    } = cmd
    {
        use crate::cli::handlers::defect_prediction_handler::DefectPredictionConfig;

        let path = project_path.unwrap_or(path);
        let config = DefectPredictionConfig {
            project_path: path,
            confidence_threshold,
            min_lines,
            include_low_confidence,
            format,
            high_risk_only,
            include_recommendations,
            include,
            exclude,
            output,
            perf,
            top_files,
        };

        crate::cli::handlers::defect_prediction_handler::handle_analyze_defect_prediction(config)
            .await
    } else {
        unreachable!("Expected DefectPrediction command")
    }
}

/// Route provability analysis command
pub(super) async fn route_provability_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::Provability {
        path,
        project_path,
        functions,
        analysis_depth,
        format,
        high_confidence_only,
        include_evidence,
        output,
        top_files,
    } = cmd
    {
        use crate::cli::handlers::provability_handler::ProvabilityConfig;

        // A KNOB WIRED TO NOTHING IS WORSE THAN NO KNOB. `--analysis-depth`
        // documented "number of iterations"; the analyzer runs no iteration
        // (`AbstractInterpreter::analyze_iteration` has no caller) and its depth
        // is the fixed `ANALYSIS_DEPTH`. Every value from 0 to 1000 produced the
        // same report. Refuse rather than accept and ignore (#920).
        if analysis_depth.is_some() {
            anyhow::bail!(
                "--analysis-depth is not implemented: provability scores each function once \
                 from its source, with no iteration to bound, so every value produced the same \
                 report. Re-run `analyze provability` without --analysis-depth."
            );
        }

        let path = project_path.unwrap_or(path);
        let config = ProvabilityConfig {
            project_path: path,
            functions,
            analysis_depth: crate::services::lightweight_provability_analyzer::ANALYSIS_DEPTH,
            format,
            high_confidence_only,
            include_evidence,
            output,
            top_files,
        };

        crate::cli::handlers::provability_handler::handle_analyze_provability(config).await
    } else {
        unreachable!("Expected Provability command")
    }
}

/// Route clippy analysis command (complexity: 4)
pub(super) async fn route_clippy_analysis(cmd: AnalyzeCommands) -> Result<()> {
    if let AnalyzeCommands::Clippy {
        path,
        project_path,
        confidence,
        dry_run,
        fix_codes,
        output,
        perf: _perf,
    } = cmd
    {
        let path = project_path.unwrap_or(path);
        // Call the auto_clippy_fix MCP tool function directly
        use crate::mcp_pmcp::tools::auto_clippy_fix::auto_clippy_fix;

        let confidence_level = Some(confidence.clone());
        let codes = if fix_codes.is_empty() {
            None
        } else {
            Some(fix_codes.clone())
        };

        let result = auto_clippy_fix(
            Some(path.to_string_lossy().to_string()),
            confidence_level,
            Some(dry_run),
            codes,
        )
        .await?;

        let report = clippy_result_payload(&result);

        if let Some(output_path) = output {
            use std::fs;
            fs::write(&output_path, &report)?;
            eprintln!("\u{1f4c1} Results written to {}", output_path.display());
        } else {
            println!("{report}");
        }

        if result.is_error {
            anyhow::bail!("Clippy analysis failed");
        }

        Ok(())
    } else {
        unreachable!("Expected Clippy command")
    }
}

/// The JSON payload an MCP tool result carries, as a CLI report.
///
/// `analyze clippy` used to `eprintln!("{result:?}")` — the Debug rendering of
/// the MCP transport envelope — so stdout was empty and the only output was an
/// unparseable `CallToolResult { content: [Text { text: "{\n \"action\"…" }],
/// is_error: false, … }` on stderr. The envelope is an implementation detail of
/// the MCP server; a CLI prints the payload, on stdout, so it can be piped.
fn clippy_result_payload(result: &pmcp::ToolResult) -> String {
    let texts: Vec<&str> = result
        .content
        .iter()
        .filter_map(|c| match c {
            pmcp::Content::Text { text } => Some(text.as_str()),
            _ => None,
        })
        .collect();

    if texts.is_empty() {
        // Never invent a report: say the tool returned no text payload.
        return serde_json::json!({
            "error": "clippy analysis returned no text content",
            "is_error": result.is_error,
        })
        .to_string();
    }

    texts.join("\n")
}

#[cfg(test)]
mod converter_tests {
    //! Wave 39 PR4 — pure-helper tests for advanced_routes.rs.
    //! The async route_* functions remain untested (heavy I/O / handler chains).
    use super::*;

    // ── convert_deep_context_dag_type ───────────────────────────────────────

    #[test]
    fn test_convert_dag_type_call_graph() {
        assert!(matches!(
            convert_deep_context_dag_type(cli::DeepContextDagType::CallGraph),
            cli::DagType::CallGraph
        ));
    }

    #[test]
    fn test_convert_dag_type_import_graph() {
        assert!(matches!(
            convert_deep_context_dag_type(cli::DeepContextDagType::ImportGraph),
            cli::DagType::ImportGraph
        ));
    }

    #[test]
    fn test_convert_dag_type_inheritance() {
        assert!(matches!(
            convert_deep_context_dag_type(cli::DeepContextDagType::Inheritance),
            cli::DagType::Inheritance
        ));
    }

    #[test]
    fn test_convert_dag_type_full_dependency() {
        assert!(matches!(
            convert_deep_context_dag_type(cli::DeepContextDagType::FullDependency),
            cli::DagType::FullDependency
        ));
    }

    // ── convert_cache_strategy ──────────────────────────────────────────────

    #[test]
    fn test_convert_cache_strategy_normal() {
        assert_eq!(
            convert_cache_strategy(cli::DeepContextCacheStrategy::Normal),
            "normal"
        );
    }

    #[test]
    fn test_convert_cache_strategy_force_refresh() {
        // PIN: hyphenated kebab-case ("force-refresh") not snake_case.
        assert_eq!(
            convert_cache_strategy(cli::DeepContextCacheStrategy::ForceRefresh),
            "force-refresh"
        );
    }

    #[test]
    fn test_convert_cache_strategy_offline() {
        assert_eq!(
            convert_cache_strategy(cli::DeepContextCacheStrategy::Offline),
            "offline"
        );
    }

    // ── clippy_result_payload ───────────────────────────────────────────────

    #[test]
    fn clippy_report_is_the_payload_not_the_mcp_envelope() {
        let payload = "{\n  \"action\": \"analyzed\",\n  \"results\": {}\n}";
        let result = pmcp::ToolResult::new(vec![pmcp::Content::Text {
            text: payload.to_string(),
        }]);

        let report = clippy_result_payload(&result);

        assert_eq!(report, payload);
        assert!(
            serde_json::from_str::<serde_json::Value>(&report).is_ok(),
            "the CLI report must be parseable JSON"
        );
        // What the command used to print: the Debug rendering of the transport
        // envelope, which no consumer can parse.
        assert!(
            serde_json::from_str::<serde_json::Value>(&format!("{result:?}")).is_err(),
            "the MCP envelope Debug rendering is not a report"
        );
    }

    #[test]
    fn clippy_report_says_so_when_there_is_no_text_payload() {
        let result = pmcp::ToolResult::new(vec![]);
        let report = clippy_result_payload(&result);
        assert!(report.contains("no text content"), "got: {report}");
    }
}