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
//! Uniform CLI commands that use the contracts system
//! These are the FUTURE commands that will replace the inconsistent ones

#![cfg_attr(coverage_nightly, coverage(off))]
use super::{
    AnalyzeComplexityContract, AnalyzeDeadCodeContract, AnalyzeLintHotspotContract,
    AnalyzeSatdContract, AnalyzeTdgContract, BaseAnalysisContract, OutputFormat, SatdSeverity,
};
use clap::{Parser, Subcommand, ValueEnum};
use std::path::PathBuf;

/// Uniform analyze commands with consistent parameters
#[derive(Subcommand)]
#[cfg_attr(test, derive(Debug))]
pub enum UniformAnalyzeCommands {
    /// Analyze code complexity using uniform contracts
    #[command(name = "complexity")]
    Complexity(UniformComplexityArgs),

    /// Analyze Self-Admitted Technical Debt using uniform contracts  
    #[command(name = "satd")]
    Satd(UniformSatdArgs),

    /// Analyze dead and unreachable code using uniform contracts
    #[command(name = "dead-code")]
    DeadCode(UniformDeadCodeArgs),

    /// Analyze Technical Debt Gradient using uniform contracts
    #[command(name = "tdg")]
    Tdg(UniformTdgArgs),

    /// Find lint hotspots using uniform contracts
    #[command(name = "lint-hotspot")]
    LintHotspot(UniformLintHotspotArgs),
}

/// Uniform complexity analysis arguments
#[derive(Parser)]
#[cfg_attr(test, derive(Debug))]
pub struct UniformComplexityArgs {
    /// Path to analyze (file or directory)
    #[arg(short = 'p', long, default_value = ".")]
    pub path: PathBuf,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: UniformOutputFormat,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Number of top files to show
    #[arg(long, default_value_t = 10)]
    pub top_files: usize,

    /// Include test files in analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Analysis timeout in seconds
    #[arg(long, default_value_t = 60)]
    pub timeout: u64,

    /// Maximum cyclomatic complexity threshold
    #[arg(long)]
    pub max_cyclomatic: Option<u32>,

    /// Maximum cognitive complexity threshold
    #[arg(long)]
    pub max_cognitive: Option<u32>,

    /// Maximum Halstead difficulty threshold
    #[arg(long)]
    pub max_halstead: Option<f64>,
}

/// Uniform SATD analysis arguments
#[derive(Parser)]
#[cfg_attr(test, derive(Debug))]
pub struct UniformSatdArgs {
    /// Path to analyze (file or directory)
    #[arg(short = 'p', long, default_value = ".")]
    pub path: PathBuf,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: UniformOutputFormat,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Number of top files to show
    #[arg(long, default_value_t = 10)]
    pub top_files: usize,

    /// Include test files in analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Analysis timeout in seconds
    #[arg(long, default_value_t = 60)]
    pub timeout: u64,

    /// Filter by severity level
    #[arg(long, value_enum)]
    pub severity: Option<UniformSatdSeverity>,

    /// Show only critical debt items
    #[arg(long)]
    pub critical_only: bool,

    /// Use strict mode (only TODO/FIXME/HACK/BUG)
    #[arg(long)]
    pub strict: bool,

    /// Exit with error if violations found
    #[arg(long)]
    pub fail_on_violation: bool,
}

/// Uniform dead code analysis arguments
#[derive(Parser)]
#[cfg_attr(test, derive(Debug))]
pub struct UniformDeadCodeArgs {
    /// Path to analyze (file or directory)
    #[arg(short = 'p', long, default_value = ".")]
    pub path: PathBuf,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: UniformOutputFormat,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Number of top files to show
    #[arg(long, default_value_t = 10)]
    pub top_files: usize,

    /// Include test files in analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Analysis timeout in seconds
    #[arg(long, default_value_t = 60)]
    pub timeout: u64,

    /// Include unreachable code blocks
    #[arg(long)]
    pub include_unreachable: bool,

    /// Minimum dead lines to report
    #[arg(long, default_value_t = 10)]
    pub min_dead_lines: usize,

    /// Maximum allowed dead code percentage
    #[arg(long, default_value_t = 15.0)]
    pub max_percentage: f64,

    /// Exit with error if violations found
    #[arg(long)]
    pub fail_on_violation: bool,
}

/// Uniform TDG analysis arguments
#[derive(Parser)]
#[cfg_attr(test, derive(Debug))]
pub struct UniformTdgArgs {
    /// Path to analyze (file or directory)
    #[arg(short = 'p', long, default_value = ".")]
    pub path: PathBuf,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: UniformOutputFormat,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Number of top files to show
    #[arg(long, default_value_t = 10)]
    pub top_files: usize,

    /// Include test files in analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Analysis timeout in seconds
    #[arg(long, default_value_t = 60)]
    pub timeout: u64,

    /// TDG threshold for filtering results
    #[arg(long, default_value_t = 1.5)]
    pub threshold: f64,

    /// Include TDG component breakdown
    #[arg(long)]
    pub include_components: bool,

    /// Show only critical files (TDG > 2.5)
    #[arg(long)]
    pub critical_only: bool,
}

/// Uniform lint hotspot analysis arguments
#[derive(Parser)]
#[cfg_attr(test, derive(Debug))]
pub struct UniformLintHotspotArgs {
    /// Path to analyze (file or directory)
    #[arg(short = 'p', long, default_value = ".")]
    pub path: PathBuf,

    /// Output format
    #[arg(long, value_enum, default_value = "table")]
    pub format: UniformOutputFormat,

    /// Output file path
    #[arg(short, long)]
    pub output: Option<PathBuf>,

    /// Number of top files to show
    #[arg(long, default_value_t = 10)]
    pub top_files: usize,

    /// Include test files in analysis
    #[arg(long)]
    pub include_tests: bool,

    /// Analysis timeout in seconds
    #[arg(long, default_value_t = 60)]
    pub timeout: u64,

    /// Specific file to analyze instead of finding hotspot
    #[arg(long)]
    pub file: Option<PathBuf>,

    /// Maximum allowed defect density
    #[arg(long, default_value_t = 5.0)]
    pub max_density: f64,

    /// Minimum confidence for automated fixes
    #[arg(long, default_value_t = 0.8)]
    pub min_confidence: f64,

    /// Enforce quality standards
    #[arg(long)]
    pub enforce: bool,

    /// Dry run mode - show what would be fixed
    #[arg(long)]
    pub dry_run: bool,
}

/// Uniform output format enum
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum UniformOutputFormat {
    Table,
    Json,
    Yaml,
    Markdown,
    Csv,
    Summary,
}

impl From<UniformOutputFormat> for OutputFormat {
    fn from(format: UniformOutputFormat) -> Self {
        match format {
            UniformOutputFormat::Table => OutputFormat::Table,
            UniformOutputFormat::Json => OutputFormat::Json,
            UniformOutputFormat::Yaml => OutputFormat::Yaml,
            UniformOutputFormat::Markdown => OutputFormat::Markdown,
            UniformOutputFormat::Csv => OutputFormat::Csv,
            UniformOutputFormat::Summary => OutputFormat::Summary,
        }
    }
}

/// Uniform SATD severity enum
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum UniformSatdSeverity {
    Low,
    Medium,
    High,
    Critical,
}

impl From<UniformSatdSeverity> for SatdSeverity {
    fn from(severity: UniformSatdSeverity) -> Self {
        match severity {
            UniformSatdSeverity::Low => SatdSeverity::Low,
            UniformSatdSeverity::Medium => SatdSeverity::Medium,
            UniformSatdSeverity::High => SatdSeverity::High,
            UniformSatdSeverity::Critical => SatdSeverity::Critical,
        }
    }
}

// Conversion implementations from uniform CLI args to contracts

impl From<UniformComplexityArgs> for AnalyzeComplexityContract {
    fn from(args: UniformComplexityArgs) -> Self {
        Self {
            base: BaseAnalysisContract {
                path: args.path,
                format: args.format.into(),
                output: args.output,
                top_files: Some(args.top_files),
                include_tests: args.include_tests,
                timeout: args.timeout,
            },
            max_cyclomatic: args.max_cyclomatic,
            max_cognitive: args.max_cognitive,
            max_halstead: args.max_halstead,
        }
    }
}

impl From<UniformSatdArgs> for AnalyzeSatdContract {
    fn from(args: UniformSatdArgs) -> Self {
        Self {
            base: BaseAnalysisContract {
                path: args.path,
                format: args.format.into(),
                output: args.output,
                top_files: Some(args.top_files),
                include_tests: args.include_tests,
                timeout: args.timeout,
            },
            severity: args.severity.map(std::convert::Into::into),
            critical_only: args.critical_only,
            strict: args.strict,
            fail_on_violation: args.fail_on_violation,
        }
    }
}

impl From<UniformDeadCodeArgs> for AnalyzeDeadCodeContract {
    fn from(args: UniformDeadCodeArgs) -> Self {
        Self {
            base: BaseAnalysisContract {
                path: args.path,
                format: args.format.into(),
                output: args.output,
                top_files: Some(args.top_files),
                include_tests: args.include_tests,
                timeout: args.timeout,
            },
            include_unreachable: args.include_unreachable,
            min_dead_lines: args.min_dead_lines,
            max_percentage: args.max_percentage,
            fail_on_violation: args.fail_on_violation,
        }
    }
}

impl From<UniformTdgArgs> for AnalyzeTdgContract {
    fn from(args: UniformTdgArgs) -> Self {
        Self {
            base: BaseAnalysisContract {
                path: args.path,
                format: args.format.into(),
                output: args.output,
                top_files: Some(args.top_files),
                include_tests: args.include_tests,
                timeout: args.timeout,
            },
            threshold: args.threshold,
            include_components: args.include_components,
            critical_only: args.critical_only,
        }
    }
}

impl From<UniformLintHotspotArgs> for AnalyzeLintHotspotContract {
    fn from(args: UniformLintHotspotArgs) -> Self {
        Self {
            base: BaseAnalysisContract {
                path: args.path,
                format: args.format.into(),
                output: args.output,
                top_files: Some(args.top_files),
                include_tests: args.include_tests,
                timeout: args.timeout,
            },
            file: args.file,
            max_density: args.max_density,
            min_confidence: args.min_confidence,
            enforce: args.enforce,
            dry_run: args.dry_run,
        }
    }
}

/// Handler for uniform commands using contracts
pub struct UniformCommandHandler {
    service: Arc<crate::contracts::service::ContractService>,
}

impl UniformCommandHandler {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> anyhow::Result<Self> {
        Ok(Self {
            service: Arc::new(crate::contracts::service::ContractService::new()?),
        })
    }

    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub async fn handle_analyze_command(&self, cmd: UniformAnalyzeCommands) -> anyhow::Result<()> {
        match cmd {
            UniformAnalyzeCommands::Complexity(args) => self.handle_complexity_analysis(args).await,
            UniformAnalyzeCommands::Satd(args) => self.handle_satd_analysis(args).await,
            UniformAnalyzeCommands::DeadCode(args) => self.handle_dead_code_analysis(args).await,
            UniformAnalyzeCommands::Tdg(args) => self.handle_tdg_analysis(args).await,
            UniformAnalyzeCommands::LintHotspot(args) => {
                self.handle_lint_hotspot_analysis(args).await
            }
        }
    }

    async fn handle_complexity_analysis(&self, args: UniformComplexityArgs) -> anyhow::Result<()> {
        let contract = AnalyzeComplexityContract::from(args);
        let result = self.service.analyze_complexity(contract).await?;
        self.output_result(result)
    }

    async fn handle_satd_analysis(&self, args: UniformSatdArgs) -> anyhow::Result<()> {
        let contract = AnalyzeSatdContract::from(args);
        let result = self.service.analyze_satd(contract).await?;
        self.output_result(result)
    }

    async fn handle_dead_code_analysis(&self, args: UniformDeadCodeArgs) -> anyhow::Result<()> {
        let contract = AnalyzeDeadCodeContract::from(args);
        let result = self.service.analyze_dead_code(contract).await?;
        self.output_result(result)
    }

    async fn handle_tdg_analysis(&self, args: UniformTdgArgs) -> anyhow::Result<()> {
        let contract = AnalyzeTdgContract::from(args);
        let result = self.service.analyze_tdg(contract).await?;
        self.output_result(result)
    }

    async fn handle_lint_hotspot_analysis(
        &self,
        args: UniformLintHotspotArgs,
    ) -> anyhow::Result<()> {
        let contract = AnalyzeLintHotspotContract::from(args);
        let result = self.service.analyze_lint_hotspot(contract).await?;
        self.output_result(result)
    }

    fn output_result(&self, result: serde_json::Value) -> anyhow::Result<()> {
        match result {
            serde_json::Value::String(s) => println!("{s}"),
            other => println!("{}", serde_json::to_string_pretty(&other)?),
        }
        Ok(())
    }
}

use std::sync::Arc;

// Tests extracted to uniform_cli_commands_tests.rs for file health (CB-040).
include!("uniform_cli_commands_tests.rs");