pmat 3.11.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
#![cfg_attr(coverage_nightly, coverage(off))]
//! Contract versioning support for backward compatibility and evolution
//! This ensures contracts can evolve while maintaining compatibility

use super::{AnalyzeComplexityContract, AnalyzeSatdContract, BaseAnalysisContract, ContractError};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Contract version information
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ContractVersion {
    pub major: u32,
    pub minor: u32,
    pub patch: u32,
}

impl ContractVersion {
    #[must_use]
    pub fn new(major: u32, minor: u32, patch: u32) -> Self {
        Self {
            major,
            minor,
            patch,
        }
    }

    #[must_use]
    pub fn current() -> Self {
        Self::new(1, 0, 0) // Current contract version
    }

    #[must_use]
    pub fn is_compatible(&self, other: &Self) -> bool {
        // Same major version = compatible
        // Higher minor version = backward compatible
        self.major == other.major && self.minor >= other.minor
    }

    #[must_use]
    pub fn requires_migration(&self, other: &Self) -> bool {
        self.major != other.major
    }
}

impl std::fmt::Display for ContractVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// Versioned contract wrapper
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct VersionedContract<T> {
    pub version: ContractVersion,
    pub contract: T,
    pub metadata: ContractMetadata,
}

/// Contract metadata for versioning and tracking
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ContractMetadata {
    pub created_at: u64,
    pub created_by: String,
    pub description: Option<String>,
    pub deprecated: bool,
    pub migration_notes: Option<String>,
}

impl ContractMetadata {
    #[must_use]
    pub fn new(created_by: &str) -> Self {
        Self {
            created_at: std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap_or_else(|_| std::time::Duration::from_secs(0))
                .as_secs(),
            created_by: created_by.to_string(),
            description: None,
            deprecated: false,
            migration_notes: None,
        }
    }

    #[must_use]
    pub fn with_description(mut self, description: &str) -> Self {
        self.description = Some(description.to_string());
        self
    }

    #[must_use]
    pub fn deprecated(mut self, migration_notes: &str) -> Self {
        self.deprecated = true;
        self.migration_notes = Some(migration_notes.to_string());
        self
    }
}

/// Contract registry for managing versions
pub struct ContractRegistry {
    contracts: HashMap<String, Vec<VersionedContract<serde_json::Value>>>,
    migrations: HashMap<(ContractVersion, ContractVersion), Box<dyn ContractMigration>>,
}

impl Default for ContractRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl ContractRegistry {
    #[must_use]
    pub fn new() -> Self {
        Self {
            contracts: HashMap::new(),
            migrations: HashMap::new(),
        }
    }

    /// Register a contract version
    pub fn register<T>(
        &mut self,
        name: &str,
        contract: VersionedContract<T>,
    ) -> Result<(), ContractError>
    where
        T: Serialize,
    {
        let json_contract = VersionedContract {
            version: contract.version,
            contract: serde_json::to_value(contract.contract)
                .map_err(|e| ContractError::InvalidValue(e.to_string()))?,
            metadata: contract.metadata,
        };

        self.contracts
            .entry(name.to_string())
            .or_default()
            .push(json_contract);

        Ok(())
    }

    /// Get the latest version of a contract
    #[must_use]
    pub fn get_latest(&self, name: &str) -> Option<&VersionedContract<serde_json::Value>> {
        self.contracts
            .get(name)?
            .iter()
            .max_by_key(|c| (&c.version.major, &c.version.minor, &c.version.patch))
    }

    /// Get a specific version of a contract
    #[must_use]
    pub fn get_version(
        &self,
        name: &str,
        version: &ContractVersion,
    ) -> Option<&VersionedContract<serde_json::Value>> {
        self.contracts
            .get(name)?
            .iter()
            .find(|c| &c.version == version)
    }

    /// Get all versions of a contract
    #[must_use]
    pub fn get_all_versions(
        &self,
        name: &str,
    ) -> Option<&Vec<VersionedContract<serde_json::Value>>> {
        self.contracts.get(name)
    }

    /// Register a migration between versions
    pub fn register_migration(
        &mut self,
        from: ContractVersion,
        to: ContractVersion,
        migration: Box<dyn ContractMigration>,
    ) {
        self.migrations.insert((from, to), migration);
    }

    /// Migrate contract from one version to another
    pub fn migrate(
        &self,
        name: &str,
        from_version: &ContractVersion,
        to_version: &ContractVersion,
        contract: serde_json::Value,
    ) -> Result<serde_json::Value, ContractError> {
        if let Some(migration) = self
            .migrations
            .get(&(from_version.clone(), to_version.clone()))
        {
            migration.migrate(contract)
        } else {
            Err(ContractError::InvalidValue(format!(
                "No migration available from {from_version} to {to_version} for contract {name}"
            )))
        }
    }

    /// Check if a contract version is deprecated
    #[must_use]
    pub fn is_deprecated(&self, name: &str, version: &ContractVersion) -> bool {
        if let Some(contract) = self.get_version(name, version) {
            contract.metadata.deprecated
        } else {
            false
        }
    }

    /// Get deprecation info for a contract version
    #[must_use]
    pub fn get_deprecation_info(&self, name: &str, version: &ContractVersion) -> Option<String> {
        if let Some(contract) = self.get_version(name, version) {
            if contract.metadata.deprecated {
                contract.metadata.migration_notes.clone()
            } else {
                None
            }
        } else {
            None
        }
    }
}

/// Trait for contract migrations
pub trait ContractMigration: Send + Sync {
    fn migrate(&self, contract: serde_json::Value) -> Result<serde_json::Value, ContractError>;
}

/// Standard contract migration implementations
pub struct ParameterRenameMigration {
    pub old_name: String,
    pub new_name: String,
}

impl ContractMigration for ParameterRenameMapping {
    fn migrate(&self, mut contract: serde_json::Value) -> Result<serde_json::Value, ContractError> {
        if let Some(obj) = contract.as_object_mut() {
            for (old, new) in &self.mappings {
                if let Some(value) = obj.remove(old) {
                    obj.insert(new.clone(), value);
                }
            }
        }
        Ok(contract)
    }
}

pub struct ParameterRenameMapping {
    pub mappings: HashMap<String, String>,
}

impl Default for ParameterRenameMapping {
    fn default() -> Self {
        Self::new()
    }
}

impl ParameterRenameMapping {
    #[must_use]
    pub fn new() -> Self {
        Self {
            mappings: HashMap::new(),
        }
    }

    #[must_use]
    pub fn add_mapping(mut self, old_name: &str, new_name: &str) -> Self {
        self.mappings
            .insert(old_name.to_string(), new_name.to_string());
        self
    }

    /// Standard migration for `project_path` -> path
    #[must_use]
    pub fn project_path_to_path() -> Self {
        Self::new().add_mapping("project_path", "path")
    }

    /// Standard migration for file -> files array
    #[must_use]
    pub fn file_to_files() -> Box<dyn ContractMigration> {
        Box::new(FileToFilesMigration)
    }
}

pub struct FileToFilesMigration;

impl ContractMigration for FileToFilesMigration {
    fn migrate(&self, mut contract: serde_json::Value) -> Result<serde_json::Value, ContractError> {
        if let Some(obj) = contract.as_object_mut() {
            // Convert single 'file' to 'files' array
            if let Some(file) = obj.remove("file") {
                if !obj.contains_key("files") {
                    obj.insert("files".to_string(), serde_json::json!([file]));
                }
            }
        }
        Ok(contract)
    }
}

/// Helper to create versioned contracts
pub struct ContractBuilder<T> {
    version: ContractVersion,
    contract: T,
    metadata: ContractMetadata,
}

impl<T> ContractBuilder<T> {
    pub fn new(contract: T, created_by: &str) -> Self {
        Self {
            version: ContractVersion::current(),
            contract,
            metadata: ContractMetadata::new(created_by),
        }
    }

    pub fn version(mut self, major: u32, minor: u32, patch: u32) -> Self {
        self.version = ContractVersion::new(major, minor, patch);
        self
    }

    pub fn description(mut self, description: &str) -> Self {
        self.metadata = self.metadata.with_description(description);
        self
    }

    pub fn deprecated(mut self, migration_notes: &str) -> Self {
        self.metadata = self.metadata.deprecated(migration_notes);
        self
    }

    pub fn build(self) -> VersionedContract<T> {
        VersionedContract {
            version: self.version,
            contract: self.contract,
            metadata: self.metadata,
        }
    }
}

/// Initialize the global contract registry with current contracts
pub fn initialize_registry() -> Result<ContractRegistry, ContractError> {
    let mut registry = ContractRegistry::new();

    // Register current contract versions
    let complexity_contract = ContractBuilder::new(
        AnalyzeComplexityContract {
            base: BaseAnalysisContract::default(),
            max_cyclomatic: None,
            max_cognitive: None,
            max_halstead: None,
        },
        "pmat-system",
    )
    .description("Analyze code complexity with uniform parameters")
    .build();

    registry
        .register("analyze_complexity", complexity_contract)
        .map_err(|e| ContractError::InvalidValue(e.to_string()))?;

    let satd_contract = ContractBuilder::new(
        AnalyzeSatdContract {
            base: BaseAnalysisContract::default(),
            severity: None,
            critical_only: false,
            strict: false,
            fail_on_violation: false,
        },
        "pmat-system",
    )
    .description("Analyze Self-Admitted Technical Debt")
    .build();

    registry
        .register("analyze_satd", satd_contract)
        .map_err(|e| ContractError::InvalidValue(e.to_string()))?;

    // Register migrations for backward compatibility
    registry.register_migration(
        ContractVersion::new(0, 1, 0), // Old version
        ContractVersion::new(1, 0, 0), // New version
        Box::new(ParameterRenameMapping::project_path_to_path()),
    );

    registry.register_migration(
        ContractVersion::new(0, 1, 0),
        ContractVersion::new(1, 0, 0),
        ParameterRenameMapping::file_to_files(),
    );

    Ok(registry)
}

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

    #[test]
    fn test_version_compatibility() {
        let v1_0_0 = ContractVersion::new(1, 0, 0);
        let v1_1_0 = ContractVersion::new(1, 1, 0);
        let v2_0_0 = ContractVersion::new(2, 0, 0);

        assert!(v1_1_0.is_compatible(&v1_0_0));
        assert!(!v1_0_0.is_compatible(&v1_1_0));
        assert!(!v2_0_0.is_compatible(&v1_0_0));
        assert!(v2_0_0.requires_migration(&v1_0_0));
    }

    #[test]
    fn test_contract_registry() {
        let mut registry = ContractRegistry::new();

        let contract = ContractBuilder::new(json!({"path": ".", "format": "json"}), "test").build();

        registry.register("test_contract", contract).unwrap();

        let latest = registry.get_latest("test_contract").unwrap();
        assert_eq!(latest.version, ContractVersion::current());
        assert_eq!(latest.contract["path"], ".");
    }

    #[test]
    fn test_parameter_migration() {
        let migration = ParameterRenameMapping::project_path_to_path();

        let old_contract = json!({
            "project_path": "/src",
            "format": "json"
        });

        let new_contract = migration.migrate(old_contract).unwrap();

        assert_eq!(new_contract["path"], "/src");
        assert!(new_contract["project_path"].is_null());
        assert_eq!(new_contract["format"], "json");
    }

    #[test]
    fn test_file_to_files_migration() {
        let migration = FileToFilesMigration;

        let old_contract = json!({
            "path": ".",
            "file": "main.rs",
            "format": "json"
        });

        let new_contract = migration.migrate(old_contract).unwrap();

        assert_eq!(new_contract["files"], json!(["main.rs"]));
        assert!(new_contract["file"].is_null());
    }
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[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);
        }
    }
}