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
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Binding registry — maps contract equations to implementations.
//!
//! A `BindingRegistry` connects kernel contract equations (defined in
//! YAML) to the actual Rust functions that implement them in a target
//! crate (e.g. aprender). This enables:
//!
//! - **Audit**: `pv audit --binding` reports which obligations have
//!   implementations and which are gaps.
//! - **Wired tests**: `pv probar --binding` generates property tests
//!   that call real functions instead of `unimplemented!()`.

use std::path::Path;

use serde::{Deserialize, Serialize};

use crate::error::{ContractError, Severity, Violation};

/// Top-level binding registry parsed from YAML.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BindingRegistry {
    pub version: String,
    pub target_crate: String,
    /// Developer-declared critical path functions (Section 28).
    /// CD2 completeness = `critical_path` entries with bindings / len.
    #[serde(default)]
    pub critical_path: Vec<String>,
    #[serde(default)]
    pub bindings: Vec<KernelBinding>,
}

/// A single binding: one contract equation mapped to one implementation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KernelBinding {
    /// Contract YAML filename (e.g. "softmax-kernel-v1.yaml").
    pub contract: String,
    /// Equation name within the contract (e.g. "softmax").
    pub equation: String,
    /// Full Rust module path (e.g. `aprender::nn::functional::softmax`).
    #[serde(default)]
    pub module_path: Option<String>,
    /// Function or method name.
    #[serde(default)]
    pub function: Option<String>,
    /// Full Rust signature string.
    #[serde(default)]
    pub signature: Option<String>,
    /// Implementation status.
    pub status: ImplStatus,
    /// Free-form notes.
    #[serde(default)]
    pub notes: Option<String>,
}

/// Implementation status of a binding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ImplStatus {
    /// Fully implemented and ready for use.
    Implemented,
    /// Partially implemented with known gaps.
    Partial,
    /// Not yet implemented.
    NotImplemented,
    /// Planned but not started — skipped by enforcement checks.
    Pending,
}

/// Display implementation status as a `snake_case` string
impl std::fmt::Display for ImplStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Implemented => "implemented",
            Self::Partial => "partial",
            Self::NotImplemented => "not_implemented",
            Self::Pending => "pending",
        };
        write!(f, "{s}")
    }
}

/// Parse a binding registry YAML file.
///
/// # Errors
///
/// Returns [`ContractError::Io`] if the file cannot be read,
/// or [`ContractError::Yaml`] if the YAML is malformed.
pub fn parse_binding(path: &Path) -> Result<BindingRegistry, ContractError> {
    let content = std::fs::read_to_string(path)?;
    parse_binding_str(&content)
}

/// Parse a binding registry from a YAML string.
pub fn parse_binding_str(yaml: &str) -> Result<BindingRegistry, ContractError> {
    let registry: BindingRegistry = serde_yaml::from_str(yaml)?;
    Ok(registry)
}

/// Normalize a contract identifier by stripping `.yaml`/`.yml` extension.
///
/// Both binding entries (`contract: foo-v1.yaml`) and file stems (`foo-v1`)
/// are normalized to the bare stem so comparisons work regardless of whether
/// the caller used a filename or stem.
pub fn normalize_contract_id(id: &str) -> &str {
    id.strip_suffix(".yaml")
        .or_else(|| id.strip_suffix(".yml"))
        .unwrap_or(id)
}

impl BindingRegistry {
    /// Find all bindings matching a contract (normalizes both sides).
    pub fn bindings_for(&self, contract_id: &str) -> Vec<&KernelBinding> {
        let needle = normalize_contract_id(contract_id);
        self.bindings
            .iter()
            .filter(|b| normalize_contract_id(&b.contract) == needle)
            .collect()
    }

    /// Find a specific binding by contract + equation (normalizes contract).
    pub fn find_binding(&self, contract_id: &str, equation: &str) -> Option<&KernelBinding> {
        let needle = normalize_contract_id(contract_id);
        self.bindings
            .iter()
            .find(|b| normalize_contract_id(&b.contract) == needle && b.equation == equation)
    }

    /// L5 verification: return a copy of this registry in which every binding
    /// marked `implemented` whose `function` is NOT actually defined in the
    /// source tree under `source_root` is downgraded to `not_implemented`.
    ///
    /// This turns the L5 predicate "all bindings **verified** as implemented"
    /// (see [`crate::proof_status`]) into a fact instead of a self-declared YAML
    /// flag: a binding only survives as `implemented` if a real `fn <function>`
    /// exists in source. Rename or delete the function and the binding is
    /// downgraded, dropping the contract below L5 — the check is falsifiable.
    ///
    /// The source tree is scanned once (all `.rs` files, skipping build/vcs
    /// dirs) and the resulting function-name set is reused for every binding.
    #[must_use]
    pub fn verified(&self, source_root: &Path) -> BindingRegistry {
        let fn_names = collect_fn_names(source_root);
        let bindings = self
            .bindings
            .iter()
            .map(|b| {
                let mut b = b.clone();
                if b.status == ImplStatus::Implemented && !b.function_defined_in(&fn_names) {
                    b.status = ImplStatus::NotImplemented;
                }
                b
            })
            .collect();
        BindingRegistry {
            version: self.version.clone(),
            target_crate: self.target_crate.clone(),
            critical_path: self.critical_path.clone(),
            bindings,
        }
    }
}

impl KernelBinding {
    /// True when this binding's `function` is present in the given set of
    /// function names discovered in source. A binding with no `function` field
    /// cannot be verified and returns `false`.
    #[must_use]
    pub fn function_defined_in(&self, fn_names: &std::collections::HashSet<String>) -> bool {
        self.function
            .as_deref()
            .is_some_and(|f| fn_names.contains(f))
    }
}

/// Collect every Rust function name (`fn <name>`) defined in `.rs` files under
/// `root`, skipping `target/`, `.git/`, `.lake/`, and `node_modules/`. Used by
/// [`BindingRegistry::verified`] to check bindings point to real code.
#[must_use]
pub fn collect_fn_names(root: &Path) -> std::collections::HashSet<String> {
    let mut names = std::collections::HashSet::new();
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_dir() {
                let skip = matches!(
                    path.file_name().and_then(|n| n.to_str()),
                    Some("target" | ".git" | ".lake" | "node_modules")
                );
                if !skip {
                    stack.push(path);
                }
            } else if path.extension().is_some_and(|e| e == "rs") {
                if let Ok(content) = std::fs::read_to_string(&path) {
                    extract_fn_names(&content, &mut names);
                }
            }
        }
    }
    names
}

/// Extract `fn <name>` identifiers from a Rust source string into `names`.
fn extract_fn_names(content: &str, names: &mut std::collections::HashSet<String>) {
    for line in content.lines() {
        let mut rest = line;
        while let Some(pos) = rest.find("fn ") {
            // Require `fn ` to start a word (preceded by start/space) to avoid
            // matching identifiers like `my_fn `.
            let ok_boundary = pos == 0
                || rest[..pos]
                    .chars()
                    .next_back()
                    .is_some_and(|c| !c.is_alphanumeric() && c != '_');
            let after = &rest[pos + 3..];
            if ok_boundary {
                let name: String = after
                    .chars()
                    .take_while(|c| c.is_alphanumeric() || *c == '_')
                    .collect();
                if !name.is_empty() {
                    names.insert(name);
                }
            }
            rest = after;
        }
    }
}

/// Validate a binding registry's OWN shape (rules BINDING-001..006).
///
/// # Why pv validates its own artifact
///
/// `contracts/binding.yaml` and `contracts/aprender/binding.yaml` are pv's
/// output and pv's input: `pv audit --binding` reports coverage from them and
/// `pv probar --binding` generates property tests that call the functions they
/// name. Until now `pv validate` could not read either — both failed with
/// ``missing field `metadata` ``, because the single-file surface parsed
/// everything as a `Contract` while `is_contract_yaml` had already excluded
/// them BY NAME from the directory surface. The tool's own manifest was the
/// one file it could not check.
///
/// The rules below are the ones a registry can be wrong about in a way that
/// silently degrades a downstream gate: an unnamed target crate, an entry that
/// binds nothing, two entries claiming the same equation, and — the one that
/// matters most — a binding that says `implemented` while naming nothing a
/// reader could go and look at.
#[must_use]
pub fn validate_binding_registry(registry: &BindingRegistry) -> Vec<Violation> {
    let mut violations = Vec::new();
    let err = |rule: &str, message: String, location: String| Violation {
        severity: Severity::Error,
        rule: rule.to_string(),
        message,
        location: Some(location),
    };

    if registry.version.trim().is_empty() {
        violations.push(err(
            "BINDING-001",
            "binding registry has no `version:` — every consumer of this file records \
             which version of the mapping it audited against"
                .to_string(),
            "version".to_string(),
        ));
    }
    if registry.target_crate.trim().is_empty() {
        violations.push(err(
            "BINDING-002",
            "binding registry has no `target_crate:` — a mapping from equations to \
             functions is meaningless without saying which crate those functions live in"
                .to_string(),
            "target_crate".to_string(),
        ));
    }
    if registry.bindings.is_empty() {
        violations.push(err(
            "BINDING-003",
            "binding registry declares no `bindings:` — `pv audit --binding` would \
             report 0/0 coverage, which reads as clean"
                .to_string(),
            "bindings".to_string(),
        ));
    }

    let mut seen: std::collections::HashSet<(String, String)> = std::collections::HashSet::new();
    for (i, binding) in registry.bindings.iter().enumerate() {
        validate_one_binding(i, binding, &mut seen, &mut violations);
    }
    violations
}

/// BINDING-004/005/006 for a single entry.
fn validate_one_binding(
    index: usize,
    binding: &KernelBinding,
    seen: &mut std::collections::HashSet<(String, String)>,
    violations: &mut Vec<Violation>,
) {
    let at = |field: &str| format!("bindings[{index}].{field}");
    let err = |rule: &str, message: String, location: String| Violation {
        severity: Severity::Error,
        rule: rule.to_string(),
        message,
        location: Some(location),
    };

    if binding.contract.trim().is_empty() {
        violations.push(err(
            "BINDING-004",
            format!(
                "bindings[{index}] names no `contract:` — the entry binds an equation to nothing"
            ),
            at("contract"),
        ));
    }
    if binding.equation.trim().is_empty() {
        violations.push(err(
            "BINDING-004",
            format!(
                "bindings[{index}] names no `equation:` — `bindings_for()` matches on the \
                 contract/equation pair, so an entry without one can never be found"
            ),
            at("equation"),
        ));
    }

    // BINDING-005: an entry claiming an implementation must name where it is.
    //
    // `module_path` + `function` is the usual answer. `notes` is accepted as
    // the other one because five entries in `contracts/binding.yaml` are
    // discharged by a shell guard rather than a Rust function
    // (`scripts/check_pr_review_receipt.sh`) and say so at length. What is
    // rejected is the entry that claims `implemented` and points at NOTHING —
    // an implementation claim no reader can go and check.
    let claims_implementation = matches!(
        binding.status,
        ImplStatus::Implemented | ImplStatus::Partial
    );
    let names_rust = binding.module_path.is_some() && binding.function.is_some();
    let names_evidence = binding
        .notes
        .as_deref()
        .is_some_and(|n| !n.trim().is_empty());
    if claims_implementation && !names_rust && !names_evidence {
        violations.push(err(
            "BINDING-005",
            format!(
                "bindings[{index}] ({}::{}) is `status: {}` but names neither a \
                 `module_path:`+`function:` nor any `notes:` saying what discharges it — \
                 an implementation claim nobody can go and look at",
                binding.contract, binding.equation, binding.status
            ),
            at("status"),
        ));
    }

    // BINDING-006: one equation, one binding. `find_binding` returns the FIRST
    // match, so a duplicate silently decides which implementation is audited.
    let key = (
        normalize_contract_id(&binding.contract).to_string(),
        binding.equation.clone(),
    );
    if !seen.insert(key) {
        violations.push(err(
            "BINDING-006",
            format!(
                "duplicate binding for {}::{} — `find_binding()` returns the first match, \
                 so the second entry is audited by nothing and can drift unnoticed",
                binding.contract, binding.equation
            ),
            at("equation"),
        ));
    }
}

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

    #[test]
    fn parse_minimal_binding() {
        let yaml = r#"
version: "1.0.0"
target_crate: aprender
bindings: []
"#;
        let reg = parse_binding_str(yaml).unwrap();
        assert_eq!(reg.version, "1.0.0");
        assert_eq!(reg.target_crate, "aprender");
        assert!(reg.bindings.is_empty());
    }

    #[test]
    fn parse_binding_with_entries() {
        let yaml = r#"
version: "1.0.0"
target_crate: aprender
bindings:
  - contract: softmax-kernel-v1.yaml
    equation: softmax
    module_path: "aprender::nn::functional::softmax"
    function: softmax
    signature: "fn softmax(x: &Tensor, dim: i32) -> Tensor"
    status: implemented
  - contract: activation-kernel-v1.yaml
    equation: silu
    status: not_implemented
    notes: "Not yet available"
"#;
        let reg = parse_binding_str(yaml).unwrap();
        assert_eq!(reg.bindings.len(), 2);
        assert_eq!(reg.bindings[0].equation, "softmax");
        assert_eq!(reg.bindings[0].status, ImplStatus::Implemented);
        assert!(reg.bindings[0].module_path.is_some());
        assert_eq!(reg.bindings[1].equation, "silu");
        assert_eq!(reg.bindings[1].status, ImplStatus::NotImplemented);
        assert!(reg.bindings[1].module_path.is_none());
    }

    #[test]
    fn parse_partial_status() {
        let yaml = r#"
version: "1.0.0"
target_crate: test
bindings:
  - contract: test.yaml
    equation: f
    module_path: "test::f"
    function: f
    status: partial
    notes: "Only scalar path"
"#;
        let reg = parse_binding_str(yaml).unwrap();
        assert_eq!(reg.bindings[0].status, ImplStatus::Partial);
    }

    #[test]
    fn impl_status_display() {
        assert_eq!(ImplStatus::Implemented.to_string(), "implemented");
        assert_eq!(ImplStatus::Partial.to_string(), "partial");
        assert_eq!(ImplStatus::NotImplemented.to_string(), "not_implemented");
        assert_eq!(ImplStatus::Pending.to_string(), "pending");
    }

    #[test]
    fn parse_invalid_binding_yaml() {
        let result = parse_binding_str("not: [valid: {{");
        assert!(result.is_err());
    }

    #[test]
    fn parse_binding_from_file() {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../contracts/aprender/binding.yaml");
        let reg = parse_binding(&path).unwrap();
        assert_eq!(reg.target_crate, "aprender");
        assert!(!reg.bindings.is_empty());
    }

    #[test]
    fn parse_binding_nonexistent_file() {
        let result = parse_binding(std::path::Path::new("/nonexistent/binding.yaml"));
        assert!(result.is_err());
    }

    // ── L5 binding-verification feature ──

    #[test]
    fn extract_fn_names_finds_definitions() {
        let mut names = std::collections::HashSet::new();
        extract_fn_names(
            "pub fn to_anthropic(m: &Message) -> Value {\n  async fn helper() {}\n",
            &mut names,
        );
        assert!(names.contains("to_anthropic"));
        assert!(names.contains("helper"));
    }

    #[test]
    fn extract_fn_names_respects_word_boundary() {
        let mut names = std::collections::HashSet::new();
        // `my_fn foo` must NOT register `foo` (the `fn ` is inside `my_fn `).
        extract_fn_names("let my_fn foo = 1;", &mut names);
        assert!(!names.contains("foo"));
    }

    #[test]
    fn function_defined_in_checks_membership() {
        let names: std::collections::HashSet<String> =
            ["to_anthropic".to_string()].into_iter().collect();
        let bound = KernelBinding {
            contract: "c-v1.yaml".into(),
            equation: "e".into(),
            module_path: None,
            function: Some("to_anthropic".into()),
            signature: None,
            status: ImplStatus::Implemented,
            notes: None,
        };
        assert!(bound.function_defined_in(&names));

        let missing = KernelBinding {
            function: Some("does_not_exist".into()),
            ..bound.clone()
        };
        assert!(!missing.function_defined_in(&names));

        // No function field → cannot be verified.
        let no_fn = KernelBinding {
            function: None,
            ..bound
        };
        assert!(!no_fn.function_defined_in(&names));
    }

    #[test]
    fn verified_downgrades_phantom_implemented_bindings() {
        // A temp source tree with exactly one real function.
        let dir = std::env::temp_dir().join(format!("bindver_{}", std::process::id()));
        let _ = std::fs::create_dir_all(&dir);
        std::fs::write(dir.join("lib.rs"), "pub fn real_one() {}\n").unwrap();

        let reg = BindingRegistry {
            version: "1.0.0".into(),
            target_crate: "t".into(),
            critical_path: vec![],
            bindings: vec![
                KernelBinding {
                    contract: "c-v1.yaml".into(),
                    equation: "a".into(),
                    module_path: None,
                    function: Some("real_one".into()),
                    signature: None,
                    status: ImplStatus::Implemented,
                    notes: None,
                },
                KernelBinding {
                    contract: "c-v1.yaml".into(),
                    equation: "b".into(),
                    module_path: None,
                    function: Some("phantom".into()),
                    signature: None,
                    status: ImplStatus::Implemented,
                    notes: None,
                },
            ],
        };

        let v = reg.verified(&dir);
        // Real fn stays implemented; phantom is downgraded.
        assert_eq!(v.bindings[0].status, ImplStatus::Implemented);
        assert_eq!(v.bindings[1].status, ImplStatus::NotImplemented);
        let _ = std::fs::remove_dir_all(&dir);
    }
}