pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
Documentation
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extract_path_references() {
        let extractor = SpecClaimExtractor::new();
        let content = r#"
## Architecture
The main module is at `src/services/context.rs` which handles indexing.
Configuration lives in `docs/specifications/falsify-rag.md`.
"#;
        let claims = extractor.extract(content, Path::new("test.md"));
        let path_claims: Vec<_> = claims
            .iter()
            .filter(|c| c.category == SpecClaimCategory::PathReference)
            .collect();
        assert!(
            path_claims.len() >= 2,
            "Expected >=2 path claims, got {}: {:?}",
            path_claims.len(),
            path_claims
        );
        assert!(path_claims
            .iter()
            .any(|c| c.path_refs.iter().any(|p| p.contains("context.rs"))));
    }

    #[test]
    fn extract_rfc2119_priorities() {
        let extractor = SpecClaimExtractor::new();
        let content = r#"
## Requirements
- Implementations MUST validate all inputs before processing
- Clients SHOULD cache results for performance
- Servers MAY support optional compression
"#;
        let claims = extractor.extract(content, Path::new("test.md"));
        assert!(claims
            .iter()
            .any(|c| c.priority == ClaimPriority::P0Critical));
        assert!(claims.iter().any(|c| c.priority == ClaimPriority::P1High));
        assert!(claims.iter().any(|c| c.priority == ClaimPriority::P2Low));
    }

    #[test]
    fn extract_numeric_claims() {
        let extractor = SpecClaimExtractor::new();
        let content = "Coverage must be >= 95% across all modules.\n";
        let claims = extractor.extract(content, Path::new("test.md"));
        let metric_claims: Vec<_> = claims
            .iter()
            .filter(|c| {
                matches!(
                    c.category,
                    SpecClaimCategory::MetricClaim
                        | SpecClaimCategory::AbsenceClaim
                        | SpecClaimCategory::ArchitecturalClaim
                )
            })
            .collect();
        // Should find a claim with numeric value
        let has_numeric = claims.iter().any(|c| c.numeric_value.is_some());
        assert!(
            has_numeric,
            "Expected numeric claim, got: {:?}",
            metric_claims
        );
    }

    #[test]
    fn extract_code_entities() {
        let extractor = SpecClaimExtractor::new();
        let content = "The `FalsificationEngine` processes claims via `ClaimExtractor`.\n";
        let claims = extractor.extract(content, Path::new("test.md"));
        let entity_claims: Vec<_> = claims
            .iter()
            .filter(|c| c.category == SpecClaimCategory::CodeEntity)
            .collect();
        assert!(
            !entity_claims.is_empty(),
            "Expected entity claims, got none"
        );
        assert!(entity_claims
            .iter()
            .any(|c| c.entity_refs.contains(&"FalsificationEngine".to_string())));
    }

    #[test]
    fn extract_absence_claims() {
        let extractor = SpecClaimExtractor::new();
        let content = "There must be zero unsafe blocks in the parser module.\n";
        let claims = extractor.extract(content, Path::new("test.md"));
        let absence = claims
            .iter()
            .filter(|c| c.category == SpecClaimCategory::AbsenceClaim)
            .count();
        assert!(absence > 0, "Expected absence claim, got: {:?}", claims);
    }

    #[test]
    fn extract_command_claims() {
        let extractor = SpecClaimExtractor::new();
        let content = "Run `pmat falsify` to validate specs against the codebase.\n";
        let claims = extractor.extract(content, Path::new("test.md"));
        let cmd_claims: Vec<_> = claims
            .iter()
            .filter(|c| c.category == SpecClaimCategory::CommandClaim)
            .collect();
        assert!(!cmd_claims.is_empty(), "Expected command claims");
    }

    #[test]
    fn skip_code_blocks() {
        let extractor = SpecClaimExtractor::new();
        let content = r#"
## Example
```rust
// This MUST not be extracted as a claim
let x = src/foo/bar.rs;
```
This line SHOULD be extracted.
"#;
        let claims = extractor.extract(content, Path::new("test.md"));
        // Only the "SHOULD" line should be extracted, not the code block contents
        assert!(
            claims.iter().all(|c| !c.original_text.contains("let x =")),
            "Code block content should not be extracted as claims"
        );
        assert!(claims.iter().any(|c| c.original_text.contains("SHOULD")));
    }

    #[test]
    fn absolute_language_detection() {
        let extractor = SpecClaimExtractor::new();
        let content = "All modules MUST have complete test coverage.\n";
        let claims = extractor.extract(content, Path::new("test.md"));
        assert!(!claims.is_empty());
        assert!(claims[0].is_absolute);
        assert_eq!(claims[0].priority, ClaimPriority::P0Critical);
    }

    #[test]
    fn path_reference_validation_existing_file() {
        let engine = FalsificationEngine::new(Path::new(env!("CARGO_MANIFEST_DIR")));
        let claim = SpecClaim {
            id: "test-001".to_string(),
            original_text: "Config at src/lib.rs".to_string(),
            source_line: 1,
            category: SpecClaimCategory::PathReference,
            priority: ClaimPriority::P3Default,
            is_absolute: false,
            path_refs: vec!["src/lib.rs".to_string()],
            entity_refs: vec![],
            numeric_value: None,
            numeric_comparator: None,
        };
        let evidence = engine.check_path_references(&claim);
        assert!(!evidence.is_empty());
        assert_eq!(
            evidence[0].contradiction_score, 0.0,
            "src/lib.rs should exist"
        );
    }

    #[test]
    fn path_reference_validation_missing_file() {
        let engine = FalsificationEngine::new(Path::new(env!("CARGO_MANIFEST_DIR")));
        let claim = SpecClaim {
            id: "test-002".to_string(),
            original_text: "Config at src/nonexistent_file_xyz.rs".to_string(),
            source_line: 1,
            category: SpecClaimCategory::PathReference,
            priority: ClaimPriority::P3Default,
            is_absolute: false,
            path_refs: vec!["src/nonexistent_file_xyz.rs".to_string()],
            entity_refs: vec![],
            numeric_value: None,
            numeric_comparator: None,
        };
        let evidence = engine.check_path_references(&claim);
        assert!(!evidence.is_empty());
        assert_eq!(
            evidence[0].contradiction_score, 1.0,
            "Nonexistent file should be falsified"
        );
    }

    #[test]
    fn verdict_determination() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = SpecClaim {
            id: "test".to_string(),
            original_text: "test".to_string(),
            source_line: 1,
            category: SpecClaimCategory::PathReference,
            priority: ClaimPriority::P3Default,
            is_absolute: false,
            path_refs: vec![],
            entity_refs: vec![],
            numeric_value: None,
            numeric_comparator: None,
        };

        // Surviving evidence
        let survived_ev = vec![SpecEvidence::supports("test", "ok")];
        assert_eq!(
            engine.determine_verdict(&claim, &survived_ev),
            VerdictStatus::Survived
        );

        // Falsified evidence
        let falsified_ev = vec![SpecEvidence::contradicts_with("test", "bad")];
        assert_eq!(
            engine.determine_verdict(&claim, &falsified_ev),
            VerdictStatus::Falsified
        );
    }

    #[test]
    fn summary_computation() {
        let claim = SpecClaim {
            id: "c1".to_string(),
            original_text: "test".to_string(),
            source_line: 1,
            category: SpecClaimCategory::PathReference,
            priority: ClaimPriority::P3Default,
            is_absolute: false,
            path_refs: vec![],
            entity_refs: vec![],
            numeric_value: None,
            numeric_comparator: None,
        };

        let verdicts = vec![
            SpecVerdict {
                claim: claim.clone(),
                status: VerdictStatus::Survived,
                evidence: vec![],
                contradiction_score: 0.0,
            },
            SpecVerdict {
                claim: claim.clone(),
                status: VerdictStatus::Falsified,
                evidence: vec![],
                contradiction_score: 1.0,
            },
            SpecVerdict {
                claim: claim.clone(),
                status: VerdictStatus::Unfalsifiable,
                evidence: vec![],
                contradiction_score: 0.0,
            },
        ];

        let summary = FalsificationEngine::compute_summary(&verdicts);
        assert_eq!(summary.total_claims, 3);
        assert_eq!(summary.survived, 1);
        assert_eq!(summary.falsified, 1);
        assert_eq!(summary.unfalsifiable, 1);
        // health = 1 survived / 2 testable = 0.5
        assert!((summary.health_score - 0.5).abs() < f64::EPSILON);
    }

    fn make_claim(
        id: &str,
        original_text: &str,
        category: SpecClaimCategory,
    ) -> SpecClaim {
        SpecClaim {
            id: id.to_string(),
            original_text: original_text.to_string(),
            source_line: 1,
            category,
            priority: ClaimPriority::P3Default,
            is_absolute: false,
            path_refs: vec![],
            entity_refs: vec![],
            numeric_value: None,
            numeric_comparator: None,
        }
    }

    // ── check_metric_claim: refuses explicitly, never certifies ──

    #[test]
    fn check_metric_claim_returns_unmeasured_evidence() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("m1", "coverage >= 95%", SpecClaimCategory::MetricClaim);
        let evidence = engine.check_metric_claim(&claim);
        assert_eq!(
            evidence.len(),
            1,
            "metric claims always return one evidence entry"
        );
        // PIN: pmat does not measure spec metrics. The evidence must say so
        // out loud rather than scoring 0.0 as if the check had passed.
        assert!(
            !evidence[0].measured,
            "an unrun metric check must be flagged unmeasured"
        );
        assert!(
            evidence[0].finding.contains("NOT MEASURED"),
            "refusal must be explicit, got: {}",
            evidence[0].finding
        );
        assert!(
            !evidence[0].contradicts(),
            "unmeasured evidence is not a contradiction either"
        );
    }

    /// REGRESSION (blocker: `pmat falsify` certified impossible metric claims).
    ///
    /// `check_metric_claim` was a stub returning contradiction_score 0.0, which
    /// `determine_verdict` mapped to SURVIVED — so every MetricClaim in every
    /// spec, including deliberately impossible ones, reported a green verdict.
    #[test]
    fn metric_claim_can_never_report_survived() {
        let engine = FalsificationEngine::new(Path::new("."));
        for text in [
            "The system MUST maintain test coverage >= 99.9% at all times.",
            "Every function MUST have cyclomatic complexity <= 1.",
            "The binary MUST start in < 0 ms.",
        ] {
            let claim = make_claim("m", text, SpecClaimCategory::MetricClaim);
            let evidence = engine.check_metric_claim(&claim);
            let verdict = engine.determine_verdict(&claim, &evidence);
            assert_eq!(
                verdict,
                VerdictStatus::Inconclusive,
                "unmeasured metric claim must not survive: {text}"
            );
            assert_ne!(verdict, VerdictStatus::Survived);
        }
    }

    /// A check that could not run (pmat missing, unparseable command) used to
    /// score 0.0 and therefore SURVIVE. Unmeasured must never certify.
    #[test]
    fn unmeasured_evidence_never_yields_survived() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("u", "t", SpecClaimCategory::CodeEntity);

        let unmeasured = vec![SpecEvidence::unmeasured("x", "NOT MEASURED: tool missing")];
        assert_eq!(
            engine.determine_verdict(&claim, &unmeasured),
            VerdictStatus::Inconclusive
        );

        // Even mixed with a real pass, one skipped check blocks SURVIVED.
        let mixed = vec![
            SpecEvidence::supports("a", "found"),
            SpecEvidence::unmeasured("b", "NOT MEASURED: tool missing"),
        ];
        assert_eq!(
            engine.determine_verdict(&claim, &mixed),
            VerdictStatus::Inconclusive
        );

        // A measured contradiction still wins over a skipped sibling check.
        let contradicted = vec![
            SpecEvidence::contradicts_with("a", "missing"),
            SpecEvidence::unmeasured("b", "NOT MEASURED: tool missing"),
        ];
        assert_eq!(
            engine.determine_verdict(&claim, &contradicted),
            VerdictStatus::Falsified
        );
    }

    /// The whole-spec report for a metric-only spec must not read as healthy.
    #[test]
    fn impossible_metric_spec_reports_zero_health() {
        let dir = tempfile::tempdir().unwrap();
        let spec = dir.path().join("impossible.md");
        std::fs::write(
            &spec,
            "# Impossible\n\nThe system MUST maintain test coverage >= 99.9% at all times.\n\
             The project MUST contain >= 100000000 lines of Rust.\n",
        )
        .unwrap();

        let engine = FalsificationEngine::new(dir.path());
        let report = engine.falsify_spec(&spec).unwrap();

        assert!(report.summary.total_claims >= 2, "claims must be extracted");
        assert_eq!(
            report.summary.survived, 0,
            "no impossible metric claim may survive"
        );
        assert_eq!(report.summary.inconclusive, report.summary.total_claims);
        assert_eq!(
            report.summary.health_score, 0.0,
            "an entirely unmeasured spec is not 100% healthy"
        );
    }

    // ── determine_verdict: unfalsifiable + inconclusive + boundary arms ──

    #[test]
    fn determine_verdict_unfalsifiable_category_short_circuits() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("u1", "t", SpecClaimCategory::Unfalsifiable);
        // Even a falsified-looking evidence vector is ignored for this category.
        let strong_ev = vec![SpecEvidence::contradicts_with("x", "y")];
        assert_eq!(
            engine.determine_verdict(&claim, &strong_ev),
            VerdictStatus::Unfalsifiable
        );
    }

    #[test]
    fn determine_verdict_architectural_claim_also_unfalsifiable() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("u2", "t", SpecClaimCategory::ArchitecturalClaim);
        assert_eq!(
            engine.determine_verdict(&claim, &[]),
            VerdictStatus::Unfalsifiable
        );
    }

    #[test]
    fn determine_verdict_empty_evidence_is_inconclusive() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("e1", "t", SpecClaimCategory::PathReference);
        assert_eq!(
            engine.determine_verdict(&claim, &[]),
            VerdictStatus::Inconclusive
        );
    }

    #[test]
    fn determine_verdict_contradiction_between_0_4_and_0_8_is_inconclusive() {
        let engine = FalsificationEngine::new(Path::new("."));
        let claim = make_claim("m1", "t", SpecClaimCategory::PathReference);
        let ev = vec![SpecEvidence::measured("x", "y", 0.5)];
        assert_eq!(
            engine.determine_verdict(&claim, &ev),
            VerdictStatus::Inconclusive
        );
    }

    // ── compute_summary health_score edge cases ──

    #[test]
    fn compute_summary_empty_verdicts_yields_perfect_health() {
        let summary = FalsificationEngine::compute_summary(&[]);
        assert_eq!(summary.total_claims, 0);
        // No testable claims → health_score defaults to 1.0 (perfect).
        assert!((summary.health_score - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn compute_summary_all_unfalsifiable_yields_perfect_health() {
        let c = make_claim("u", "t", SpecClaimCategory::Unfalsifiable);
        let verdicts = vec![
            SpecVerdict {
                claim: c.clone(),
                status: VerdictStatus::Unfalsifiable,
                evidence: vec![],
                contradiction_score: 0.0,
            },
            SpecVerdict {
                claim: c,
                status: VerdictStatus::Unfalsifiable,
                evidence: vec![],
                contradiction_score: 0.0,
            },
        ];
        let s = FalsificationEngine::compute_summary(&verdicts);
        assert_eq!(s.unfalsifiable, 2);
        // 2 - 2 = 0 testable → defaults to 1.0.
        assert!((s.health_score - 1.0).abs() < f64::EPSILON);
    }

    #[test]
    fn compute_summary_counts_inconclusive() {
        let c = make_claim("i", "t", SpecClaimCategory::PathReference);
        let verdicts = vec![
            SpecVerdict {
                claim: c.clone(),
                status: VerdictStatus::Inconclusive,
                evidence: vec![],
                contradiction_score: 0.5,
            },
            SpecVerdict {
                claim: c,
                status: VerdictStatus::Survived,
                evidence: vec![],
                contradiction_score: 0.0,
            },
        ];
        let s = FalsificationEngine::compute_summary(&verdicts);
        assert_eq!(s.inconclusive, 1);
        assert_eq!(s.survived, 1);
        // testable = 2 (0 unfalsifiable); survived/testable = 0.5.
        assert!((s.health_score - 0.5).abs() < f64::EPSILON);
    }

    // ── #956: the verdict must not depend on PATH ──

    /// REGRESSION (#956): every real check spawned a bare `pmat`, resolved
    /// through PATH. The verdict therefore came from whatever build happened to
    /// be installed — on the reporting machine, a *different, dirty* commit than
    /// the binary being asked — and disappeared entirely on a runner with no
    /// pmat installed.
    ///
    /// The fake `pmat` planted on PATH below answers every search with 999999
    /// occurrences. On the old code the absence check consumed that answer and
    /// returned a measured contradiction; the running build must ignore it.
    #[cfg(unix)]
    #[test]
    #[serial_test::serial]
    fn a_pmat_on_path_is_never_consulted() {
        use std::os::unix::fs::PermissionsExt;

        struct PathGuard(Option<std::ffi::OsString>);
        impl Drop for PathGuard {
            fn drop(&mut self) {
                match self.0.take() {
                    Some(old) => std::env::set_var("PATH", old),
                    None => std::env::remove_var("PATH"),
                }
            }
        }

        let dir = tempfile::tempdir().unwrap();
        let fake = dir.path().join("pmat");
        std::fs::write(&fake, "#!/bin/sh\necho 'src/lib.rs:999999'\nexit 0\n").unwrap();
        std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();

        let _guard = PathGuard(std::env::var_os("PATH"));
        std::env::set_var("PATH", dir.path());

        let engine = FalsificationEngine::new(dir.path());
        let claim = make_claim(
            "a",
            "The project MUST have zero unwrap() calls.",
            SpecClaimCategory::AbsenceClaim,
        );
        let evidence = engine.check_absence_claim(&claim);

        assert_eq!(evidence.len(), 1, "one search term: unwrap()");
        assert!(
            !evidence[0].measured,
            "an impostor `pmat` on PATH was consulted: {}",
            evidence[0].finding
        );
        assert!(
            !evidence[0].finding.contains("999999"),
            "evidence came from the PATH binary, not from this build: {}",
            evidence[0].finding
        );
        assert_eq!(
            engine.determine_verdict(&claim, &evidence),
            VerdictStatus::Inconclusive,
            "a check that did not run is inconclusive, never survived"
        );
    }

    /// The falsifier must ask the build that is running, not a name on PATH.
    /// Source-level pin: three call sites regressed to `Command::new("pmat")`
    /// once already, and each one flips a verdict when PATH changes.
    #[test]
    fn the_engine_spawns_only_its_own_executable() {
        let source = include_str!("spec_falsification_engine.rs");
        // Split so this probe cannot match its own text.
        let bare = concat!("Command::new(", "\"pmat\")");
        assert!(
            !source.contains(bare),
            "a bare `pmat` resolved through PATH makes the verdict machine-dependent"
        );
        assert!(source.contains("std::env::current_exe()"));
    }

    /// Under `cargo test` the running executable is a libtest harness, which
    /// cannot answer `pmat query`. Refusing is the honest outcome; spawning it
    /// anyway would let libtest's own `--help` masquerade as a pmat subcommand.
    #[test]
    fn self_exe_refuses_a_non_pmat_harness() {
        let resolved = FalsificationEngine::self_exe();
        let running = std::env::current_exe().unwrap();
        let stem = running.file_stem().and_then(|s| s.to_str()).unwrap_or("");
        if stem == "pmat" {
            assert!(resolved.is_ok());
        } else {
            let err = resolved.expect_err("a non-pmat executable must be refused");
            assert!(err.to_string().contains("not a pmat binary"), "{err}");
        }
    }
}