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
//! Comprehensive contract tests covering all scenarios
//! These tests ensure the uniform contract system works correctly

use super::*;
use super::versioning::*;
use super::simple_service::SimpleContractService;
use super::mcp_simple::SimpleMcpHandler;
use serde_json::json;
use tokio_test;

/// Test contract validation rules
#[test]
fn test_contract_validation() {
    // Valid contract
    let valid_contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(5),
            include_tests: false,
            timeout: 30,
        },
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(5.0),
    };
    
    assert!(valid_contract.validate().is_ok());
    
    // Invalid contract - nonexistent path
    let invalid_contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::path::PathBuf::from("/nonexistent/path"),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(5),
            include_tests: false,
            timeout: 30,
        },
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(5.0),
    };
    
    assert!(invalid_contract.validate().is_err());
    
    // Invalid contract - zero timeout
    let invalid_timeout = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(5),
            include_tests: false,
            timeout: 0, // Invalid
        },
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(5.0),
    };
    
    assert!(invalid_timeout.validate().is_err());
    
    // Invalid contract - too many files
    let too_many_files = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(1001), // Too many
            include_tests: false,
            timeout: 60,
        },
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(5.0),
    };
    
    assert!(too_many_files.validate().is_err());
    
    // Invalid contract - negative halstead
    let negative_halstead = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(5),
            include_tests: false,
            timeout: 60,
        },
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(-1.0), // Invalid
    };
    
    assert!(negative_halstead.validate().is_err());
}

/// Test service integration with contracts
#[tokio::test]
async fn test_service_integration() {
    let service = SimpleContractService::new().unwrap();
    
    let contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(3),
            include_tests: false,
            timeout: 30,
        },
        max_cyclomatic: Some(20),
        max_cognitive: Some(15),
        max_halstead: Some(10.0),
    };
    
    let result = service.analyze_complexity(contract).await;
    assert!(result.is_ok());
    
    let value = result.unwrap();
    assert!(value.is_object());
    
    // Check that result has expected structure
    let obj = value.as_object().unwrap();
    assert!(obj.contains_key("results"));
    assert!(obj.contains_key("summary"));
    assert!(obj.contains_key("metadata"));
}

/// Test MCP handler with contracts
#[tokio::test]
async fn test_mcp_handler_integration() {
    let handler = SimpleMcpHandler::new().unwrap();
    
    let params = json!({
        "path": ".",
        "format": "json",
        "top_files": 3,
        "include_tests": false,
        "timeout": 30,
        "max_cyclomatic": 20,
        "max_cognitive": 15,
        "max_halstead": 10.0
    });
    
    let result = handler.handle_tool_call("analyze_complexity", params).await;
    assert!(result.is_ok());
    
    let value = result.unwrap();
    assert!(value.is_object());
    
    // Test unknown tool
    let unknown_result = handler.handle_tool_call("unknown_tool", json!({})).await;
    assert!(unknown_result.is_err());
}

/// Test contract serialization and deserialization
#[test]
fn test_contract_serialization() {
    let original_contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::path::PathBuf::from("src"),
            format: OutputFormat::Json,
            output: Some(std::path::PathBuf::from("output.json")),
            top_files: Some(5),
            include_tests: true,
            timeout: 120,
        },
        max_cyclomatic: Some(10),
        max_cognitive: None,
        max_halstead: Some(5.0),
    };
    
    // Serialize to JSON
    let json = serde_json::to_value(&original_contract).unwrap();
    
    // Verify flat structure (base fields are flattened)
    assert_eq!(json["path"], "src");
    assert_eq!(json["format"], "json");
    assert_eq!(json["output"], "output.json");
    assert_eq!(json["top_files"], 5);
    assert_eq!(json["include_tests"], true);
    assert_eq!(json["timeout"], 120);
    assert_eq!(json["max_cyclomatic"], 10);
    assert_eq!(json["max_halstead"], 5.0);
    assert!(json["max_cognitive"].is_null());
    
    // Deserialize back
    let deserialized: AnalyzeComplexityContract = serde_json::from_value(json).unwrap();
    assert_eq!(deserialized, original_contract);
}

/// Test backward compatibility with adapter
#[test]
fn test_backward_compatibility() {
    // Old parameter format
    let old_params = json!({
        "project_path": "/src",
        "file": "main.rs",
        "format": "human"
    });
    
    let new_params = super::adapter::BackwardCompatibility::map_json_params(old_params);
    
    // Verify mapping
    assert_eq!(new_params["path"], "/src");
    assert_eq!(new_params["files"], json!(["main.rs"]));
    assert_eq!(new_params["format"], "summary");
    assert!(new_params.get("project_path").is_none());
    assert!(new_params.get("file").is_none());
}

/// Test contract versioning
#[test]
fn test_contract_versioning() {
    let mut registry = ContractRegistry::new();
    
    // Register v1.0.0 contract
    let v1_contract = ContractBuilder::new(
        json!({
            "path": ".",
            "format": "json"
        }),
        "test"
    )
    .version(1, 0, 0)
    .description("Version 1.0.0 contract")
    .build();
    
    registry.register("test_contract", v1_contract).unwrap();
    
    // Register v1.1.0 contract with new field
    let v1_1_contract = ContractBuilder::new(
        json!({
            "path": ".",
            "format": "json",
            "timeout": 60
        }),
        "test"
    )
    .version(1, 1, 0)
    .description("Version 1.1.0 contract with timeout")
    .build();
    
    registry.register("test_contract", v1_1_contract).unwrap();
    
    // Test version retrieval
    let latest = registry.get_latest("test_contract").unwrap();
    assert_eq!(latest.version, ContractVersion::new(1, 1, 0));
    assert!(latest.contract.get("timeout").is_some());
    
    let v1_0 = registry.get_version("test_contract", &ContractVersion::new(1, 0, 0)).unwrap();
    assert!(v1_0.contract.get("timeout").is_none());
    
    // 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));
}

/// Test contract migration
#[test]
fn test_contract_migration() {
    let migration = super::versioning::ParameterRenameMapping::project_path_to_path();
    
    let old_contract = json!({
        "project_path": "/src",
        "format": "json",
        "max_cyclomatic": 20
    });
    
    let migrated = migration.migrate(old_contract).unwrap();
    
    assert_eq!(migrated["path"], "/src");
    assert!(migrated.get("project_path").is_none());
    assert_eq!(migrated["format"], "json");
    assert_eq!(migrated["max_cyclomatic"], 20);
}

/// Test error handling and propagation
#[tokio::test]
async fn test_error_handling() {
    let service = SimpleContractService::new().unwrap();
    
    // Test SATD contract with fail_on_violation
    let satd_contract = AnalyzeSatdContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(5),
            include_tests: false,
            timeout: 30,
        },
        severity: Some(SatdSeverity::Critical),
        critical_only: false,
        strict: true,
        fail_on_violation: true,
    };
    
    // This should succeed with simple service (no real violations)
    let result = service.analyze_satd(satd_contract).await;
    assert!(result.is_ok());
}

/// Test all contract types
#[test]
fn test_all_contract_types() {
    let contracts: Vec<Box<dyn ContractValidation>> = vec![
        Box::new(AnalyzeComplexityContract {
            base: BaseAnalysisContract::default(),
            max_cyclomatic: Some(10),
            max_cognitive: Some(8),
            max_halstead: Some(5.0),
        }),
        Box::new(AnalyzeSatdContract {
            base: BaseAnalysisContract::default(),
            severity: Some(SatdSeverity::Medium),
            critical_only: false,
            strict: false,
            fail_on_violation: false,
        }),
        Box::new(AnalyzeDeadCodeContract {
            base: BaseAnalysisContract::default(),
            include_unreachable: true,
            min_dead_lines: 5,
            max_percentage: 20.0,
            fail_on_violation: false,
        }),
        Box::new(AnalyzeTdgContract {
            base: BaseAnalysisContract::default(),
            threshold: 2.0,
            include_components: true,
            critical_only: false,
        }),
        Box::new(AnalyzeLintHotspotContract {
            base: BaseAnalysisContract::default(),
            file: None,
            max_density: 10.0,
            min_confidence: 0.7,
            enforce: false,
            dry_run: true,
        }),
        Box::new(QualityGateContract {
            base: BaseAnalysisContract::default(),
            profile: QualityProfile::Standard,
            file: None,
            fail_on_violation: false,
            verbose: false,
        }),
        Box::new(RefactorAutoContract {
            file: std::env::current_dir().unwrap().join("test.rs"),
            format: OutputFormat::Json,
            output: None,
            target_complexity: 8,
            dry_run: true,
            timeout: 60,
        }),
    ];
    
    // All contracts should have valid default configurations
    for contract in contracts {
        // Note: Some may fail validation due to missing files, but structure should be valid
        let _ = contract.validate();
    }
}

/// Integration test with all service types
#[tokio::test]
async fn test_service_type_integration() {
    // Test simple service
    let simple_service = SimpleContractService::new().unwrap();
    let unified_service = super::service::ContractService::new().unwrap();
    
    let contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract {
            path: std::env::current_dir().unwrap(),
            format: OutputFormat::Json,
            output: None,
            top_files: Some(3),
            include_tests: false,
            timeout: 30,
        },
        max_cyclomatic: Some(20),
        max_cognitive: Some(15),
        max_halstead: Some(10.0),
    };
    
    // Both services should work with same contract
    let simple_result = simple_service.analyze_complexity(contract.clone()).await;
    let unified_result = unified_service.analyze_complexity(contract).await;
    
    assert!(simple_result.is_ok());
    assert!(unified_result.is_ok());
    
    // Results should have similar structure
    let simple_value = simple_result.unwrap();
    let unified_value = unified_result.unwrap();
    
    assert!(simple_value.is_object());
    assert!(unified_value.is_object());
}

/// Test contract enforcement at compile time
#[test]
fn test_contract_type_safety() {
    // These should compile successfully
    let complexity_contract = AnalyzeComplexityContract {
        base: BaseAnalysisContract::default(),
        max_cyclomatic: Some(10),
        max_cognitive: Some(8),
        max_halstead: Some(5.0),
    };
    
    let satd_contract = AnalyzeSatdContract {
        base: BaseAnalysisContract::default(),
        severity: Some(SatdSeverity::High),
        critical_only: true,
        strict: false,
        fail_on_violation: false,
    };
    
    // Verify contracts can be serialized/deserialized
    let complexity_json = serde_json::to_value(&complexity_contract).unwrap();
    let satd_json = serde_json::to_value(&satd_contract).unwrap();
    
    let _: AnalyzeComplexityContract = serde_json::from_value(complexity_json).unwrap();
    let _: AnalyzeSatdContract = serde_json::from_value(satd_json).unwrap();
}

/// Performance test for contract operations
#[test]
fn test_contract_performance() {
    let start = std::time::Instant::now();
    
    // Create many contracts
    for i in 0..1000 {
        let contract = AnalyzeComplexityContract {
            base: BaseAnalysisContract {
                path: std::path::PathBuf::from("."),
                format: OutputFormat::Json,
                output: None,
                top_files: Some(i % 50),
                include_tests: i % 2 == 0,
                timeout: 60,
            },
            max_cyclomatic: Some(i as u32 % 30),
            max_cognitive: Some(i as u32 % 25),
            max_halstead: Some((i as f64) / 100.0),
        };
        
        // Validate
        let _ = contract.validate();
        
        // Serialize
        let _ = serde_json::to_value(&contract).unwrap();
    }
    
    let duration = start.elapsed();
    println!("Contract operations took: {:?}", duration);
    
    // Should complete in reasonable time (less than 100ms)
    assert!(duration.as_millis() < 100);
}