aprender-contracts 0.69.2

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
use super::*;

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

#[test]
fn lint_passes_on_real_contracts() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.0);
    let report = run_lint(&config);
    assert!(report.passed, "lint should pass: {report:?}");
    // 12 gates: validate, audit, score, verify, enforce, enforcement-level, reverse-coverage,
    // duplicate-stems (PV-DUP-001), composition, sigma (ONT-2b), relations (ONT-4), shapes (ONT-4b).
    assert_eq!(report.gates.len(), 12);
}

#[test]
fn lint_score_gate_fails_with_high_threshold() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.99);
    let report = run_lint(&config);
    assert!(!report.passed);
    assert!(!report.findings.is_empty());
}

#[test]
fn lint_empty_dir() {
    let tmp = tempfile::tempdir().unwrap();
    let config = LintConfig::new(tmp.path(), None, 0.0);
    let report = run_lint(&config);
    assert!(report.passed);
}

#[test]
fn lint_report_serializes_to_json() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.0);
    let report = run_lint(&config);
    let json = serde_json::to_string_pretty(&report).unwrap();
    assert!(json.contains("\"passed\""));
}

#[test]
fn gate_detail_variants() {
    let skipped = GateDetail::Skipped {
        reason: "test".into(),
    };
    let json = serde_json::to_string(&skipped).unwrap();
    assert!(json.contains("skipped"));
}

#[test]
fn lint_findings_on_failure() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.99);
    let report = run_lint(&config);
    assert!(report.findings.iter().any(|f| f.rule_id == "PV-SCR-001"));
}

#[test]
fn lint_severity_filter() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.99);
    config.severity_filter = Some(RuleSeverity::Error);
    let report = run_lint(&config);
    assert!(report
        .findings
        .iter()
        .all(|f| f.severity >= RuleSeverity::Error));
}

#[test]
fn lint_suppression_by_rule() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.99);
    config.suppressed_rules = vec!["PV-SCR-001".into()];
    let report = run_lint(&config);
    for f in &report.findings {
        if f.rule_id == "PV-SCR-001" {
            assert!(f.suppressed);
        }
    }
}

#[test]
fn lint_strict_mode() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.0);
    config.strict = true;
    let report = run_lint(&config);
    for f in &report.findings {
        assert_ne!(f.severity, RuleSeverity::Warning);
    }
}

#[test]
fn lint_sarif_output() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.99);
    let report = run_lint(&config);
    let sarif_log = sarif::findings_to_sarif(&report.findings, "0.1.0");
    let json = sarif::sarif_to_json(&sarif_log, true);
    assert!(json.contains("sarif-schema-2.1.0"));
    assert!(json.contains("PV-SCR-001"));
}

#[test]
fn skipped_gate_creates_correct_result() {
    let g = skipped_gate("test", "reason");
    assert_eq!(g.name, "test");
    assert!(!g.passed);
    assert!(g.skipped);
}

#[test]
fn lint_cache_populates_stats() {
    let dir = contracts_dir();
    let config = LintConfig::new(&dir, None, 0.0);
    let report = run_lint(&config);
    // Default config has cache enabled, so stats should be populated
    assert!(report.cache_stats.total > 0);
    assert_eq!(
        report.cache_stats.total,
        report.cache_stats.hits + report.cache_stats.misses
    );
}

#[test]
fn lint_no_cache_skips_stats() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.0);
    config.no_cache = true;
    let report = run_lint(&config);
    assert_eq!(report.cache_stats.total, 0);
}

#[test]
fn lint_cache_second_run_hits() {
    let tmp = tempfile::tempdir().unwrap();
    let tmp_dir = tmp.path().join("contracts");
    std::fs::create_dir_all(&tmp_dir).unwrap();
    // Copy one contract for a small test
    let src = contracts_dir().join("softmax-kernel-v1.yaml");
    std::fs::copy(&src, tmp_dir.join("softmax-kernel-v1.yaml")).unwrap();

    let config = LintConfig::new(&tmp_dir, None, 0.0);
    let r1 = run_lint(&config);
    assert!(r1.cache_stats.misses > 0);

    let r2 = run_lint(&config);
    assert!(r2.cache_stats.hits > 0);
}

#[test]
fn lint_validation_failure_skips_audit_and_score() {
    let tmp = tempfile::tempdir().unwrap();
    // Write a malformed YAML that will parse into a Contract with validation errors
    // Actually: write something that fails to parse entirely
    std::fs::write(tmp.path().join("bad.yaml"), "not: valid: yaml: {{{{").unwrap();
    let config = LintConfig::new(tmp.path(), None, 0.0);
    let report = run_lint(&config);
    assert!(!report.passed);
    // validate should fail, all subsequent gates should be skipped
    assert_eq!(report.gates.len(), 12);
    assert!(!report.gates[0].passed); // validate failed
    assert!(report.gates[1].skipped); // audit skipped
    assert!(report.gates[2].skipped); // score skipped
    assert!(report.gates[3].skipped); // verify skipped
    assert!(report.gates[4].skipped); // enforce skipped
    assert!(report.gates[5].skipped); // enforcement-level skipped
    assert!(report.gates[6].skipped); // reverse-coverage skipped
    assert!(report.gates[7].skipped); // duplicate-stems skipped
    assert!(report.gates[8].skipped); // composition skipped
}

#[test]
fn lint_suppression_by_stem() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.99);
    // Suppress by contract stem (--suppress)
    config.suppressed_findings = vec!["special-tokens-registry-v1".into()];
    let report = run_lint(&config);
    for f in &report.findings {
        if f.contract_stem.as_deref() == Some("special-tokens-registry-v1") {
            assert!(f.suppressed);
        }
    }
}

#[test]
fn lint_suppression_by_file_pattern() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.99);
    config.suppressed_files = vec!["arch-constraints".into()];
    let report = run_lint(&config);
    for f in &report.findings {
        if f.file.contains("arch-constraints") {
            assert!(f.suppressed);
        }
    }
}

#[test]
fn lint_severity_override() {
    let dir = contracts_dir();
    let mut config = LintConfig::new(&dir, None, 0.99);
    let mut overrides = HashMap::new();
    overrides.insert("PV-SCR-001".into(), RuleSeverity::Warning);
    config.severity_overrides = overrides;
    let report = run_lint(&config);
    for f in &report.findings {
        if f.rule_id == "PV-SCR-001" {
            assert_eq!(f.severity, RuleSeverity::Warning);
        }
    }
}

#[test]
fn lifecycle_first_run_all_new() {
    let tmp = tempfile::tempdir().unwrap();
    let contract_dir = tmp.path().join("contracts");
    std::fs::create_dir_all(&contract_dir).unwrap();
    let src = contracts_dir().join("softmax-kernel-v1.yaml");
    std::fs::copy(&src, contract_dir.join("softmax-kernel-v1.yaml")).unwrap();

    let config = LintConfig::new(&contract_dir, None, 0.99);
    let report = run_lint(&config);
    // First run: every finding should be marked new
    let active: Vec<_> = report.findings.iter().filter(|f| !f.suppressed).collect();
    assert!(!active.is_empty(), "should have findings");
    assert!(
        active.iter().all(|f| f.is_new),
        "first run: all findings should be new"
    );
}

#[test]
fn lifecycle_second_run_pre_existing() {
    let tmp = tempfile::tempdir().unwrap();
    let contract_dir = tmp.path().join("contracts");
    std::fs::create_dir_all(&contract_dir).unwrap();
    let src = contracts_dir().join("softmax-kernel-v1.yaml");
    std::fs::copy(&src, contract_dir.join("softmax-kernel-v1.yaml")).unwrap();

    // First run — seeds .pv/lint-previous.json
    let config = LintConfig::new(&contract_dir, None, 0.99);
    let _ = run_lint(&config);

    // Second run — same contract, same findings
    let report2 = run_lint(&config);
    let active: Vec<_> = report2.findings.iter().filter(|f| !f.suppressed).collect();
    assert!(!active.is_empty(), "should have findings");
    assert!(
        active.iter().all(|f| !f.is_new),
        "second identical run: no finding should be new"
    );
}

#[test]
fn lifecycle_persists_fingerprints() {
    let tmp = tempfile::tempdir().unwrap();
    let contract_dir = tmp.path().join("contracts");
    std::fs::create_dir_all(&contract_dir).unwrap();
    let src = contracts_dir().join("softmax-kernel-v1.yaml");
    std::fs::copy(&src, contract_dir.join("softmax-kernel-v1.yaml")).unwrap();

    let config = LintConfig::new(&contract_dir, None, 0.99);
    let _ = run_lint(&config);

    let previous_path = tmp.path().join(".pv").join("lint-previous.json");
    assert!(
        previous_path.exists(),
        ".pv/lint-previous.json should be created"
    );
    let content = std::fs::read_to_string(&previous_path).unwrap();
    let fps: std::collections::HashSet<String> = serde_json::from_str(&content).unwrap();
    assert!(!fps.is_empty(), "fingerprint set should not be empty");
}

#[test]
fn lifecycle_mark_new_findings_unit() {
    use super::mark_new_findings;

    let tmp = tempfile::tempdir().unwrap();
    let contract_dir = tmp.path().join("contracts");
    std::fs::create_dir_all(&contract_dir).unwrap();

    let mut findings = vec![
        finding::LintFinding::new("PV-VAL-001", RuleSeverity::Error, "msg1", "a.yaml"),
        finding::LintFinding::new("PV-VAL-002", RuleSeverity::Warning, "msg2", "b.yaml"),
    ];

    // First call: all new (no previous file)
    mark_new_findings(&mut findings, &contract_dir);
    assert!(findings[0].is_new);
    assert!(findings[1].is_new);

    // Reset is_new for second pass
    for f in &mut findings {
        f.is_new = false;
    }

    // Second call: same findings, none new
    mark_new_findings(&mut findings, &contract_dir);
    assert!(!findings[0].is_new);
    assert!(!findings[1].is_new);

    // Third call: add a new finding
    findings.push(finding::LintFinding::new(
        "PV-VAL-003",
        RuleSeverity::Info,
        "msg3",
        "c.yaml",
    ));
    for f in &mut findings {
        f.is_new = false;
    }
    mark_new_findings(&mut findings, &contract_dir);
    assert!(
        !findings[0].is_new,
        "pre-existing finding should not be new"
    );
    assert!(
        !findings[1].is_new,
        "pre-existing finding should not be new"
    );
    assert!(findings[2].is_new, "newly added finding should be new");
}

/// ONT-6 (PMAT-3451): every gate of a real run carries the lattice element its own `passed`/`skipped`
/// pair maps to, and the report's verdict is the meet over the default armed set — so no constructor can
/// set a verdict that disagrees with the booleans it sits beside.
#[test]
fn every_gate_verdict_agrees_with_passed_and_skipped_on_the_real_corpus() {
    let dir = contracts_dir();
    let report = run_lint(&LintConfig::new(&dir, None, 0.0));
    for g in &report.gates {
        assert_eq!(
            g.verdict,
            Verdict::from_gate(g.passed, g.skipped),
            "gate {}",
            g.name
        );
    }
    let armed = ArmedGates::default_set();
    let expected = armed
        .names()
        .iter()
        .map(|n| {
            report.gates.iter().find(|g| &g.name == n).map_or(
                Verdict::Unknown(crate::ontology::verdict::Reason::NotRun),
                |g| g.verdict,
            )
        })
        .fold(Verdict::Pass, Verdict::meet);
    assert_eq!(report.verdict, expected);
    assert_eq!(
        report.verdict,
        Verdict::Pass,
        "the repo corpus passes its armed meet"
    );
    // `run_lint` arms the DEFAULT set (the 8), so the three gates outside it are reported and excluded. The repo's
    // own `lint-baseline.json` arms `sigma` and `relations` as well — per-repo declarations, not the default.
    assert_eq!(
        report.not_armed,
        vec![
            "reverse-coverage".to_string(),
            "sigma".to_string(),
            "relations".to_string(),
            "shapes".to_string()
        ]
    );
}

/// ONT-001 §3.9: arming is the corpus's declaration, not the command line. A gate a flag ran is computed and
/// reported, and stays outside the meet unless `armed_gates` names it.
#[test]
fn a_gate_a_flag_ran_is_reported_but_not_armed() {
    let tmp = tempfile::tempdir().unwrap();
    let corpus = tmp.path().join("contracts");
    std::fs::create_dir_all(&corpus).unwrap();
    std::fs::copy(
        contracts_dir().join("softmax-kernel-v1.yaml"),
        corpus.join("softmax-kernel-v1.yaml"),
    )
    .unwrap();
    let mut config = LintConfig::new(&corpus, None, 0.0);
    config.strict_test_binding = true;
    let report = run_lint(&config);
    assert!(
        report.gates.iter().any(|g| g.name == "strict-test-binding"),
        "the flag ran the gate"
    );
    assert!(
        report.not_armed.iter().any(|n| n == "strict-test-binding"),
        "not declared, so not armed: {:?}",
        report.not_armed
    );
    assert!(!report
        .armed_gates
        .iter()
        .any(|g| g.name == "strict-test-binding"));
    assert_eq!(report.armed_gates.len(), 8);
}