aprender-contracts 0.68.1

Papers to Math to Contracts in Code — YAML contract parsing, validation, scaffold generation, and Kani harness codegen for provable Rust kernels
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
//! Gate implementations: validate, audit, score.
//!
//! Each gate runs a specific quality check and returns a `GateResult`
//! plus a list of `LintFinding`s for downstream rendering.
//!
//! Extended gates (verify, enforce) are in `gates_extended.rs`.

use std::path::Path;
use std::time::Instant;

use crate::audit::audit_contract;
use crate::binding::{parse_binding, BindingRegistry};
use crate::error::Severity;
use crate::schema::{is_contract_yaml, parse_contract, validate_contract, Contract};
use crate::scoring::{score_contract, ContractScore};

use super::finding::LintFinding;
use super::rules::RuleSeverity;
use super::{GateDetail, GateResult};

/// Load and parse all YAML contracts from a directory.
///
/// Returns successfully parsed contracts and a list of parse errors.
#[allow(clippy::type_complexity)]
pub(crate) fn load_contracts(dir: &Path) -> (Vec<(String, Contract)>, Vec<(String, String)>) {
    let mut contracts = Vec::new();
    let mut parse_errors = Vec::new();
    let mut yaml_paths = Vec::new();
    if dir.is_file() {
        // PVL-1 (PMAT-1099): `pv lint <file>` lints THAT file. Before this, a file
        // path was walked with `read_dir`, found nothing, and reported PASS over
        // 0 contracts.
        yaml_paths.push(dir.to_path_buf());
    } else {
        collect_yaml_files(dir, &mut yaml_paths);
    }
    // DETERMINISM: `read_dir` order is unspecified (on ext4 it is a filename-hash
    // order, so it changes when a DIRECTORY IS RENAMED even though no file content
    // changed). Sorting by full path imposes a total order, so everything derived
    // from `yaml_paths` — finding order, per-contract timings, and the order two
    // files sharing a stem are seen in — is a function of the tree's contents only.
    //
    // This alone does NOT make a duplicate stem safe to collapse: the sort key still
    // contains the directory name, so a rename still permutes which copy comes last.
    // Collapsing is handled by refusing ambiguous stems — see `duplicate_stems.rs`.
    yaml_paths.sort();

    for path in &yaml_paths {
        let stem = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
            .to_string();
        match parse_contract(path) {
            Ok(c) => contracts.push((stem, c)),
            Err(e) => parse_errors.push((stem, e.to_string())),
        }
    }
    contracts.sort_by(|a, b| a.0.cmp(&b.0));
    (contracts, parse_errors)
}

/// Recursively collect `.yaml` contract files, skipping non-contract directories.
///
/// Emits entries in `read_dir` order, which is UNSPECIFIED. Every caller must
/// impose its own total order before deriving a verdict from the result.
pub fn collect_yaml_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            let dirname = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
            // `publish-manifests/` holds PublishManifest artifacts (model
            // ship metadata keyed by `model_id:`), not Contract schemas;
            // validating them here would fail on missing `metadata.` root.
            if matches!(
                dirname,
                // `quarantine/` holds contracts ONT-001 ONT-1 pulled OUT of the
                // corpus precisely because they do not parse; walking them would
                // make every gate reject on the files quarantine exists to hold.
                "kaizen" | "legacy" | "pipelines" | "publish-manifests" | "quarantine"
            ) {
                continue;
            }
            collect_yaml_files(&path, out);
        } else if is_contract_yaml(&path) {
            out.push(path);
        }
    }
}

/// Load binding registry from an optional path.
pub(crate) fn load_binding(path: Option<&Path>) -> Option<BindingRegistry> {
    path.and_then(|p| parse_binding(p).ok())
}

pub(crate) fn run_validate_gate(
    contracts: &[(String, Contract)],
    parse_errors: &[(String, String)],
) -> (GateResult, Vec<LintFinding>) {
    let start = Instant::now();
    let mut total_errors = 0usize;
    let mut total_warnings = 0usize;
    let mut error_messages = Vec::new();
    let mut findings = Vec::new();

    for (stem, err) in parse_errors {
        total_errors += 1;
        error_messages.push(format!("Parse error: {err} ({stem}.yaml)"));
        findings.push(
            LintFinding::new(
                "PV-VAL-001",
                RuleSeverity::Error,
                format!("YAML parse error: {err}"),
                format!("contracts/{stem}.yaml"),
            )
            .with_stem(stem.clone()),
        );
    }

    for (stem, contract) in contracts {
        let violations = validate_contract(contract);
        for v in &violations {
            let sev = match v.severity {
                Severity::Error => {
                    total_errors += 1;
                    error_messages.push(format!("{v} ({stem})"));
                    RuleSeverity::Error
                }
                Severity::Warning => {
                    total_warnings += 1;
                    RuleSeverity::Warning
                }
                Severity::Info => RuleSeverity::Info,
            };
            let rule_id = map_validation_rule(&v.rule);
            findings.push(
                LintFinding::new(
                    rule_id,
                    sev,
                    format!("{}: {}", v.rule, v.message),
                    format!("contracts/{stem}.yaml"),
                )
                .with_stem(stem.clone()),
            );
        }
    }

    let result = GateResult {
        name: "validate".into(),
        passed: total_errors == 0,
        skipped: false,
        duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
        detail: GateDetail::Validate {
            contracts: contracts.len() + parse_errors.len(),
            errors: total_errors,
            warnings: total_warnings,
            error_messages,
        },
        extra: None,
    };
    (result, findings)
}

pub(crate) fn run_audit_gate(contracts: &[(String, Contract)]) -> (GateResult, Vec<LintFinding>) {
    let start = Instant::now();
    let mut total_findings = 0usize;
    let mut finding_messages = Vec::new();
    let mut findings = Vec::new();

    for (stem, contract) in contracts {
        let report = audit_contract(contract);
        for v in &report.violations {
            let sev = match v.severity {
                Severity::Error => {
                    total_findings += 1;
                    finding_messages.push(format!("{v} ({stem})"));
                    RuleSeverity::Error
                }
                Severity::Warning => RuleSeverity::Warning,
                Severity::Info => RuleSeverity::Info,
            };
            let rule_id = map_audit_rule(&v.rule);
            findings.push(
                LintFinding::new(
                    rule_id,
                    sev,
                    format!("{}: {}", v.rule, v.message),
                    format!("contracts/{stem}.yaml"),
                )
                .with_stem(stem.clone()),
            );
        }
    }

    let result = GateResult {
        name: "audit".into(),
        passed: total_findings == 0,
        skipped: false,
        duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
        detail: GateDetail::Audit {
            contracts: contracts.len(),
            findings: total_findings,
            finding_messages,
        },
        extra: None,
    };
    (result, findings)
}

#[allow(clippy::cast_precision_loss)]
pub(crate) fn run_score_gate(
    contracts: &[(String, Contract)],
    binding: Option<&BindingRegistry>,
    threshold: f64,
) -> (GateResult, Vec<LintFinding>) {
    let start = Instant::now();
    let mut scores: Vec<ContractScore> = Vec::new();
    let mut below_threshold = Vec::new();
    let mut findings = Vec::new();

    for (stem, contract) in contracts {
        let s = score_contract(contract, binding, stem);
        if s.composite < threshold {
            below_threshold.push(format!(
                "{} — {:.2} (Grade {}, threshold {:.2})",
                stem, s.composite, s.grade, threshold
            ));
            findings.push(
                LintFinding::new(
                    "PV-SCR-001",
                    RuleSeverity::Error,
                    format!(
                        "Score {:.2} (Grade {}) below threshold {:.2}",
                        s.composite, s.grade, threshold
                    ),
                    format!("contracts/{stem}.yaml"),
                )
                .with_stem(stem.clone())
                .with_evidence(format!(
                    "spec={:.2} falsify={:.2} kani={:.2} lean={:.2} bind={:.2}",
                    s.spec_depth,
                    s.falsification_coverage,
                    s.kani_coverage,
                    s.lean_coverage,
                    s.binding_coverage
                )),
            );
        }
        scores.push(s);
    }

    let min_score = scores
        .iter()
        .map(|s| s.composite)
        .fold(f64::INFINITY, f64::min);
    let mean_score = if scores.is_empty() {
        0.0
    } else {
        scores.iter().map(|s| s.composite).sum::<f64>() / scores.len() as f64
    };

    let passed = below_threshold.is_empty();

    let result = GateResult {
        name: "score".into(),
        passed,
        skipped: false,
        duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
        detail: GateDetail::Score {
            contracts: contracts.len(),
            min_score: if scores.is_empty() { 0.0 } else { min_score },
            mean_score,
            threshold,
            below_threshold,
        },
        extra: None,
    };
    (result, findings)
}

/// Map existing validation rule IDs to PV-VAL-NNN catalog IDs.
fn map_validation_rule(rule: &str) -> String {
    match rule {
        "PROVABILITY-001" => "PV-PRV-001".into(),
        r if r.starts_with("SCHEMA-") => match r {
            "SCHEMA-004" => "PV-VAL-004".into(),
            "SCHEMA-005" => "PV-VAL-005".into(),
            "SCHEMA-006" => "PV-VAL-006".into(),
            _ => "PV-VAL-001".into(),
        },
        _ => "PV-VAL-001".into(),
    }
}

/// Map existing audit rule IDs to PV-AUD-NNN catalog IDs.
fn map_audit_rule(rule: &str) -> String {
    if rule.contains("paper") || rule.contains("reference") {
        "PV-AUD-002".into()
    } else if rule.contains("test") || rule.contains("falsification") {
        "PV-AUD-001".into()
    } else if rule.contains("domain") {
        "PV-AUD-004".into()
    } else if rule.contains("tolerance") {
        "PV-AUD-005".into()
    } else {
        "PV-AUD-003".into()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn contracts_dir() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contracts")
    }

    #[test]
    fn load_contracts_real() {
        let (contracts, errors) = load_contracts(&contracts_dir());
        assert!(contracts.len() > 100, "Expected 100+ contracts");
        assert!(errors.is_empty(), "No parse errors expected: {errors:?}");
    }

    #[test]
    fn load_contracts_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let (contracts, errors) = load_contracts(tmp.path());
        assert!(contracts.is_empty());
        assert!(errors.is_empty());
    }

    #[test]
    fn load_contracts_reports_parse_errors() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("bad.yaml"), "not: valid: yaml: {{{{").unwrap();
        let (contracts, errors) = load_contracts(tmp.path());
        assert!(contracts.is_empty());
        assert_eq!(errors.len(), 1);
        assert_eq!(errors[0].0, "bad");
    }

    #[test]
    fn validate_gate_fails_on_parse_errors() {
        let parse_errors = vec![("bad".into(), "invalid YAML".into())];
        let (result, findings) = run_validate_gate(&[], &parse_errors);
        assert!(!result.passed);
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "PV-VAL-001");
        assert!(findings[0].message.contains("parse error"));
    }

    #[test]
    fn validate_gate_passes() {
        let (contracts, errors) = load_contracts(&contracts_dir());
        let (result, _findings) = run_validate_gate(&contracts, &errors);
        assert!(result.passed);
    }

    #[test]
    fn audit_gate_passes() {
        let (contracts, _) = load_contracts(&contracts_dir());
        let (result, _findings) = run_audit_gate(&contracts);
        assert!(result.passed);
    }

    #[test]
    fn score_gate_passes_zero_threshold() {
        let (contracts, _) = load_contracts(&contracts_dir());
        let (result, findings) = run_score_gate(&contracts, None, 0.0);
        assert!(result.passed);
        assert!(findings.is_empty());
    }

    #[test]
    fn score_gate_fails_high_threshold() {
        let (contracts, _) = load_contracts(&contracts_dir());
        let (result, findings) = run_score_gate(&contracts, None, 0.99);
        assert!(!result.passed);
        assert!(!findings.is_empty());
        assert!(findings.iter().all(|f| f.rule_id == "PV-SCR-001"));
    }

    #[test]
    fn map_validation_rules() {
        assert_eq!(map_validation_rule("PROVABILITY-001"), "PV-PRV-001");
        assert_eq!(map_validation_rule("SCHEMA-001"), "PV-VAL-001");
        assert_eq!(map_validation_rule("SCHEMA-004"), "PV-VAL-004");
        assert_eq!(map_validation_rule("SCHEMA-005"), "PV-VAL-005");
        assert_eq!(map_validation_rule("SCHEMA-006"), "PV-VAL-006");
        assert_eq!(map_validation_rule("SCHEMA-999"), "PV-VAL-001");
        assert_eq!(map_validation_rule("UNKNOWN"), "PV-VAL-001");
    }

    #[test]
    fn map_audit_rules() {
        assert_eq!(map_audit_rule("missing paper reference"), "PV-AUD-002");
        assert_eq!(map_audit_rule("no falsification test"), "PV-AUD-001");
        assert_eq!(map_audit_rule("missing domain"), "PV-AUD-004");
        assert_eq!(map_audit_rule("no tolerance"), "PV-AUD-005");
        assert_eq!(map_audit_rule("other issue"), "PV-AUD-003");
    }
}