aprender-contracts 0.72.3

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
//! Quality trend tracking — record and display lint snapshots over time.
//!
//! Each `--trend` invocation records a timestamped snapshot to
//! `.pv/trend/`. Historical snapshots enable drift detection
//! and quality regression alerts.
//!
//! Spec: `docs/specifications/sub/lint.md` Section 9

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::finding::LintFinding;
use super::rules::RuleSeverity;
use super::LintReport;

/// A single point-in-time lint snapshot.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TrendSnapshot {
    pub timestamp: String,
    pub commit: Option<String>,
    pub total_contracts: usize,
    pub errors: usize,
    pub warnings: usize,
    pub mean_score: f64,
    pub findings_count: usize,
    pub passed: bool,
}

/// Get the trend directory path.
pub fn trend_dir(base: &Path) -> PathBuf {
    base.join(".pv").join("trend")
}

/// Record a lint report as a trend snapshot.
pub fn record_snapshot(
    trend_root: &Path,
    report: &LintReport,
    contracts_count: usize,
) -> Result<PathBuf, String> {
    std::fs::create_dir_all(trend_root).map_err(|e| format!("Failed to create trend dir: {e}"))?;

    let timestamp = now_iso8601();
    let commit = current_commit().ok();

    let (errors, warnings) = count_by_severity(&report.findings);
    let mean_score = extract_mean_score(report);

    let snapshot = TrendSnapshot {
        timestamp: timestamp.clone(),
        commit,
        total_contracts: contracts_count,
        errors,
        warnings,
        mean_score,
        findings_count: report.findings.len(),
        passed: report.passed,
    };

    let filename = format!("{}.json", timestamp.replace(':', "-"));
    let path = trend_root.join(&filename);
    let json = serde_json::to_string_pretty(&snapshot)
        .map_err(|e| format!("Failed to serialize snapshot: {e}"))?;
    std::fs::write(&path, json).map_err(|e| format!("Failed to write snapshot: {e}"))?;

    Ok(path)
}

/// Load all trend snapshots, sorted by timestamp.
pub fn load_snapshots(trend_root: &Path) -> Vec<TrendSnapshot> {
    let Ok(entries) = std::fs::read_dir(trend_root) else {
        return vec![];
    };
    let mut snapshots: Vec<TrendSnapshot> = entries
        .flatten()
        .filter(|e| e.path().extension().and_then(|x| x.to_str()) == Some("json"))
        .filter_map(|e| {
            let content = std::fs::read_to_string(e.path()).ok()?;
            serde_json::from_str(&content).ok()
        })
        .collect();
    snapshots.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
    snapshots
}

/// Check for quality drift: mean score drop >threshold from rolling avg.
#[allow(clippy::cast_precision_loss)]
pub fn detect_drift(snapshots: &[TrendSnapshot], threshold: f64) -> Option<f64> {
    if snapshots.len() < 2 {
        return None;
    }

    let window = snapshots.len().min(7);
    let recent = &snapshots[snapshots.len().saturating_sub(window)..snapshots.len() - 1];
    if recent.is_empty() {
        return None;
    }

    let avg: f64 = recent.iter().map(|s| s.mean_score).sum::<f64>() / recent.len() as f64;
    let current = snapshots.last()?.mean_score;
    let drop = avg - current;

    if drop > threshold {
        Some(drop)
    } else {
        None
    }
}

/// Format trend display.
pub fn format_trend(snapshots: &[TrendSnapshot], limit: usize) -> String {
    let mut lines = Vec::new();
    lines.push("Date                 Score  Errors  Warnings  Result".into());
    lines.push("-".repeat(60));

    for snap in snapshots.iter().rev().take(limit) {
        let result = if snap.passed { "PASS" } else { "FAIL" };
        lines.push(format!(
            "{:<20} {:.2}   {:<7} {:<9} {}",
            &snap.timestamp[..19.min(snap.timestamp.len())],
            snap.mean_score,
            snap.errors,
            snap.warnings,
            result,
        ));
    }

    if snapshots.len() >= 2 {
        let first = &snapshots[0];
        let last = snapshots
            .last()
            .expect("snapshots is non-empty: len() >= 2 checked above");
        let delta = last.mean_score - first.mean_score;
        let direction = if delta > 0.01 {
            "improving"
        } else if delta < -0.01 {
            "declining"
        } else {
            "stable"
        };
        lines.push(format!(
            "Trend: {:+.3} score over {} snapshots ({direction})",
            delta,
            snapshots.len()
        ));
    }

    lines.join("\n")
}

fn count_by_severity(findings: &[LintFinding]) -> (usize, usize) {
    let errors = findings
        .iter()
        .filter(|f| f.severity == RuleSeverity::Error && !f.suppressed)
        .count();
    let warnings = findings
        .iter()
        .filter(|f| f.severity == RuleSeverity::Warning && !f.suppressed)
        .count();
    (errors, warnings)
}

fn extract_mean_score(report: &LintReport) -> f64 {
    for gate in &report.gates {
        if let super::GateDetail::Score { mean_score, .. } = &gate.detail {
            return *mean_score;
        }
    }
    0.0
}

#[allow(
    clippy::cast_possible_wrap,
    clippy::cast_sign_loss,
    clippy::similar_names
)]
fn now_iso8601() -> String {
    // UTC timestamp without chrono dependency — manual epoch-to-date conversion
    let duration = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let secs = duration.as_secs();
    let millis = duration.subsec_millis();

    // Days since epoch
    let days = (secs / 86400) as i64;
    let time_secs = secs % 86400;
    let hours = time_secs / 3600;
    let minutes = (time_secs % 3600) / 60;
    let seconds = time_secs % 60;

    // Civil date from days since epoch (Algorithm from Howard Hinnant)
    let z = days + 719_468;
    let era = (if z >= 0 { z } else { z - 146_096 }) / 146_097;
    let doe = (z - era * 146_097) as u64;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365;
    let y = yoe as i64 + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };

    format!("{y:04}-{m:02}-{d:02}T{hours:02}:{minutes:02}:{seconds:02}.{millis:03}Z")
}

fn current_commit() -> Result<String, String> {
    let output = std::process::Command::new("git")
        .args(["rev-parse", "--short", "HEAD"])
        .output()
        .map_err(|e| format!("git: {e}"))?;
    if output.status.success() {
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        Err("not a git repo".into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lint::cache::CacheStats;

    fn sample_snapshot(score: f64, ts: &str) -> TrendSnapshot {
        TrendSnapshot {
            timestamp: ts.into(),
            commit: Some("abc123".into()),
            total_contracts: 107,
            errors: 0,
            warnings: 5,
            mean_score: score,
            findings_count: 5,
            passed: true,
        }
    }

    #[test]
    fn record_and_load_snapshot() {
        let tmp = tempfile::tempdir().unwrap();
        let trend = tmp.path().join("trend");

        let report = LintReport {
            passed: true,
            gates: vec![],
            total_duration_ms: 10,
            findings: vec![],
            cache_stats: CacheStats::default(),
            contract_timings: vec![],
            verdict: crate::ontology::verdict::Verdict::Pass,
            armed_gates: vec![],
            not_armed: vec![],
            armed_monotone: None,
            armed_shapes_monotone: None,
        };
        let path = record_snapshot(&trend, &report, 107).unwrap();
        assert!(path.exists());

        let loaded = load_snapshots(&trend);
        assert_eq!(loaded.len(), 1);
        assert_eq!(loaded[0].total_contracts, 107);
    }

    #[test]
    fn detect_drift_no_data() {
        assert!(detect_drift(&[], 0.05).is_none());
    }

    #[test]
    fn detect_drift_one_snapshot() {
        let snaps = vec![sample_snapshot(0.80, "2026-03-01")];
        assert!(detect_drift(&snaps, 0.05).is_none());
    }

    #[test]
    fn detect_drift_stable() {
        let snaps = vec![
            sample_snapshot(0.80, "2026-03-01"),
            sample_snapshot(0.79, "2026-03-02"),
            sample_snapshot(0.80, "2026-03-03"),
        ];
        assert!(detect_drift(&snaps, 0.05).is_none());
    }

    #[test]
    fn detect_drift_declining() {
        let snaps = vec![
            sample_snapshot(0.80, "2026-03-01"),
            sample_snapshot(0.80, "2026-03-02"),
            sample_snapshot(0.70, "2026-03-03"),
        ];
        let drift = detect_drift(&snaps, 0.05);
        assert!(drift.is_some());
        assert!(drift.unwrap() > 0.05);
    }

    #[test]
    fn format_trend_display() {
        let snaps = vec![
            sample_snapshot(0.75, "2026-03-01T10:00:00"),
            sample_snapshot(0.78, "2026-03-02T10:00:00"),
            sample_snapshot(0.80, "2026-03-03T10:00:00"),
        ];
        let display = format_trend(&snaps, 10);
        assert!(display.contains("2026-03-03"));
        assert!(display.contains("improving"));
    }

    #[test]
    fn format_trend_empty() {
        let display = format_trend(&[], 10);
        assert!(display.contains("Date"));
    }

    #[test]
    fn load_snapshots_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let snaps = load_snapshots(tmp.path());
        assert!(snaps.is_empty());
    }

    #[test]
    fn trend_dir_path() {
        let path = trend_dir(Path::new("/repo"));
        assert_eq!(path, PathBuf::from("/repo/.pv/trend"));
    }

    #[test]
    fn load_snapshots_nonexistent_dir() {
        let snaps = load_snapshots(Path::new("/nonexistent/trend"));
        assert!(snaps.is_empty());
    }

    #[test]
    fn detect_drift_empty_recent_window() {
        // Two snapshots with same score — no drift
        let snaps = vec![
            sample_snapshot(0.80, "2026-03-01"),
            sample_snapshot(0.80, "2026-03-02"),
        ];
        assert!(detect_drift(&snaps, 0.05).is_none());
    }

    #[test]
    fn format_trend_declining() {
        let snaps = vec![
            sample_snapshot(0.80, "2026-03-01T10:00:00"),
            sample_snapshot(0.60, "2026-03-02T10:00:00"),
        ];
        let display = format_trend(&snaps, 10);
        assert!(display.contains("declining"));
    }

    #[test]
    fn format_trend_stable() {
        let snaps = vec![
            sample_snapshot(0.80, "2026-03-01T10:00:00"),
            sample_snapshot(0.80, "2026-03-02T10:00:00"),
        ];
        let display = format_trend(&snaps, 10);
        assert!(display.contains("stable"));
    }

    #[test]
    fn extract_mean_score_no_score_gate() {
        let report = LintReport {
            passed: true,
            gates: vec![],
            total_duration_ms: 0,
            findings: vec![],
            cache_stats: CacheStats::default(),
            contract_timings: vec![],
            verdict: crate::ontology::verdict::Verdict::Pass,
            armed_gates: vec![],
            not_armed: vec![],
            armed_monotone: None,
            armed_shapes_monotone: None,
        };
        assert!((extract_mean_score(&report) - 0.0).abs() < f64::EPSILON);
    }

    #[test]
    fn now_iso8601_format() {
        let ts = now_iso8601();
        // Should be ISO 8601 with milliseconds: YYYY-MM-DDTHH:MM:SS.mmmZ
        assert!(ts.ends_with('Z'));
        assert!(ts.contains('T'));
        assert!(ts.contains('.'));
        assert_eq!(ts.len(), 24); // "2026-03-07T19:31:33.056Z"
    }

    #[test]
    fn count_by_severity_mixed() {
        use crate::lint::finding::LintFinding;
        let findings = vec![
            LintFinding::new("PV-VAL-001", RuleSeverity::Error, "e", "f.yaml"),
            LintFinding::new("PV-AUD-001", RuleSeverity::Warning, "w", "f.yaml"),
            LintFinding::new("PV-AUD-002", RuleSeverity::Info, "i", "f.yaml"),
        ];
        let (errors, warnings) = count_by_severity(&findings);
        assert_eq!(errors, 1);
        assert_eq!(warnings, 1);
    }
}