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
437
#![cfg_attr(coverage_nightly, coverage(off))]
// Red Team Mode CLI Handler
//
// Implements hallucination detection for commit messages, documentation, and code comments
// Based on specification: docs/specifications/red-team-mode-spec.md v1.1

use crate::cli::progress::MultiStageProgress;
use crate::red_team::{
    Claim, ClaimExtractor, CommitInfo, EvidenceGatherer, EvidenceResult, IntentClassifier,
    RepositoryContext,
};
use anyhow::Context;
use clap::{Parser, Subcommand, ValueEnum};
use std::fmt;
use std::path::PathBuf;
use std::process::ExitCode;

/// Red Team Mode handler result
#[derive(Debug)]
pub struct RedTeamResult {
    pub commit_message: String,
    pub claims: Vec<Claim>,
    pub evidence_per_claim: Vec<Vec<EvidenceResult>>,
    pub hallucinations_detected: bool,
    pub confidence: f64,
}

impl RedTeamResult {
    /// Format as human-readable text report
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn format_text(&self) -> String {
        let mut output = String::new();

        if self.claims.is_empty() {
            output.push_str("โœ… No testable claims found\n\n");
            output.push_str(&format!("Commit message: \"{}\"\n", self.commit_message));
            output.push_str("\nThis commit message makes no absolute or testable claims.\n");
            output.push_str("No hallucination detection needed.\n");
            return output;
        }

        if !self.hallucinations_detected {
            output.push_str("โœ… All claims verified\n\n");
            output.push_str(&format!("Commit message: \"{}\"\n\n", self.commit_message));
            output.push_str(&format!("Found {} testable claim(s):\n", self.claims.len()));

            for claim in &self.claims {
                output.push_str(&format!("  โ€ข {}\n", claim.text));
            }

            output.push_str("\nAll claims are supported by evidence.\n");
            return output;
        }

        // Hallucination detected
        output.push_str("๐Ÿ”ด HALLUCINATION DETECTED\n\n");
        output.push_str(&format!("Commit message: \"{}\"\n\n", self.commit_message));
        output.push_str(&format!("Confidence: {:.2}\n\n", self.confidence));

        for (i, claim) in self.claims.iter().enumerate() {
            let evidence = &self.evidence_per_claim[i];
            let contradicting: Vec<_> = evidence.iter().filter(|e| !e.supports_claim).collect();

            if contradicting.is_empty() {
                continue;
            }

            output.push_str(&format!("Claim {}: \"{}\"\n", i + 1, claim.text));
            output.push_str(&format!("  Category: {:?}\n", claim.category));
            output.push_str(&format!("  Absolute: {}\n\n", claim.is_absolute));

            output.push_str("  Contradicting Evidence:\n");
            for (j, e) in contradicting.iter().enumerate() {
                output.push_str(&format!(
                    "    {}. {:?}: {} (confidence: {:.2})\n",
                    j + 1,
                    e.source,
                    e.details,
                    e.confidence
                ));
            }
            output.push('\n');
        }

        output.push_str("Verdict: POTENTIAL HALLUCINATION\n");
        output.push_str("\nRemediation:\n");
        output.push_str("  1. Run validation tests before committing\n");
        output.push_str("  2. Update commit message to reflect actual state\n");
        output.push_str(
            "  3. Use qualified language (\"MVP\", \"Phase 1\", etc.) for incremental work\n",
        );

        output
    }

    /// Format as JSON
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn format_json(&self) -> serde_json::Value {
        serde_json::json!({
            "commit_message": self.commit_message,
            "claims": self.claims.iter().map(|c| {
                serde_json::json!({
                    "text": c.text,
                    "category": format!("{:?}", c.category),
                    "is_absolute": c.is_absolute,
                    "numeric_value": c.numeric_value,
                    "has_scope_qualifier": c.has_scope_qualifier,
                })
            }).collect::<Vec<_>>(),
            "evidence": self.evidence_per_claim.iter().map(|evidence_list| {
                evidence_list.iter().map(|e| {
                    serde_json::json!({
                        "source": format!("{:?}", e.source),
                        "supports_claim": e.supports_claim,
                        "confidence": e.confidence,
                        "details": e.details,
                        "timestamp": e.timestamp,
                    })
                }).collect::<Vec<_>>()
            }).collect::<Vec<_>>(),
            "hallucinations_detected": self.hallucinations_detected,
            "confidence": self.confidence,
        })
    }
}

impl fmt::Display for RedTeamResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.format_text())
    }
}

/// Red Team Mode handler
pub struct RedTeamHandler {
    extractor: ClaimExtractor,
    gatherer: EvidenceGatherer,
    classifier: IntentClassifier,
}

impl RedTeamHandler {
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    /// Create a new instance.
    pub fn new() -> Self {
        Self {
            extractor: ClaimExtractor::new(),
            gatherer: EvidenceGatherer::new(),
            classifier: IntentClassifier::new(),
        }
    }

    /// Analyze a commit message for hallucinations
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn analyze_commit_message(
        &self,
        commit_message: &str,
        context: &RepositoryContext,
    ) -> RedTeamResult {
        debug_assert!(
            !commit_message.is_empty(),
            "commit_message must not be empty"
        );
        // Step 1: Extract claims
        let claims = self.extractor.extract(commit_message);

        if claims.is_empty() {
            return RedTeamResult {
                commit_message: commit_message.to_string(),
                claims: vec![],
                evidence_per_claim: vec![],
                hallucinations_detected: false,
                confidence: 0.0,
            };
        }

        // Step 2: Gather evidence for each claim
        let mut evidence_per_claim = Vec::new();
        let mut any_hallucination = false;
        let mut max_contradiction_confidence: f64 = 0.0;

        for claim in &claims {
            let evidence = self.gatherer.gather_evidence(claim, context);

            // Check if any evidence contradicts the claim
            let contradicting = evidence
                .iter()
                .filter(|e| !e.supports_claim)
                .collect::<Vec<_>>();

            if !contradicting.is_empty() {
                any_hallucination = true;
                for e in &contradicting {
                    max_contradiction_confidence = max_contradiction_confidence.max(e.confidence);
                }
            }

            evidence_per_claim.push(evidence);
        }

        RedTeamResult {
            commit_message: commit_message.to_string(),
            claims,
            evidence_per_claim,
            hallucinations_detected: any_hallucination,
            confidence: max_contradiction_confidence,
        }
    }

    /// Analyze a pair of commits to classify intent
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn analyze_commit_pair(
        &self,
        original: &CommitInfo,
        followup: &CommitInfo,
    ) -> crate::red_team::IntentClassification {
        self.classifier.classify(original, followup)
    }
}

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

/// Output format for Red Team analysis
#[derive(Debug, Clone, ValueEnum)]
pub enum RedTeamOutputFormat {
    /// Human-readable text output
    Text,
    /// JSON output for programmatic consumption
    Json,
}

/// Red Team subcommands
#[derive(Subcommand, Debug)]
pub enum RedTeamCommands {
    /// Analyze a commit message for hallucinations
    Analyze {
        /// Commit message to analyze
        #[arg(short, long, required = true)]
        message: String,

        /// Project path (defaults to current directory)
        #[arg(short, long, default_value = ".")]
        path: PathBuf,

        /// Output format (text or json)
        #[arg(short = 'f', long, default_value = "text")]
        format: RedTeamOutputFormat,

        /// Verbose output
        #[arg(short, long)]
        verbose: bool,

        /// Deep scan: Check entire git history (slower but more thorough)
        /// Default: false (scan recent commits only - last 30 days)
        #[arg(short = 'd', long)]
        deep: bool,
    },
}

/// Red Team Mode CLI command
///
/// # Example
///
/// ```bash
/// # Analyze a commit message
/// pmat red-team analyze --message "feat: All tests passing"
///
/// # Analyze with JSON output
/// pmat red-team analyze --message "test: Coverage at 85%" --format json
/// ```
#[derive(Parser, Debug)]
pub struct RedTeamCmd {
    #[command(subcommand)]
    pub command: RedTeamCommands,
}

impl RedTeamCmd {
    /// Execute the red-team command
    #[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
    pub fn execute(&self) -> anyhow::Result<ExitCode> {
        match &self.command {
            RedTeamCommands::Analyze {
                message,
                path,
                format,
                verbose,
                deep,
            } => {
                if *verbose {
                    eprintln!("๐Ÿ”ด Red Team Mode: Analyzing commit message");
                    eprintln!("๐Ÿ“ Message: {}", message);
                    eprintln!("๐Ÿ“ Repository: {}", path.display());
                    eprintln!(
                        "๐Ÿ” Scan mode: {}",
                        if *deep {
                            "Deep (entire git history)"
                        } else {
                            "Fast (recent commits only)"
                        }
                    );
                }

                // Initialize progress indicator (only for text output)
                let show_progress = matches!(format, RedTeamOutputFormat::Text);
                let mut progress = if show_progress {
                    let stages = vec![
                        "Building repository context".to_string(),
                        "Extracting claims".to_string(),
                        "Gathering evidence".to_string(),
                        "Analyzing results".to_string(),
                    ];
                    Some(MultiStageProgress::new(stages))
                } else {
                    None
                };

                // Stage 1: Build repository context
                if let Some(ref mut p) = progress {
                    p.next_stage("Building repository context");
                }

                let handler = RedTeamHandler::new();
                let context = RepositoryContext::from_path_with_config(path, *deep)
                    .context("Failed to build repository context")?;

                if *verbose {
                    eprintln!(
                        "๐Ÿ“Š Git history: {}",
                        if context.has_git_history() {
                            "โœ… Found"
                        } else {
                            "โš ๏ธ  None"
                        }
                    );
                    eprintln!("๐Ÿงช Test files: {} found", context.get_test_files().len());
                    eprintln!(
                        "๐Ÿ“ˆ Coverage report: {}",
                        if context.has_coverage_report() {
                            "โœ… Found"
                        } else {
                            "โš ๏ธ  None"
                        }
                    );
                }

                // Stage 2: Extract claims
                if let Some(ref mut p) = progress {
                    p.next_stage("Extracting claims");
                }

                let result = handler.analyze_commit_message(message, &context);

                // Stage 3: Analysis complete
                if let Some(ref mut p) = progress {
                    p.next_stage("Analyzing results");
                }

                // Clear progress before output
                if let Some(p) = progress {
                    p.finish("Analysis complete");
                }

                match format {
                    RedTeamOutputFormat::Text => {
                        println!("{}", result.format_text());
                    }
                    RedTeamOutputFormat::Json => {
                        println!("{}", serde_json::to_string_pretty(&result.format_json())?);
                    }
                }

                // Exit with error if hallucinations detected
                if result.hallucinations_detected {
                    Ok(ExitCode::from(1))
                } else {
                    Ok(ExitCode::SUCCESS)
                }
            }
        }
    }
}

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

    #[test]
    fn test_handler_no_claims() {
        let handler = RedTeamHandler::new();
        let context = RepositoryContext::new_mock();

        let result = handler.analyze_commit_message("refactor: Improve code style", &context);

        assert_eq!(result.claims.len(), 0);
        assert!(!result.hallucinations_detected);
    }

    #[test]
    fn test_handler_with_hallucination() {
        let handler = RedTeamHandler::new();
        let context = RepositoryContext::new_mock().with_test_results(true, 5);

        let result = handler.analyze_commit_message("feat: All tests passing", &context);

        assert_eq!(result.claims.len(), 1);
        assert!(result.hallucinations_detected);
        assert!(result.confidence > 0.0);
    }

    #[test]
    fn test_handler_format_text() {
        let handler = RedTeamHandler::new();
        let context = RepositoryContext::new_mock().with_test_results(true, 5);

        let result = handler.analyze_commit_message("feat: All tests passing", &context);

        let text = result.format_text();
        assert!(text.contains("HALLUCINATION DETECTED"));
        assert!(text.contains("All tests passing"));
        assert!(text.contains("Contradicting Evidence"));
    }

    #[test]
    fn test_handler_format_json() {
        let handler = RedTeamHandler::new();
        let context = RepositoryContext::new_mock();

        let result = handler.analyze_commit_message("test: Add new tests", &context);

        let json = result.format_json();
        assert_eq!(json["commit_message"], "test: Add new tests");
        assert_eq!(json["hallucinations_detected"], false);
    }
}