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
/// Format provability results as summary
///
/// # Example
///
/// ```no_run
/// use pmat::cli::provability_helpers::format_provability_summary;
/// use pmat::services::lightweight_provability_analyzer::{FunctionId, ProofSummary};
/// use std::path::PathBuf;
///
/// let function_ids = vec![
///     FunctionId {
///         file_path: "src/main.rs".to_string(),
///         function_name: "high_score_func".to_string(),
///         line_number: 10,
///     },
///     FunctionId {
///         file_path: "src/lib.rs".to_string(),
///         function_name: "low_score_func".to_string(),
///         line_number: 20,
///     },
/// ];
///
/// let summaries = vec![
///     ProofSummary {
///         provability_score: 0.9,
///         analysis_time_us: 1000,
///         verified_properties: vec![],
///         version: 1,
///     },
///     ProofSummary {
///         provability_score: 0.3,
///         analysis_time_us: 500,
///         verified_properties: vec![],
///         version: 1,
///     },
/// ];
///
/// let output = format_provability_summary(&function_ids, &summaries, 5).unwrap();
///
/// assert!(output.contains("Provability Analysis Summary"));
/// assert!(output.contains("Total functions analyzed:"));
/// assert!(output.contains("Top Files by Provability"));
/// ```
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub fn format_provability_summary(
    function_ids: &[FunctionId],
    summaries: &[ProofSummary],
    top_files: usize,
) -> Result<String> {
    let mut output = String::new();

    write_summary_header(&mut output, function_ids.len())?;
    write_scoring_model(&mut output)?;
    write_score_distribution(&mut output, summaries)?;
    write_property_coverage(&mut output, summaries)?;
    write_average_score(&mut output, summaries)?;
    write_lowest_scoring_functions(&mut output, function_ids, summaries, 10)?;
    write_top_files_section(&mut output, function_ids, summaries, top_files)?;

    Ok(output)
}

fn write_summary_header(output: &mut String, total_functions: usize) -> Result<()> {
    use crate::cli::colors as c;
    writeln!(output, "{}\n", c::header("Provability Analysis Summary"))?;
    writeln!(
        output,
        "Total functions analyzed: {}",
        c::number(&total_functions.to_string())
    )?;
    Ok(())
}

/// Explain the 4-factor scoring model so users understand what drives provability (#229).
fn write_scoring_model(output: &mut String) -> Result<()> {
    use crate::cli::colors as c;
    writeln!(
        output,
        "\n{}\n",
        c::subheader("Scoring Model (4 factors, equally weighted)")
    )?;
    writeln!(
        output,
        "  {}{:<14}{} {:<14} {:<14} 0%",
        c::seq(c::BOLD),
        "Factor",
        c::seq(c::RESET),
        "100%",
        "50%"
    )?;
    writeln!(output, "  {}", c::separator())?;
    writeln!(
        output,
        "  {:<14} {}NotNull{}       {}MaybeNull{}    {}Unknown/Null{}",
        "Nullability",
        c::seq(c::GREEN),
        c::seq(c::RESET),
        c::seq(c::YELLOW),
        c::seq(c::RESET),
        c::seq(c::RED),
        c::seq(c::RESET)
    )?;
    writeln!(
        output,
        "  {:<14} {}Both bounds{}   {}One bound{}    {}No bounds{}",
        "Bounds",
        c::seq(c::GREEN),
        c::seq(c::RESET),
        c::seq(c::YELLOW),
        c::seq(c::RESET),
        c::seq(c::RED),
        c::seq(c::RESET)
    )?;
    writeln!(
        output,
        "  {:<14} {}NoAlias{}       {:<14} {}MayAlias/Unknown{}",
        "Aliasing",
        c::seq(c::GREEN),
        c::seq(c::RESET),
        "-",
        c::seq(c::RED),
        c::seq(c::RESET)
    )?;
    writeln!(
        output,
        "  {:<14} {}Pure{}          {}ReadOnly(70){} {}WriteGlobal{}",
        "Purity",
        c::seq(c::GREEN),
        c::seq(c::RESET),
        c::seq(c::YELLOW),
        c::seq(c::RESET),
        c::seq(c::RED),
        c::seq(c::RESET)
    )?;
    Ok(())
}

/// Show aggregate property verification coverage across all functions (#229).
fn write_property_coverage(output: &mut String, summaries: &[ProofSummary]) -> Result<()> {
    use crate::services::lightweight_provability_analyzer::PropertyType;

    if summaries.is_empty() {
        return Ok(());
    }

    let total = summaries.len();
    let mut counts: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
    for name in &[
        "NullSafety",
        "BoundsCheck",
        "NoAliasing",
        "PureFunction",
        "MemorySafety",
        "ThreadSafety",
    ] {
        counts.insert(name, 0);
    }

    for s in summaries {
        for prop in &s.verified_properties {
            let key = match prop.property_type {
                PropertyType::NullSafety => "NullSafety",
                PropertyType::BoundsCheck => "BoundsCheck",
                PropertyType::NoAliasing => "NoAliasing",
                PropertyType::PureFunction => "PureFunction",
                PropertyType::MemorySafety => "MemorySafety",
                PropertyType::ThreadSafety => "ThreadSafety",
            };
            *counts.entry(key).or_default() += 1;
        }
    }

    use crate::cli::colors as c;
    writeln!(output, "\n{}\n", c::subheader("Verified Property Coverage"))?;
    for (name, count) in &counts {
        let pct_val = (*count as f64 / total as f64) * 100.0;
        writeln!(
            output,
            "  {}{}{}: {}/{} ({})",
            c::seq(c::BOLD),
            name,
            c::seq(c::RESET),
            c::number(&count.to_string()),
            c::number(&total.to_string()),
            c::pct(pct_val, 80.0, 50.0),
        )?;
    }
    Ok(())
}

/// Show the lowest-scoring functions with their verified properties (#229).
fn write_lowest_scoring_functions(
    output: &mut String,
    function_ids: &[FunctionId],
    summaries: &[ProofSummary],
    limit: usize,
) -> Result<()> {
    if function_ids.is_empty() {
        return Ok(());
    }

    let mut indexed: Vec<(usize, f64)> = summaries
        .iter()
        .enumerate()
        .map(|(i, s)| (i, s.provability_score))
        .collect();
    indexed.sort_by(|a, b| a.1.total_cmp(&b.1));

    use crate::cli::colors as c;
    writeln!(output, "\n{}\n", c::subheader("Lowest Scoring Functions"))?;
    for (idx, score_val) in indexed.iter().take(limit) {
        let func = &function_ids[*idx];
        let summary = &summaries[*idx];
        // Basename only ("mod.rs") does not identify a file in a tree with
        // hundreds of them; print the path the analyzer keyed the score by.
        let filename = crate::cli::report_paths::report_path(&func.file_path);
        let props: Vec<String> = summary
            .verified_properties
            .iter()
            .map(|p| format!("{:?}({:.0}%)", p.property_type, p.confidence * 100.0))
            .collect();
        let props_str = if props.is_empty() {
            format!("{}none verified{}", c::seq(c::DIM), c::seq(c::RESET))
        } else {
            props.join(", ")
        };
        writeln!(
            output,
            "  {} ({}:{}) \u{2014} {} \u{2014} verified: {props_str}",
            c::label(&func.function_name),
            c::path(filename),
            c::number(&func.line_number.to_string()),
            c::pct(score_val * 100.0, 80.0, 50.0),
        )?;
    }
    Ok(())
}

fn write_score_distribution(output: &mut String, summaries: &[ProofSummary]) -> Result<()> {
    use crate::cli::colors as c;
    let (high_count, medium_count, low_count) = categorize_scores(summaries);

    writeln!(output, "\n{}", c::subheader("Score Distribution:"))?;
    writeln!(
        output,
        "  {}High{} ({}\u{2265}80%{}): {} functions",
        c::seq(c::GREEN),
        c::seq(c::RESET),
        c::seq(c::GREEN),
        c::seq(c::RESET),
        c::number(&high_count.to_string())
    )?;
    writeln!(
        output,
        "  {}Medium{} ({}50-79%{}): {} functions",
        c::seq(c::YELLOW),
        c::seq(c::RESET),
        c::seq(c::YELLOW),
        c::seq(c::RESET),
        c::number(&medium_count.to_string())
    )?;
    writeln!(
        output,
        "  {}Low{} ({}<50%{}): {} functions",
        c::seq(c::RED),
        c::seq(c::RESET),
        c::seq(c::RED),
        c::seq(c::RESET),
        c::number(&low_count.to_string())
    )?;

    Ok(())
}

fn write_average_score(output: &mut String, summaries: &[ProofSummary]) -> Result<()> {
    use crate::cli::colors as c;
    let avg_score = calculate_average_score(summaries);
    writeln!(
        output,
        "\nAverage provability score: {}",
        c::pct(avg_score * 100.0, 80.0, 50.0)
    )?;
    Ok(())
}

fn write_top_files_section(
    output: &mut String,
    function_ids: &[FunctionId],
    summaries: &[ProofSummary],
    top_files: usize,
) -> Result<()> {
    if function_ids.is_empty() {
        return Ok(());
    }

    use crate::cli::colors as c;
    writeln!(output, "\n{}\n", c::subheader("Top Files by Provability"))?;
    let file_avg_scores = calculate_file_averages(function_ids, summaries);
    write_top_files_list(output, &file_avg_scores, top_files)?;

    Ok(())
}

fn calculate_file_averages<'a>(
    function_ids: &'a [FunctionId],
    summaries: &'a [ProofSummary],
) -> Vec<(&'a str, f64, usize)> {
    let mut file_scores: HashMap<&str, Vec<f64>> = HashMap::new();

    for (func_id, summary) in function_ids.iter().zip(summaries.iter()) {
        file_scores
            .entry(&func_id.file_path)
            .or_default()
            .push(summary.provability_score);
    }

    let mut file_avg_scores: Vec<_> = file_scores
        .iter()
        .map(|(file_path, scores)| {
            let avg_score = scores.iter().sum::<f64>() / scores.len() as f64;
            (*file_path, avg_score, scores.len())
        })
        .collect();

    // DETERMINISM (round-3 sweep): the average score is not a total order —
    // two files can score identically, and on a small tree they usually do —
    // and the ranking is built from a `HashMap`, so `.take(n)` printed
    // "1. b.rs / 2. a.rs" on one run and "1. a.rs / 2. b.rs" on the next for
    // byte-identical input. Path breaks the tie.
    file_avg_scores.sort_by(|a, b| {
        b.1.partial_cmp(&a.1)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.0.cmp(b.0))
    });
    file_avg_scores
}

fn write_top_files_list(
    output: &mut String,
    file_avg_scores: &[(&str, f64, usize)],
    top_files: usize,
) -> Result<()> {
    use crate::cli::colors as c;
    // `--help` documents `--top-files <N>` as "0 = all", but 0 was remapped to
    // the default 10 here, so asking for every file silently truncated the
    // ranking at ten and the dropped files were never mentioned. The rule has
    // one implementation now: `crate::cli::top_files_slice`.
    for (i, (file_path, avg_score, function_count)) in
        crate::cli::top_files_slice(file_avg_scores, top_files)
            .iter()
            .enumerate()
    {
        let filename = crate::cli::report_paths::report_path(file_path);
        writeln!(
            output,
            "  {}. {} - {} avg score ({} functions)",
            c::number(&(i + 1).to_string()),
            c::path(filename),
            c::pct(avg_score * 100.0, 80.0, 50.0),
            c::number(&function_count.to_string()),
        )?;
    }

    Ok(())
}

#[cfg(test)]
mod plain_output_tests {
    //! `--color never`, `NO_COLOR=1` and a redirected stdout all left 17
    //! escape-bearing lines in `analyze provability`'s summary: the renderer
    //! interpolated the raw `pub const` sequences, which are `const` and so
    //! cannot consult `colors_enabled()`. Only `--color always` differed —
    //! i.e. the flag parsed and only its "always" branch did anything.
    use super::*;
    use crate::services::lightweight_provability_analyzer::{FunctionId, ProofSummary};

    fn fixture() -> (Vec<FunctionId>, Vec<ProofSummary>) {
        let ids = vec![
            FunctionId {
                file_path: "src/main.rs".to_string(),
                function_name: "high".to_string(),
                line_number: 10,
            },
            FunctionId {
                file_path: "src/lib.rs".to_string(),
                function_name: "low".to_string(),
                line_number: 20,
            },
        ];
        let summaries = vec![
            ProofSummary {
                provability_score: 0.9,
                analysis_time_us: 1000,
                verified_properties: vec![],
                version: 1,
            },
            ProofSummary {
                provability_score: 0.3,
                analysis_time_us: 500,
                verified_properties: vec![],
                version: 1,
            },
        ];
        (ids, summaries)
    }

    #[test]
    fn summary_is_plain_text_when_colour_is_disabled() {
        assert!(
            !crate::cli::colors::colors_enabled(),
            "cargo test captures stdout, so colour must resolve to off here"
        );

        let (ids, summaries) = fixture();
        let rendered = format_provability_summary(&ids, &summaries, 5).expect("render");

        assert!(
            !rendered.contains('\u{1b}'),
            "no ANSI escape may reach a redirected stdout: {:?}",
            rendered
                .lines()
                .filter(|l| l.contains('\u{1b}'))
                .collect::<Vec<_>>()
        );
        // The payload must survive the de-colouring.
        assert!(rendered.contains("Provability Analysis Summary"));
        assert!(rendered.contains("Scoring Model"));
        assert!(rendered.contains("Score Distribution"));
        assert!(rendered.contains("Top Files by Provability"));
    }

    /// `--top-files` documents "0 = all", but 0 was remapped to the default 10,
    /// so every file past the tenth vanished from the ranking with no notice.
    #[test]
    fn top_files_zero_lists_every_file_not_the_default_ten() {
        let ids: Vec<FunctionId> = (0..12)
            .map(|i| FunctionId {
                file_path: format!("src/f{i:02}.rs"),
                function_name: format!("f{i}"),
                line_number: i + 1,
            })
            .collect();
        let summaries: Vec<ProofSummary> = (0..12)
            .map(|i| ProofSummary {
                provability_score: f64::from(i) / 100.0,
                analysis_time_us: 1,
                verified_properties: vec![],
                version: 1,
            })
            .collect();

        let rendered = format_provability_summary(&ids, &summaries, 0).expect("render");
        let listed = rendered.lines().filter(|l| l.contains("avg score")).count();
        assert_eq!(
            listed, 12,
            "--top-files 0 must list all 12 files, not truncate to the default: {rendered}"
        );
        assert!(
            rendered.contains("f11.rs"),
            "the eleventh-ranked file was dropped: {rendered}"
        );
    }
}