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

use super::*;

// ============================================================================
// CB-529: .pmat/ Tracked in Git
// ============================================================================
mod cb529_tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use std::process::Command;
    use tempfile::TempDir;

    fn init_git_repo(dir: &Path) {
        Command::new("git")
            .args(["init", "--initial-branch=main"])
            .current_dir(dir)
            .output()
            .expect("git init");
        Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir)
            .output()
            .expect("git config email");
        Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir)
            .output()
            .expect("git config name");
    }

    fn git_add_commit(dir: &Path, files: &[&str]) {
        for f in files {
            Command::new("git")
                .args(["add", f])
                .current_dir(dir)
                .output()
                .expect("git add");
        }
        Command::new("git")
            .args(["commit", "-m", "init", "--allow-empty"])
            .current_dir(dir)
            .output()
            .expect("git commit");
    }

    #[test]
    fn test_cb529_detects_root_pmat_files() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        init_git_repo(root);

        fs::create_dir_all(root.join(".pmat")).unwrap();
        fs::write(root.join(".pmat/context.db"), "fake").unwrap();
        fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
        git_add_commit(root, &[".pmat/context.db", "Cargo.toml"]);

        let violations = detect_cb529_pmat_tracked_in_git(root);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].pattern_id, "CB-529");
        assert!(violations[0].file.contains(".pmat/context.db"));
        assert_eq!(violations[0].severity, Severity::Error);
    }

    #[test]
    fn test_cb529_detects_subcrate_pmat_files() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        init_git_repo(root);

        fs::create_dir_all(root.join("crates/foo/.pmat")).unwrap();
        fs::write(root.join("crates/foo/.pmat/context.idx"), "data").unwrap();
        fs::write(root.join("crates/foo/.pmat/dead-code-cache.json"), "{}").unwrap();
        git_add_commit(
            root,
            &[
                "crates/foo/.pmat/context.idx",
                "crates/foo/.pmat/dead-code-cache.json",
            ],
        );

        let violations = detect_cb529_pmat_tracked_in_git(root);
        assert_eq!(violations.len(), 2);
        assert!(violations.iter().all(|v| v.pattern_id == "CB-529"));
        assert!(violations.iter().all(|v| v.file.contains("/.pmat/")));
    }

    #[test]
    fn test_cb529_passes_clean_repo() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        init_git_repo(root);

        fs::write(root.join("Cargo.toml"), "[package]\nname = \"test\"\n").unwrap();
        fs::write(root.join("README.md"), "# Test\n").unwrap();
        git_add_commit(root, &["Cargo.toml", "README.md"]);

        let violations = detect_cb529_pmat_tracked_in_git(root);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_cb529_ignores_pmat_in_filenames() {
        let temp = TempDir::new().unwrap();
        let root = temp.path();
        init_git_repo(root);

        // A file named "some.pmat_config" is NOT a .pmat/ directory artifact
        fs::write(root.join("some.pmat_config"), "data").unwrap();
        git_add_commit(root, &["some.pmat_config"]);

        let violations = detect_cb529_pmat_tracked_in_git(root);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_cb529_not_git_repo() {
        let temp = TempDir::new().unwrap();
        let violations = detect_cb529_pmat_tracked_in_git(temp.path());
        assert!(violations.is_empty());
    }
}

// ============================================================================
// CB-528: Division-by-length Without Empty Guard
// ============================================================================
mod cb528_tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_cb528_detects_unguarded_division_by_len() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("stats.rs"),
            r#"
fn mean(values: &[f64]) -> f64 {
    let sum: f64 = values.iter().sum();
    sum / values.len() as f64
}
"#,
        )
        .unwrap();

        let violations = detect_cb528_division_by_length(temp.path());
        assert_eq!(
            violations.len(),
            1,
            "should detect unguarded division by len"
        );
        assert!(violations[0].description.contains("Division by .len()"));
        assert_eq!(violations[0].pattern_id, "CB-528");
    }

    #[test]
    fn test_cb528_allows_guarded_division_with_is_empty() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("stats.rs"),
            r#"
fn mean(values: &[f64]) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    let sum: f64 = values.iter().sum();
    sum / values.len() as f64
}
"#,
        )
        .unwrap();

        let violations = detect_cb528_division_by_length(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag when is_empty guard present"
        );
    }

    #[test]
    fn test_cb528_allows_guarded_division_with_max_1() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("stats.rs"),
            r#"
fn diversity(items: &[String], total: &[String]) -> f32 {
    items.len() as f32 / total.len().max(1) as f32
}
"#,
        )
        .unwrap();

        let violations = detect_cb528_division_by_length(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag when .max(1) guard present"
        );
    }

    #[test]
    fn test_cb528_skips_test_code() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("lib.rs"),
            r#"
fn production() {}

#[cfg(test)]
mod tests {
    fn test_mean() {
        let sum = 10.0;
        let result = sum / vec![1,2,3].len() as f64;
    }
}
"#,
        )
        .unwrap();

        let violations = detect_cb528_division_by_length(temp.path());
        assert!(violations.is_empty(), "should not flag test code");
    }

    #[test]
    fn test_cb528_allows_len_gt_zero_guard() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("stats.rs"),
            r#"
fn mean(values: &[f64]) -> f64 {
    if values.len() > 0 {
        values.iter().sum::<f64>() / values.len() as f64
    } else {
        0.0
    }
}
"#,
        )
        .unwrap();

        let violations = detect_cb528_division_by_length(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag when len > 0 guard present"
        );
    }
}

// ============================================================================
// CB-530: Log Without Clamp Guard
// ============================================================================
mod cb530_tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_cb530_detects_bare_ln() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("loss.rs"),
            r#"
fn cross_entropy(probs: &[f32], labels: &[usize]) -> f32 {
    let mut total = 0.0;
    for &label in labels {
        total -= probs[label].ln();
    }
    total
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert_eq!(
            violations.len(),
            1,
            "should detect bare .ln() without guard"
        );
        assert!(violations[0].description.contains("ln()"));
        assert_eq!(violations[0].pattern_id, "CB-530");
    }

    #[test]
    fn test_cb530_allows_max_guarded_ln() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("loss.rs"),
            r#"
fn cross_entropy(probs: &[f32], labels: &[usize]) -> f32 {
    let mut total = 0.0;
    for &label in labels {
        total -= probs[label].max(1e-10).ln();
    }
    total
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag when .max(eps) guard present"
        );
    }

    #[test]
    fn test_cb530_allows_clamp_guarded_log() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("info.rs"),
            r#"
fn entropy(p: f64) -> f64 {
    let safe_p = p.clamp(1e-15, 1.0);
    -safe_p * safe_p.ln()
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        // The clamp is on a preceding line — should be caught by context check
        // Actually .ln() is on safe_p which was clamped, but our detector checks same line
        // This tests that we look at preceding lines for guards
        assert!(
            violations.is_empty(),
            "should not flag when .clamp() guard on preceding line"
        );
    }

    #[test]
    fn test_cb530_allows_positive_literal_log() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("math.rs"),
            r#"
fn log_base_2() -> f64 {
    let ln2 = 2.0_f64.ln();
    ln2
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag positive literal .ln()"
        );
    }

    #[test]
    fn test_cb530_detects_log2() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("bits.rs"),
            r#"
fn bit_entropy(freq: f32) -> f32 {
    -freq * freq.log2()
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert_eq!(violations.len(), 1, "should detect bare .log2()");
        assert!(violations[0].description.contains("log2()"));
    }

    #[test]
    fn test_cb530_skips_test_code() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("lib.rs"),
            r#"
fn production() {}

#[cfg(test)]
mod tests {
    fn test_log() {
        let x = 0.5_f32.ln();
    }
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert!(violations.is_empty(), "should not flag test code");
    }

    #[test]
    fn test_cb530_allows_log_of_one_plus_x() {
        let temp = TempDir::new().unwrap();
        let src = temp.path().join("src");
        fs::create_dir_all(&src).unwrap();
        fs::write(
            src.join("mel.rs"),
            r#"
fn hz_to_mel(hz: f32) -> f32 {
    2595.0 * (1.0 + hz / 700.0).log10()
}
"#,
        )
        .unwrap();

        let violations = detect_cb530_log_without_clamp(temp.path());
        assert!(
            violations.is_empty(),
            "should not flag log of (1.0 + x) pattern"
        );
    }
}