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
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use crate::services::satd_detector::*;
    use proptest::prelude::*;
    use std::io::Write;
    use std::path::Path;
    use tempfile::NamedTempFile;

    // Strategy for generating valid SATD markers
    prop_compose! {
        fn arb_satd_marker()
            (choice in 0usize..10)
            -> &'static str
        {
            match choice {
                0 => "TODO",
                1 => "FIXME",
                2 => "HACK",
                3 => "BUG",
                4 => "XXX",
                5 => "OPTIMIZE",
                6 => "SECURITY",
                7 => "KLUDGE",
                8 => "REFACTOR",
                _ => "TECHNICAL DEBT",
            }
        }
    }

    // Strategy for generating comment styles
    prop_compose! {
        fn arb_comment_style()
            (style in 0usize..5,
             padding in prop::collection::vec(prop::sample::select(vec![" ", "\t"]), 0..5))
            -> String
        {
            let padding_str = padding.join("");
            match style {
                0 => format!("{}//", padding_str),
                1 => format!("{}#", padding_str),
                2 => format!("{}/*", padding_str),
                3 => format!("{} *", padding_str),
                _ => format!("{}--", padding_str),
            }
        }
    }

    // Strategy for generating SATD comments
    prop_compose! {
        fn arb_satd_comment()
            (marker in arb_satd_marker(),
             style in arb_comment_style(),
             message in "[a-zA-Z0-9 .,!?-]{0,100}",
             extra_spaces in 0usize..5)
            -> String
        {
            format!("{}{}{}: {}",
                style,
                " ".repeat(extra_spaces),
                marker,
                message)
        }
    }

    // Strategy for generating source code with embedded SATD
    prop_compose! {
        fn arb_source_with_satd()
            (num_lines in 1usize..50,
             satd_lines in prop::collection::vec((0usize..50, arb_satd_comment()), 0..10),
             code_lines in prop::collection::vec("[a-zA-Z0-9_(){}; ]{0,80}", 0..50))
            -> String
        {
            let mut lines = vec![];
            let satd_map: std::collections::HashMap<_, _> = satd_lines.into_iter().collect();

            for i in 0..num_lines {
                if let Some(satd) = satd_map.get(&i) {
                    lines.push(satd.clone());
                } else if let Some(code) = code_lines.get(i % code_lines.len().max(1)) {
                    lines.push(code.clone());
                } else {
                    lines.push(String::new());
                }
            }

            lines.join("\n")
        }
    }

    // Strategy for generating file extensions
    prop_compose! {
        fn arb_file_extension()
            (choice in 0usize..10)
            -> &'static str
        {
            match choice {
                0 => "rs",
                1 => "ts",
                2 => "js",
                3 => "py",
                4 => "go",
                5 => "java",
                6 => "cpp",
                7 => "c",
                8 => "rb",
                _ => "txt",
            }
        }
    }

    #[test]
    #[ignore = "Property test hangs - parser stress test too slow"]
    fn test_satd_parser_total_function() {
        proptest!(|(source in arb_source_with_satd())| {
            // Property: Parser is total (never panics on any input)
            let detector = SATDDetector::new();
            let result = std::panic::catch_unwind(|| {
                detector.extract_from_content(&source, Path::new("test.rs"))
            });
            prop_assert!(result.is_ok(), "Parser panicked on input");
        });
    }

    #[test]
    fn test_satd_extraction_deterministic() {
        proptest!(|(
            source in arb_source_with_satd(),
            ext in arb_file_extension()
        )| {
            // Property: Parsing is deterministic
            let detector = SATDDetector::new();
            let filename = format!("test.{}", ext);
            let path = Path::new(&filename);

            let result1 = detector.extract_from_content(&source, path);
            let result2 = detector.extract_from_content(&source, path);

            match (result1, result2) {
                (Ok(debts1), Ok(debts2)) => {
                    prop_assert_eq!(debts1.len(), debts2.len(),
                        "Different number of SATD items on repeated parse");

                    for (d1, d2) in debts1.iter().zip(debts2.iter()) {
                        prop_assert_eq!(d1.category, d2.category);
                        prop_assert_eq!(d1.severity, d2.severity);
                        prop_assert_eq!(&d1.text, &d2.text);
                        prop_assert_eq!(d1.line, d2.line);
                    }
                },
                (Err(_), Err(_)) => {
                    // Both failed consistently
                },
                _ => prop_assert!(false, "Inconsistent parsing results"),
            }
        });
    }

    #[test]
    fn test_satd_line_numbers_valid() {
        proptest!(|(source in arb_source_with_satd())| {
            // Property: All detected SATD items have valid line numbers
            let detector = SATDDetector::new();
            let result = detector.extract_from_content(&source, Path::new("test.rs"));

            if let Ok(debts) = result {
                let total_lines = source.lines().count() as u32;

                for debt in debts {
                    prop_assert!(debt.line > 0, "Line number must be positive");
                    prop_assert!(debt.line <= total_lines,
                        "Line number {} exceeds total lines {}", debt.line, total_lines);
                }
            }
        });
    }

    #[test]
    fn test_satd_categories_consistent() {
        proptest!(|(marker in arb_satd_marker())| {
            // Property: Known markers always map to consistent categories
            let detector = SATDDetector::new();
            let comment1 = format!("// {}: test issue", marker);
            let comment2 = format!("# {}: different message", marker);

            let result1 = detector.extract_from_content(&comment1, Path::new("test.rs"));
            let result2 = detector.extract_from_content(&comment2, Path::new("test.py"));

            if let (Ok(debts1), Ok(debts2)) = (result1, result2) {
                if !debts1.is_empty() && !debts2.is_empty() {
                    prop_assert_eq!(debts1[0].category, debts2[0].category,
                        "Same marker should map to same category");
                }
            }
        });
    }

    #[test]
    fn test_satd_severity_ordering() {
        // Property: Severity levels maintain correct ordering
        // Note: The enum derives Ord, so ordering is based on declaration order
        // EXTREME TDD FIX: Low is declared first, so it has the lowest discriminant
        use Severity::*;

        // The actual ordering based on enum declaration (Low → Critical)
        assert!(Low < Medium);
        assert!(Medium < High);
        assert!(High < Critical);

        // Test escalation
        assert_eq!(Low.escalate(), Medium);
        assert_eq!(Medium.escalate(), High);
        assert_eq!(High.escalate(), Critical);
        assert_eq!(Critical.escalate(), Critical); // Can't escalate beyond Critical

        // Test reduction
        assert_eq!(Critical.reduce(), High);
        assert_eq!(High.reduce(), Medium);
        assert_eq!(Medium.reduce(), Low);
        assert_eq!(Low.reduce(), Low); // Can't reduce below Low
    }

    #[test]
    fn test_satd_empty_input_handled() {
        proptest!(|(whitespace in prop::collection::vec(
            prop::sample::select(vec![" ", "\t", "\n", "\r"]), 0..100
        ))| {
            // Property: Empty or whitespace-only input is handled gracefully
            let content = whitespace.join("");
            let detector = SATDDetector::new();

            let result = detector.extract_from_content(&content, Path::new("test.rs"));
            prop_assert!(result.is_ok(), "Should handle empty input");

            if let Ok(debts) = result {
                prop_assert_eq!(debts.len(), 0, "Empty input should produce no SATD items");
            }
        });
    }

    #[test]
    fn test_satd_malformed_comments_handled() {
        proptest!(|(
            prefix in "[^/\\*#-]{0,50}",
            marker in arb_satd_marker(),
            suffix in "[^\\n]{0,50}"
        )| {
            // Property: Malformed comments don't crash the parser
            let malformed = format!("{}{}{}", prefix, marker, suffix);
            let detector = SATDDetector::new();

            let result = std::panic::catch_unwind(|| {
                detector.extract_from_content(&malformed, Path::new("test.rs"))
            });

            prop_assert!(result.is_ok(), "Parser should not panic on malformed input");
        });
    }

    #[test]
    fn test_satd_content_extraction_preserves_structure() {
        proptest!(|(
            lines in prop::collection::vec("[a-zA-Z0-9 ]{0,100}", 1..20),
            satd_indices in prop::collection::vec(0usize..20, 0..5)
        )| {
            // Property: Content extraction preserves line structure
            let detector = SATDDetector::new();
            let mut source_lines = lines.clone();

            // Insert SATD comments at specified indices
            for &idx in &satd_indices {
                if idx < source_lines.len() {
                    source_lines[idx] = format!("// TODO: issue at line {}", idx);
                }
            }

            let source = source_lines.join("\n");
            let result = detector.extract_from_content(&source, Path::new("test.rs"));

            if let Ok(debts) = result {
                // All detected debts should have correct line numbers
                for debt in debts {
                    let line_idx = (debt.line - 1) as usize;
                    prop_assert!(
                        line_idx < source_lines.len(),
                        "Line number {} out of bounds", debt.line
                    );
                }
            }
        });
    }

    #[test]
    #[ignore = "Property test hangs - file I/O too slow"]
    fn test_satd_file_integration() {
        proptest!(|(source in arb_source_with_satd())| {
            // Property: File I/O integration works correctly
            let detector = SATDDetector::new();

            // Create temporary file
            let mut temp_file = NamedTempFile::new().unwrap();
            temp_file.write_all(source.as_bytes()).unwrap();
            temp_file.flush().unwrap();
            let path = temp_file.path();

            // Read file and analyze
            let file_content = std::fs::read_to_string(path).unwrap();
            prop_assert_eq!(&file_content, &source, "File content should match written content");

            let result = detector.extract_from_content(&file_content, path);
            prop_assert!(result.is_ok() || file_content.len() > 10000,
                "Should successfully analyze file content");
        });
    }

    #[test]
    fn test_satd_test_block_exclusion() {
        proptest!(|(
            pre_test in prop::collection::vec("[a-zA-Z0-9_; ]{0,80}", 0..10),
            test_content in prop::collection::vec(arb_satd_comment(), 1..5),
            post_test in prop::collection::vec("[a-zA-Z0-9_; ]{0,80}", 0..10)
        )| {
            // Property: SATD in test blocks should be excluded (Rust files)
            let mut lines = vec![];

            // Add pre-test code
            lines.extend(pre_test);

            // Add test block
            lines.push("#[cfg(test)]".to_string());
            lines.push("mod tests {".to_string());
            let test_content_len = test_content.len();
            lines.extend(test_content);
            lines.push("}".to_string());

            // Add post-test code
            lines.extend(post_test);

            let source = lines.join("\n");
            let detector = SATDDetector::new();

            let result = detector.extract_from_content(&source, Path::new("test.rs"));

            if let Ok(debts) = result {
                // No SATD should be detected within the test block lines
                let test_start_line = lines.iter().position(|l| l.contains("#[cfg(test)]")).unwrap() + 1;
                let test_end_line = test_start_line + 3 + test_content_len;

                for debt in debts {
                    prop_assert!(
                        debt.line <= test_start_line as u32 || debt.line > test_end_line as u32,
                        "SATD found inside test block at line {}", debt.line
                    );
                }
            }
        });
    }

    #[test]
    fn test_satd_unicode_handling() {
        proptest!(|(
            prefix in "\\PC*",
            marker in arb_satd_marker(),
            suffix in "\\PC*"
        )| {
            // Property: Unicode in comments is handled properly
            let content = format!("// {} {}: {}", prefix, marker, suffix);
            let detector = SATDDetector::new();

            let result = std::panic::catch_unwind(|| {
                detector.extract_from_content(&content, Path::new("test.rs"))
            });

            prop_assert!(result.is_ok(), "Should handle Unicode without panicking");
        });
    }

    #[test]
    #[ignore = "Property test hangs - large file generation too slow"]
    fn test_satd_large_file_performance() {
        proptest!(|(
            line_template in "[a-zA-Z0-9 ]{0,100}",
            num_repetitions in 100usize..1000
        )| {
            // Property: Performance scales linearly with file size
            let detector = SATDDetector::new();

            // Create a large file by repeating lines
            let mut lines = vec![];
            for i in 0..num_repetitions {
                if i % 10 == 0 {
                    lines.push(format!("// TODO: Fix issue {}", i));
                } else {
                    lines.push(line_template.clone());
                }
            }
            let content = lines.join("\n");

            let result = detector.extract_from_content(&content, Path::new("test.rs"));

            if let Ok(debts) = result {
                // Should find approximately num_repetitions / 10 SATD items
                let expected = num_repetitions / 10;
                prop_assert!(
                    debts.len() >= expected - 1 && debts.len() <= expected + 1,
                    "Expected around {} SATD items, found {}", expected, debts.len()
                );
            }
        });
    }

    // Additional edge case tests
    #[test]
    fn test_satd_nested_comments() {
        proptest!(|(
            depth in 1usize..5,
            marker in arb_satd_marker()
        )| {
            // Property: Nested comment styles are parsed correctly
            let mut content = String::new();

            // Create nested comment structure
            for _ in 0..depth {
                content.push_str("/* ");
            }
            content.push_str(&format!("{}: nested issue", marker));
            for _ in 0..depth {
                content.push_str(" */");
            }

            let detector = SATDDetector::new();
            let result = detector.extract_from_content(&content, Path::new("test.c"));

            prop_assert!(result.is_ok(), "Should handle nested comments");
        });
    }

    #[test]
    fn test_satd_multiline_handling() {
        proptest!(|(
            lines in prop::collection::vec("[a-zA-Z0-9 ]{0,50}", 2..10),
            marker in arb_satd_marker()
        )| {
            // Property: Multi-line comments are handled correctly
            let mut content = vec!["/*".to_string()];
            content.push(format!(" * {}: multi-line issue", marker));
            for line in lines {
                content.push(format!(" * {}", line));
            }
            content.push(" */".to_string());

            let source = content.join("\n");
            let detector = SATDDetector::new();

            let result = detector.extract_from_content(&source, Path::new("test.c"));

            if let Ok(debts) = result {
                if !debts.is_empty() {
                    // Should detect the SATD on the correct line
                    prop_assert_eq!(debts[0].line, 2, "SATD should be on line 2");
                }
            }
        });
    }
}