pmat 2.93.1

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
//! Unified contract definitions for ALL interfaces (CLI, MCP, HTTP)
//!
//! CRITICAL: This is the SINGLE SOURCE OF TRUTH for all command parameters.
//! Every interface MUST use these exact contracts with no variations.

pub mod adapter;
pub mod cli_impl;
pub mod cli_mapping;
pub mod http_impl;
// pub mod mcp_impl; // Disabled due to pmcp dependency issues
pub mod mcp_mapping;
pub mod mcp_simple;
pub mod real_service;
pub mod service;
pub mod simple_service;
#[cfg(test)]
mod tests;
pub mod uniform_cli_commands;
pub mod versioning;

use crate::utils::path_validator::PathValidator;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use thiserror::Error;

#[derive(Debug, Error)]
pub enum ContractError {
    #[error("Path not found: {0}")]
    PathNotFound(PathBuf),

    #[error("Missing required parameter: {0}")]
    MissingParam(&'static str),

    #[error("Invalid timeout value")]
    InvalidTimeout,

    #[error("Too many files requested: {0} (max: 1000)")]
    TooManyFiles(usize),

    #[error("Invalid parameter value: {0}")]
    InvalidValue(String),
}

/// Output formats supported by ALL commands
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum OutputFormat {
    #[default]
    Table,
    Json,
    Yaml,
    Markdown,
    Csv,
    Summary,
}

/// SATD severity levels
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, PartialOrd)]
#[serde(rename_all = "lowercase")]
pub enum SatdSeverity {
    Low,
    Medium,
    High,
    Critical,
}

/// Base parameters shared by ALL analysis commands
/// This ensures consistency across all interfaces
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BaseAnalysisContract {
    /// Path to analyze - ALWAYS named 'path', never '`project_path`' or 'file'
    pub path: PathBuf,

    /// Output format - ALWAYS available, ALWAYS same enum
    pub format: OutputFormat,

    /// Output file path - ALWAYS optional
    pub output: Option<PathBuf>,

    /// Number of top files to show - ALWAYS same name, ALWAYS optional
    pub top_files: Option<usize>,

    /// Include test files - ALWAYS same behavior
    pub include_tests: bool,

    /// Analysis timeout in seconds - ALWAYS available
    pub timeout: u64,
}

impl Default for BaseAnalysisContract {
    fn default() -> Self {
        Self {
            path: PathBuf::from("."),
            format: OutputFormat::default(),
            output: None,
            top_files: Some(10),
            include_tests: false,
            timeout: 60,
        }
    }
}

/// Contract for analyze complexity command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeComplexityContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Maximum cyclomatic complexity threshold
    pub max_cyclomatic: Option<u32>,

    /// Maximum cognitive complexity threshold  
    pub max_cognitive: Option<u32>,

    /// Maximum Halstead difficulty threshold
    pub max_halstead: Option<f64>,
}

/// Contract for analyze SATD command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeSatdContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Filter by severity level
    pub severity: Option<SatdSeverity>,

    /// Show only critical debt items
    pub critical_only: bool,

    /// Use strict mode (only TODO/FIXME/HACK/BUG)
    pub strict: bool,

    /// Exit with error if violations found
    pub fail_on_violation: bool,
}

/// Contract for analyze dead code command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeDeadCodeContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Include unreachable code blocks
    pub include_unreachable: bool,

    /// Minimum dead lines to report a file
    pub min_dead_lines: usize,

    /// Maximum allowed dead code percentage
    pub max_percentage: f64,

    /// Exit with error if violations found
    pub fail_on_violation: bool,
}

/// Contract for analyze TDG command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeTdgContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// TDG threshold for filtering results
    pub threshold: f64,

    /// Include TDG component breakdown
    pub include_components: bool,

    /// Show only critical files (TDG > 2.5)
    pub critical_only: bool,
}

/// Contract for analyze lint hotspot command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeLintHotspotContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Analyze a specific file instead of finding hotspot
    pub file: Option<PathBuf>,

    /// Maximum allowed defect density
    pub max_density: f64,

    /// Minimum confidence for automated fixes
    pub min_confidence: f64,

    /// Enforce quality standards
    pub enforce: bool,

    /// Dry run - show what would be fixed
    pub dry_run: bool,
}

/// Contract for analyze entropy command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AnalyzeEntropyContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Minimum severity level to report
    pub min_severity: Option<String>,

    /// Maximum number of violations to show (0 = all)
    pub top_violations: Option<usize>,

    /// Specific file to analyze instead of project
    pub file: Option<PathBuf>,
}

/// Contract for quality gate command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct QualityGateContract {
    /// Base parameters (inherited)
    #[serde(flatten)]
    pub base: BaseAnalysisContract,

    /// Quality profile to use
    pub profile: QualityProfile,

    /// Specific file to check (optional)
    pub file: Option<PathBuf>,

    /// Exit with error if violations found
    pub fail_on_violation: bool,

    /// Show verbose output
    pub verbose: bool,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum QualityProfile {
    #[default]
    Standard,
    Strict,
    Extreme,
    Toyota,
}

/// Contract for refactor auto command
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RefactorAutoContract {
    /// File to refactor - MUST be a file, not directory
    pub file: PathBuf,

    /// Output format
    pub format: OutputFormat,

    /// Output file path
    pub output: Option<PathBuf>,

    /// Target complexity
    pub target_complexity: u32,

    /// Dry run mode
    pub dry_run: bool,

    /// Analysis timeout
    pub timeout: u64,
}

/// Trait for contract validation
pub trait ContractValidation {
    fn validate(&self) -> Result<(), ContractError>;
}

impl ContractValidation for BaseAnalysisContract {
    fn validate(&self) -> Result<(), ContractError> {
        PathValidator::ensure_exists(&self.path)
            .map_err(|_| ContractError::PathNotFound(self.path.clone()))?;

        if self.timeout == 0 {
            return Err(ContractError::InvalidTimeout);
        }

        if let Some(top_files) = self.top_files {
            if top_files > 1000 {
                return Err(ContractError::TooManyFiles(top_files));
            }
        }

        Ok(())
    }
}

impl ContractValidation for AnalyzeComplexityContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        if let Some(max_halstead) = self.max_halstead {
            if max_halstead <= 0.0 {
                return Err(ContractError::InvalidValue(
                    "max_halstead must be positive".into(),
                ));
            }
        }

        Ok(())
    }
}

impl ContractValidation for AnalyzeSatdContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()
    }
}

impl ContractValidation for AnalyzeDeadCodeContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        if self.max_percentage < 0.0 || self.max_percentage > 100.0 {
            return Err(ContractError::InvalidValue(
                "max_percentage must be 0-100".into(),
            ));
        }

        Ok(())
    }
}

impl ContractValidation for AnalyzeTdgContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        if self.threshold < 0.0 {
            return Err(ContractError::InvalidValue(
                "threshold must be non-negative".into(),
            ));
        }

        Ok(())
    }
}

impl ContractValidation for AnalyzeLintHotspotContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        if self.max_density < 0.0 {
            return Err(ContractError::InvalidValue(
                "max_density must be non-negative".into(),
            ));
        }

        if self.min_confidence < 0.0 || self.min_confidence > 1.0 {
            return Err(ContractError::InvalidValue(
                "min_confidence must be 0-1".into(),
            ));
        }

        Ok(())
    }
}

impl ContractValidation for AnalyzeEntropyContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        // Validate severity level if provided
        if let Some(severity) = &self.min_severity {
            match severity.as_str() {
                "low" | "medium" | "high" => {}
                _ => {
                    return Err(ContractError::InvalidValue(
                        "min_severity must be 'low', 'medium', or 'high'".into(),
                    ))
                }
            }
        }

        // Validate top_violations if provided
        if let Some(violations) = self.top_violations {
            if violations > 1000 {
                return Err(ContractError::TooManyFiles(violations));
            }
        }

        // Validate file path if provided
        if let Some(file) = &self.file {
            PathValidator::ensure_exists(file)
                .map_err(|_| ContractError::PathNotFound(file.clone()))?;
        }

        Ok(())
    }
}

impl ContractValidation for QualityGateContract {
    fn validate(&self) -> Result<(), ContractError> {
        self.base.validate()?;

        if let Some(file) = &self.file {
            PathValidator::ensure_exists(file)
                .map_err(|_| ContractError::PathNotFound(file.clone()))?;
        }

        Ok(())
    }
}

impl ContractValidation for RefactorAutoContract {
    fn validate(&self) -> Result<(), ContractError> {
        PathValidator::ensure_file(&self.file)
            .map_err(|_| ContractError::PathNotFound(self.file.clone()))?;

        if self.timeout == 0 {
            return Err(ContractError::InvalidTimeout);
        }

        if self.target_complexity == 0 {
            return Err(ContractError::InvalidValue(
                "target_complexity must be > 0".into(),
            ));
        }

        Ok(())
    }
}

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