aprender-contracts 0.34.0

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
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
//! Contract and codebase scoring.
//!
//! Provides quantitative quality assessment for individual contracts
//! and codebases that consume them. Five dimensions per contract,
//! ten dimensions per codebase (`PVScore`), grades A-F.
//!
//! Spec: `docs/specifications/sub/scoring.md`, `docs/specifications/sub/pvscore.md`

mod codebase;
pub mod drift;
mod pvscore;
mod types;

pub use codebase::{score_codebase, score_codebase_full, score_codebase_with_pagerank};
pub use pvscore::pvscore_10dim;
pub use types::{CodebaseScore, ContractScore, Grade, ScoreProbe, ScoringGap, ScoringWeights};

use crate::binding::{BindingRegistry, ImplStatus};
use crate::schema::{Contract, KaniHarness, KaniStrategy, LeanStatus};

/// Score a single contract against its completeness and verification depth.
///
/// Five dimensions (weights from spec):
/// - D1: Specification depth (20%)
/// - D2: Falsification coverage (25%)
/// - D3: Kani proof coverage (25%)
/// - D4: Lean proof coverage (10%)
/// - D5: Binding coverage (20%)
pub fn score_contract(
    contract: &Contract,
    binding: Option<&BindingRegistry>,
    stem: &str,
) -> ContractScore {
    score_contract_weighted(contract, binding, stem, &ScoringWeights::default())
}

/// Score a contract with custom weights for each dimension.
pub fn score_contract_weighted(
    contract: &Contract,
    binding: Option<&BindingRegistry>,
    stem: &str,
    weights: &ScoringWeights,
) -> ContractScore {
    let w = weights.normalized();
    let mut probes = Vec::new();

    let spec_depth = compute_spec_depth(contract, &mut probes);
    let falsification = compute_falsification_coverage(contract, &mut probes);
    let kani = compute_kani_coverage(contract, &mut probes);
    let lean = compute_lean_coverage(contract, &mut probes);
    let binding_cov = compute_binding_coverage(contract, binding, stem, &mut probes);

    // Non-kernel contracts (registries, model-family schemas, patterns,
    // reference documents) are data-only: they define lookup tables or
    // metadata, not executable functions. Give them full credit for
    // binding/lean so the composite reflects their declarative nature.
    let (effective_binding, effective_lean) = if contract.requires_proofs() {
        (binding_cov, lean)
    } else {
        (1.0, lean.max(0.5))
    };

    let composite = spec_depth * w.spec_depth
        + falsification * w.falsification
        + kani * w.kani
        + effective_lean * w.lean
        + effective_binding * w.binding;

    ContractScore {
        stem: stem.to_string(),
        spec_depth,
        falsification_coverage: falsification,
        kani_coverage: kani,
        lean_coverage: effective_lean,
        binding_coverage: effective_binding,
        composite,
        grade: Grade::from_score(composite),
        probes,
    }
}

#[allow(clippy::too_many_lines)]
fn compute_spec_depth(contract: &Contract, probes: &mut Vec<ScoreProbe>) -> f64 {
    let mut score = 0.0;

    // Has equations (0.30)
    let has_equations = !contract.equations.is_empty();
    probes.push(ScoreProbe {
        dimension: "spec_depth".into(),
        probe: "has_equations".into(),
        outcome: has_equations,
        detail: if has_equations {
            format!("{} equation(s)", contract.equations.len())
        } else {
            "(no equations)".into()
        },
    });
    if has_equations {
        score += 0.30;
    }

    // Per-equation probes: domain and invariants
    for (name, eq) in &contract.equations {
        let has_domain = eq.domain.is_some();
        probes.push(ScoreProbe {
            dimension: "spec_depth".into(),
            probe: format!("{name}: domain"),
            outcome: has_domain,
            detail: if has_domain {
                eq.domain.as_deref().unwrap_or("").to_string()
            } else {
                "(no domain)".into()
            },
        });
        let has_inv = !eq.invariants.is_empty();
        probes.push(ScoreProbe {
            dimension: "spec_depth".into(),
            probe: format!("{name}: invariants"),
            outcome: has_inv,
            detail: if has_inv {
                format!("{} invariant(s)", eq.invariants.len())
            } else {
                "(no invariants)".into()
            },
        });
    }

    // Has domains on equations (0.15)
    let has_domains = contract.equations.values().any(|eq| eq.domain.is_some());
    if has_domains {
        score += 0.15;
    }

    // Has invariants on equations (0.15)
    let has_invariants = contract
        .equations
        .values()
        .any(|eq| !eq.invariants.is_empty());
    if has_invariants {
        score += 0.15;
    }

    // Has kernel structure (0.15)
    let has_ks = contract.kernel_structure.is_some();
    probes.push(ScoreProbe {
        dimension: "spec_depth".into(),
        probe: "kernel_structure".into(),
        outcome: has_ks,
        detail: if has_ks {
            "present".into()
        } else {
            "(no kernel_structure)".into()
        },
    });
    if has_ks {
        score += 0.15;
    }

    // Has tolerances on obligations (0.10)
    let has_tolerances = contract
        .proof_obligations
        .iter()
        .any(|ob| ob.tolerance.is_some());
    probes.push(ScoreProbe {
        dimension: "spec_depth".into(),
        probe: "has_tolerances".into(),
        outcome: has_tolerances,
        detail: if has_tolerances {
            "at least one obligation has tolerance".into()
        } else {
            "(no tolerances)".into()
        },
    });
    if has_tolerances {
        score += 0.10;
    }

    // Has references (0.10)
    let has_refs = !contract.metadata.references.is_empty();
    probes.push(ScoreProbe {
        dimension: "spec_depth".into(),
        probe: "references".into(),
        outcome: has_refs,
        detail: if has_refs {
            format!("{} reference(s)", contract.metadata.references.len())
        } else {
            "(no references)".into()
        },
    });
    if has_refs {
        score += 0.10;
    }

    // Has depends_on (0.05)
    let has_deps = !contract.metadata.depends_on.is_empty();
    probes.push(ScoreProbe {
        dimension: "spec_depth".into(),
        probe: "depends_on".into(),
        outcome: has_deps,
        detail: if has_deps {
            format!("{} dep(s)", contract.metadata.depends_on.len())
        } else {
            "(no depends_on)".into()
        },
    });
    if has_deps {
        score += 0.05;
    }

    score
}

#[allow(clippy::cast_precision_loss)]
fn compute_falsification_coverage(contract: &Contract, probes: &mut Vec<ScoreProbe>) -> f64 {
    let total = contract.proof_obligations.len();

    // Emit a probe per obligation
    for ob in &contract.proof_obligations {
        let matching_test = contract
            .falsification_tests
            .iter()
            .find(|t| t.rule == ob.property);
        let has_test = matching_test.is_some();
        probes.push(ScoreProbe {
            dimension: "falsification".into(),
            probe: ob.property.clone(),
            outcome: has_test,
            detail: if let Some(t) = matching_test {
                t.id.clone()
            } else {
                "(no test)".into()
            },
        });
    }

    // Also probe any tests that don't match an obligation
    for t in &contract.falsification_tests {
        let matches_obligation = contract
            .proof_obligations
            .iter()
            .any(|ob| ob.property == t.rule);
        if !matches_obligation {
            probes.push(ScoreProbe {
                dimension: "falsification".into(),
                probe: t.rule.clone(),
                outcome: true,
                detail: format!("{} (unmatched)", t.id),
            });
        }
    }

    if total == 0 {
        return if contract.falsification_tests.is_empty() {
            0.0
        } else {
            1.0
        };
    }

    // Preserve original behaviour: min(test_count, obligation_count) / obligation_count
    let covered = contract.falsification_tests.len().min(total);
    covered as f64 / total as f64
}

#[allow(clippy::cast_precision_loss)]
fn compute_kani_coverage(contract: &Contract, probes: &mut Vec<ScoreProbe>) -> f64 {
    let total = contract.proof_obligations.len();

    // Emit a probe per obligation showing which harness covers it
    for ob in &contract.proof_obligations {
        let matching_harness = contract
            .kani_harnesses
            .iter()
            .find(|h| h.obligation == ob.property);
        let has_harness = matching_harness.is_some();
        probes.push(ScoreProbe {
            dimension: "kani".into(),
            probe: ob.property.clone(),
            outcome: has_harness,
            detail: if let Some(h) = matching_harness {
                let strategy_note = h.strategy.map(|s| format!(" [{s}]")).unwrap_or_default();
                format!("{}{strategy_note}", h.id)
            } else {
                "(no harness)".into()
            },
        });
    }

    // Also probe harnesses that don't match any obligation
    for h in &contract.kani_harnesses {
        let matches_obligation = contract
            .proof_obligations
            .iter()
            .any(|ob| ob.property == h.obligation);
        if !matches_obligation {
            probes.push(ScoreProbe {
                dimension: "kani".into(),
                probe: h.obligation.clone(),
                outcome: true,
                detail: format!("{} (unmatched)", h.id),
            });
        }
    }

    if total == 0 {
        return if contract.kani_harnesses.is_empty() {
            0.0
        } else {
            1.0
        };
    }

    let strategy_weight = |h: &KaniHarness| -> f64 {
        // GH-1595: If the harness has been verified by a green CI run
        // (apr-cookbook kani-gate or equivalent), lift weight to 1.0 —
        // runtime witness supplants static-readiness signal.
        if h.actually_verified == Some(true) {
            return 1.0;
        }
        match h.strategy.as_ref() {
            Some(KaniStrategy::Exhaustive) => 1.0,
            Some(KaniStrategy::BoundedInt) => 0.9,
            Some(KaniStrategy::StubFloat) => 0.8,
            Some(KaniStrategy::Compositional) => 0.7,
            None => 0.5,
        }
    };

    let weighted_sum: f64 = contract.kani_harnesses.iter().map(strategy_weight).sum();
    (weighted_sum / total as f64).min(1.0)
}

#[allow(clippy::cast_precision_loss)]
fn compute_lean_coverage(contract: &Contract, probes: &mut Vec<ScoreProbe>) -> f64 {
    // Emit a probe per obligation showing lean status
    for ob in &contract.proof_obligations {
        match &ob.lean {
            Some(lean) if lean.status != LeanStatus::NotApplicable => {
                let is_proved = lean.status == LeanStatus::Proved;
                probes.push(ScoreProbe {
                    dimension: "lean".into(),
                    probe: ob.property.clone(),
                    outcome: is_proved,
                    detail: if is_proved {
                        format!("{} (proved)", lean.theorem)
                    } else {
                        format!("{} ({})", lean.theorem, lean.status)
                    },
                });
            }
            Some(lean) => {
                // NotApplicable — still informative as a probe
                probes.push(ScoreProbe {
                    dimension: "lean".into(),
                    probe: ob.property.clone(),
                    outcome: false,
                    detail: format!("{} (not-applicable)", lean.theorem),
                });
            }
            None => {
                probes.push(ScoreProbe {
                    dimension: "lean".into(),
                    probe: ob.property.clone(),
                    outcome: false,
                    detail: "(no lean_theorem)".into(),
                });
            }
        }
    }

    let applicable: Vec<_> = contract
        .proof_obligations
        .iter()
        .filter(|ob| {
            ob.lean
                .as_ref()
                .is_some_and(|l| l.status != LeanStatus::NotApplicable)
        })
        .collect();

    if applicable.is_empty() {
        return 0.0;
    }

    let proved = applicable
        .iter()
        .filter(|ob| {
            ob.lean
                .as_ref()
                .is_some_and(|l| l.status == LeanStatus::Proved)
        })
        .count();

    proved as f64 / applicable.len() as f64
}

#[allow(clippy::cast_precision_loss)]
fn compute_binding_coverage(
    _contract: &Contract,
    binding: Option<&BindingRegistry>,
    stem: &str,
    probes: &mut Vec<ScoreProbe>,
) -> f64 {
    let Some(binding) = binding else {
        probes.push(ScoreProbe {
            dimension: "binding".into(),
            probe: "(all)".into(),
            outcome: false,
            detail: "(no binding registry)".into(),
        });
        return 0.0;
    };

    let relevant = binding.bindings_for(stem);

    if relevant.is_empty() {
        probes.push(ScoreProbe {
            dimension: "binding".into(),
            probe: stem.into(),
            outcome: false,
            detail: "(no bindings for this contract)".into(),
        });
        return 0.0;
    }

    // Emit a probe per binding entry
    for b in &relevant {
        let status_str = match b.status {
            ImplStatus::Implemented => "implemented",
            ImplStatus::Partial => "partial",
            ImplStatus::NotImplemented => "not_implemented",
            ImplStatus::Pending => "pending",
        };
        let is_implemented = b.status == ImplStatus::Implemented;
        let fn_name = b
            .function
            .as_deref()
            .or(b.module_path.as_deref())
            .unwrap_or("?");
        probes.push(ScoreProbe {
            dimension: "binding".into(),
            probe: b.equation.clone(),
            outcome: is_implemented,
            detail: format!("{fn_name} ({status_str})"),
        });
    }

    let implemented: f64 = relevant
        .iter()
        .map(|b| match b.status {
            ImplStatus::Implemented => 1.0,
            ImplStatus::Partial => 0.5,
            ImplStatus::NotImplemented | ImplStatus::Pending => 0.0,
        })
        .sum();

    implemented / relevant.len() as f64
}

#[cfg(test)]
mod tests {
    include!("scoring_tests.rs");
}