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
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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! ONT-001 §5 ONT-4b / ONT-4c1 — the `shapes` gate: every shape in the corpus, applied to the graph the
//! extractors produce (`extract:pv-contract`, `extract:gguf`, `extract:apr-model`, and `resolves: receipt` over
//! the tracked ladder receipts), with a positive control planted every run and arming per shape.
//!
//! The answers, in ONT-6's lattice:
//!
//! - a shape block outside §3.6's subset, a receipt file with a foreign schema, or a malformed `armed_shapes` →
//!   [`ShapesOutcome::Unsupported`] — the DECLARATION's fault, exit 3, never a corpus verdict;
//! - no shape anywhere → [`ShapesOutcome::NoShapes`] → `Unknown{NoShapes}` (R-2: zero is a decline);
//! - shapes but no focus node → [`ShapesOutcome::NoFocus`] → `Unknown{NoFocus}`;
//! - a shape that `resolves: receipt` and not one receipt file in the tree → [`ShapesOutcome::NoReceipts`] →
//!   `Unknown{NoCheckable}` naming the directory (ONT-4c1; the lattice is ONT-6's 15 reasons, so the spec's
//!   `ReceiptUnmeasured` maps to `NoCheckable` with the reason spelled out — recorded in the row's receipt);
//! - the positive controls did not fire → [`ShapesOutcome::PositiveControlFailed`] (R-3);
//! - warnings and no violation → `Unknown{Warn}`; a violation from an ARMED shape → `Fail` naming focus node
//!   and shape (PV-ONT-011); an extractor's rejection → `Fail` naming the file (PV-ONT-012); nothing → `Pass`.
//!
//! **Arming per shape (v4.6 §3.9).** `armed_shapes[]` in `lint-baseline.json`: absent → every shape armed;
//! present → a listed shape feeds the verdict, an unlisted one is computed and reported (`not_armed_shapes`,
//! its violations counted in `unarmed_violations` and named in the findings as warnings) and never feeds the
//! meet. The plant must draw its violation from an ARMED shape — a plant that only an unarmed shape can catch
//! proves nothing about the gate.
//!
//! **The positive controls.** `pc_shape`: a bare focus node of each shape's target class, drawn every run, must
//! violate at least one armed shape. `pc_extract` — one planted defect per extractor Σ marks implemented (R-3):
//! `pv-contract`, a contract stripped of `metadata` carries no `ont:kind`; `json`, a nested key the vocabulary does
//! not map is refused naming it; `gguf`, a corrupt magic is refused; `apr-model`, a header whose tensor count
//! disagrees with its index is refused; `code` and `lean`, as their modules state; `parity-receipt`, a record
//! stripped of `comparator` loses its comparator edge. All of them every run, in memory.

use std::collections::{BTreeMap, BTreeSet};
use std::path::Path;
use std::time::Instant;

use crate::ontology::arming::ArmedShapes;
use crate::ontology::extract::release_inputs::Subject;
use crate::ontology::extract::{
    self, apr_model, code, gguf, json, lean, parity_receipt, pv_contract, release_evidence,
    ExtractFailure,
};
use crate::ontology::rdf::{iri, Graph, Term, RDF_TYPE};
use crate::ontology::receipts;
use crate::ontology::shapes::{self, NodeShape, Report, Severity, ShapeError};
use crate::ontology::verdict::Reason;
use crate::ontology::w3c;

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

/// The IRI of the planted focus node.
pub const PLANT_ID: &str = "__pc_shape__";

/// What one `shapes` run answers. Only [`ShapesOutcome::Ran`] is a verdict about the corpus.
#[derive(Debug)]
pub enum ShapesOutcome {
    /// A shape uses a component outside §3.6, a receipt has a foreign schema, or the baseline is malformed.
    Unsupported(ShapeError),
    /// An extractor could not do its walk — an `entity: {type: json}` contract with a missing `ref`, a non-JSON
    /// document, an incomplete `vocabulary`, an unmapped nested key; a ladder receipt with a foreign schema. The
    /// DECLARATION's fault, like `Unsupported`: exit 3.
    ExtractFailed(ExtractFailure),
    /// Not one contract carries a shape.
    NoShapes { contracts_checked: usize },
    /// Shapes exist, but no node in the graph has any of their target classes.
    NoFocus { shapes_n: usize },
    /// A shape resolves receipts and the tree holds none under `evidence/dogfood/models/`.
    NoReceipts { shapes_n: usize, dir: String },
    /// PMAT-3577 — `extract:parity-receipt` matched a different number of focus nodes than
    /// `evidence/parity/EXPECTED_RECEIPTS` says the tree holds, or it refused a record by name. An
    /// extractor that silently sees the wrong corpus reports the same "no violations" as one that sees
    /// all of it, so this is `Unknown{WrongCorpus}` — never `Pass`, never a fabricated `Fail`.
    WrongCorpus {
        shapes_n: usize,
        expected: usize,
        found: usize,
        refused: Vec<String>,
    },
    /// A positive control did not fire.
    PositiveControlFailed {
        shapes_n: usize,
        focus_nodes_n: usize,
        which: String,
    },
    /// A vendored W3C SHACL-Core case did not pass (ONT-4b2): the validator disagrees with the standard on a
    /// form it claims, so no corpus verdict is trusted until it agrees — `Unknown{Differential}`.
    Differential {
        shapes_n: usize,
        focus_nodes_n: usize,
        passed: usize,
        n: usize,
        failed: Vec<String>,
    },
    /// Shapes ran over the corpus, and the controls fired.
    Ran {
        result: Box<GateResult>,
        findings: Vec<LintFinding>,
    },
}

/// Every shape under `contract_dir`, parsed, with the contract file (repo-relative) that declares it. The
/// first unsupported one is the whole answer; a shape id declared twice is malformed.
pub fn collect_shapes(
    contract_dir: &Path,
) -> Result<(Vec<(NodeShape, String)>, usize), ShapeError> {
    let mut shapes: Vec<(NodeShape, String)> = Vec::new();
    let mut checked = 0usize;
    for (stem, rel, doc) in pv_contract::documents(contract_dir) {
        checked += 1;
        for shape in shapes::parse_shapes(&stem, &doc)? {
            if let Some((_, other)) = shapes.iter().find(|(s, _)| s.id == shape.id) {
                return Err(ShapeError::Malformed {
                    shape: shape.id.clone(),
                    what: format!("declared twice: in {other} and in {rel}"),
                });
            }
            shapes.push((shape, rel.clone()));
        }
    }
    Ok((shapes, checked))
}

/// `(shape id, declaring file)` for every shape in the corpus — the arming ratchet's view of "what exists".
pub fn declared_shapes(contract_dir: &Path) -> Result<Vec<(String, String)>, ShapeError> {
    Ok(collect_shapes(contract_dir)?
        .0
        .into_iter()
        .map(|(s, f)| (s.id, f))
        .collect())
}

/// The arming declaration for shapes, from `<contract_dir>/lint-baseline.json`.
fn armed_shapes_of(contract_dir: &Path) -> Result<ArmedShapes, ShapeError> {
    let text = std::fs::read_to_string(contract_dir.join("lint-baseline.json")).ok();
    ArmedShapes::from_baseline(text.as_deref()).map_err(|e| ShapeError::Malformed {
        shape: "lint-baseline.json".into(),
        what: e.to_string(),
    })
}

/// PMAT-3577: the parity corpus must be exactly what `EXPECTED_RECEIPTS` pins, and no record may be refused,
/// before anything is graded. Either miss is `WrongCorpus`, never a corpus verdict. (Extracted from
/// `run_shapes_gate` unchanged, to keep it under the complexity ratchet.)
fn parity_refusal(
    parity: &extract::parity_receipt::ParityStats,
    shapes_n: usize,
) -> Option<ShapesOutcome> {
    let refused = || parity.errors.iter().map(ToString::to_string).collect();
    if let Some((expected, found)) = parity.wrong_corpus() {
        return Some(ShapesOutcome::WrongCorpus {
            shapes_n,
            expected,
            found,
            refused: refused(),
        });
    }
    if !parity.errors.is_empty() {
        return Some(ShapesOutcome::WrongCorpus {
            shapes_n,
            expected: parity.expected.unwrap_or(parity.records),
            found: parity.records,
            refused: refused(),
        });
    }
    None
}

/// A torn JSONL line is the INPUT's fault and is carried as a warning on the entity's root shape — the
/// gate already rules that warnings alone are `Unknown{Warn}`, never a pass and never a silent drop.
fn carry_extract_warnings(report: &mut Report, warnings: &[extract::json::Warning]) {
    for w in warnings {
        report.results.push(shapes::ValidationResult {
            severity: Severity::Warning,
            focus: iri("json", &w.contract),
            shape: w.contract.clone(),
            path: Some(w.path.clone()),
            component: "extract:json",
            message: w.to_string(),
        });
    }
}

/// ONT-4b2: the vendored W3C cases, every run. A validator that fails the standard's own case for a form
/// it claims has no standing to grade the corpus: `Err(Differential)`. `Ok` carries the run, whose counts
/// the verdict reports.
fn w3c_checked(shapes_n: usize, focus_nodes_n: usize) -> Result<w3c::W3cRun, ShapesOutcome> {
    let w3c_run = w3c::run_all();
    let failed = w3c_run.failed();
    if failed.is_empty() {
        return Ok(w3c_run);
    }
    Err(ShapesOutcome::Differential {
        shapes_n,
        focus_nodes_n,
        passed: w3c_run.passed(),
        n: w3c_run.results.len(),
        failed,
    })
}

/// What `pv lint --gate shapes` is asked beyond the corpus (aprender#3715).
#[derive(Debug, Clone, Default)]
pub struct ShapesOptions {
    /// `--shape <id>`: grade only that shape FAMILY — the shape `<id>` and every shape whose id starts with
    /// `<id>.` — and arm it whatever `armed_shapes` says: a caller that names a shape is asking for its verdict,
    /// and "computed and reported" would let a release gate print violations and exit 0.
    pub only: Option<String>,
    /// `--release-*`: the release subject `extract:release-evidence` reads. `None` → no release graph at all.
    pub release: Option<Subject>,
}

/// The shapes `only` selects, in declaration order; a name that selects nothing is the CALLER's error (exit 3),
/// never an empty pass.
fn select_family(
    declared: Vec<(NodeShape, String)>,
    only: Option<&str>,
) -> Result<Vec<NodeShape>, ShapeError> {
    let Some(id) = only else {
        return Ok(declared.into_iter().map(|(s, _)| s).collect());
    };
    let prefix = format!("{id}.");
    let family: Vec<NodeShape> = declared
        .into_iter()
        .map(|(s, _)| s)
        .filter(|s| s.id == id || s.id.starts_with(&prefix))
        .collect();
    if family.iter().any(|s| s.id == id) {
        Ok(family)
    } else {
        Err(ShapeError::Malformed {
            shape: id.to_string(),
            what: "--shape names no declared shape".into(),
        })
    }
}

/// Run the gate over `contract_dir`.
#[must_use]
pub fn run_shapes_gate(contract_dir: &Path) -> ShapesOutcome {
    run_shapes_gate_with(contract_dir, &ShapesOptions::default())
}

/// [`run_shapes_gate`] with `--shape` / `--release-*` (aprender#3715).
#[must_use]
pub fn run_shapes_gate_with(contract_dir: &Path, opts: &ShapesOptions) -> ShapesOutcome {
    let start = Instant::now();
    let (shapes, arming, checked) = match prepare(contract_dir, opts) {
        Ok(x) => x,
        Err(answer) => return answer,
    };

    // ONE walk (R-18): every extractor, the json documents, the ladder receipts joined to the rungs — the same
    // graph `pv extract` writes — plus, when a release subject is given, the release evidence (#3715).
    let extraction = match extract::all_with(contract_dir, opts.release.as_ref()) {
        Ok(x) => x,
        Err(e) => return ShapesOutcome::ExtractFailed(e),
    };
    // PMAT-3577: the count is pinned before anything is graded. A miss here is not a corpus verdict.
    if let Some(refusal) = parity_refusal(&extraction.parity, shapes.len()) {
        return refusal;
    }
    let graph = &extraction.graph;

    let (mut report, plant_violations) = validate_with_plant(graph, &shapes, &arming);
    if opts.only.is_some() {
        order_by_family(&mut report, &shapes);
    }
    carry_extract_warnings(&mut report, &extraction.warnings);
    let pc_extract = extract_controls();
    let unmeasured = needs_receipts(&shapes) && extraction.receipts.is_empty();
    if let Some(d) = decline(
        shapes.len(),
        &report,
        unmeasured,
        plant_violations,
        &pc_extract,
    ) {
        return d;
    }
    let w3c_run = match w3c_checked(shapes.len(), report.focus_nodes_n) {
        Ok(run) => run,
        Err(differential) => return differential,
    };

    let counted = findings_of(
        &report,
        &arming,
        graph,
        &extraction.gguf,
        &extraction.apr_model,
    );
    let passed = counted.violations == 0;
    let verdict = verdict_of(&counted);
    let by_shape = by_shape(graph, &shapes);
    let (armed_names, not_armed): (Vec<String>, Vec<String>) = shapes
        .iter()
        .map(|s| s.id.clone())
        .partition(|id| arming.is_armed(id));
    let by_entity_type = by_entity_type(&extraction);
    let duration = u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX);
    let result = GateResult {
        name: "shapes".into(),
        passed,
        skipped: false,
        verdict,
        duration_ms: duration,
        detail: GateDetail::Validate {
            contracts: checked,
            errors: counted.violations,
            warnings: counted.warnings,
            error_messages: counted
                .findings
                .iter()
                .filter(|f| f.severity == RuleSeverity::Error)
                .map(|f| f.message.clone())
                .collect(),
        },
        extra: Some(GateExtra::Shapes {
            shapes_n: shapes.len(),
            focus_nodes_n: report.focus_nodes_n,
            pc_shape: "fired".into(),
            plant_violations,
            violations: counted.violations,
            warnings: counted.warnings,
            by_shape,
            triples: graph.len(),
            armed_shapes: armed_names,
            not_armed_shapes: not_armed,
            unarmed_violations: counted.unarmed_violations,
            by_entity_type,
            pc_extract,
            receipts: extraction.resolve.receipts,
            witnesses: extraction.resolve.witnesses,
            hex_mismatches: extraction.resolve.hex_mismatches,
            unmeasured_rows: extraction.resolve.unmeasured_rows,
            w3c_cases_passed: w3c_run.passed(),
            w3c_cases_n: w3c_run.results.len(),
            symbols_resolved: extraction.code.resolved,
            symbols_unresolved: extraction.code.unresolved,
            lean_statements: extraction.lean.statements,
            lean_refs_unresolved: extraction.lean.refs_unresolved.len(),
            release: extraction.release.clone().map(Box::new),
        }),
    };
    ShapesOutcome::Ran {
        result: Box::new(result),
        findings: counted.findings,
    }
}

/// The shape set this run grades and its arming, or the answer that stands in for a verdict (unsupported or
/// malformed shapes, no shapes at all, a `--shape` naming nothing). A named family is armed whatever
/// `armed_shapes` says (#3715).
fn prepare(
    contract_dir: &Path,
    opts: &ShapesOptions,
) -> Result<(Vec<NodeShape>, ArmedShapes, usize), ShapesOutcome> {
    let (declared, checked) = collect_shapes(contract_dir).map_err(ShapesOutcome::Unsupported)?;
    if declared.is_empty() {
        return Err(ShapesOutcome::NoShapes {
            contracts_checked: checked,
        });
    }
    let baseline = armed_shapes_of(contract_dir).map_err(ShapesOutcome::Unsupported)?;
    let arming = if opts.only.is_some() {
        ArmedShapes::All
    } else {
        baseline
    };
    let shapes =
        select_family(declared, opts.only.as_deref()).map_err(ShapesOutcome::Unsupported)?;
    Ok((shapes, arming, checked))
}

/// A named family reports in the order its contract declares it: the release, its hosts, its context, its
/// kernels, THEN its model cells (#3715: a kernel that diverges across arches is named before any model cell it
/// breaks). Stable, so the validator's order holds within a shape.
fn order_by_family(report: &mut Report, shapes: &[NodeShape]) {
    let rank = |id: &str| shapes.iter().position(|s| s.id == id).unwrap_or(usize::MAX);
    report.results.sort_by_key(|r| rank(&r.shape));
}

/// Does any shape resolve its values against the tracked ladder receipts?
fn needs_receipts(shapes: &[NodeShape]) -> bool {
    shapes.iter().any(|s| {
        s.properties
            .iter()
            .any(|p| p.resolves.as_deref() == Some("receipt"))
    })
}

/// Violations fail; warnings alone are `Unknown{Warn}`, never a pass; nothing is `Pass`.
fn verdict_of(counted: &Counted) -> Verdict {
    if counted.violations > 0 {
        Verdict::Fail
    } else if counted.warnings > 0 {
        Verdict::Unknown(Reason::Warn)
    } else {
        Verdict::Pass
    }
}

/// `shape=focus-count` per shape, sorted.
fn by_shape(graph: &Graph, shapes: &[NodeShape]) -> Vec<String> {
    let mut out: Vec<String> = shapes
        .iter()
        .map(|s| {
            let n = shapes::instances_closed(graph, &s.target_class).len();
            format!("{}={}", s.id, n)
        })
        .collect();
    out.sort();
    out
}

/// Focus nodes each extractor produced.
fn by_entity_type(extraction: &extract::Extraction) -> BTreeMap<String, usize> {
    [
        (
            "pv-contract",
            extraction
                .graph
                .instances_of(&crate::ontology::rdf::ont("Contract"))
                .len(),
        ),
        (
            "gguf",
            extraction.gguf.rungs.len() + extraction.gguf.files_read,
        ),
        ("apr-model", extraction.apr_model.files_read),
        // ONT-4c3: registered in Σ and implemented, so it is counted here like every other entity
        // type. Without this key a probe asking `by_entity_type["parity-receipt"]` reads ABSENT —
        // and an absent key is not zero, so a consumer that treats it as one measures nothing and
        // calls it a pass. The same shape as #3610, one map over.
        ("parity-receipt", extraction.parity.records),
        ("code", extraction.code.symbols),
        ("lean", extraction.lean.statements),
    ]
    .into_iter()
    .map(|(k, v)| (k.to_string(), v))
    .collect()
}

/// The answers that are not corpus verdicts, in the order they are asked: no focus node, receipts needed and
/// none tracked, the plant silent, an extractor control silent. `None` when the corpus gets a verdict.
fn decline(
    shapes_n: usize,
    report: &Report,
    unmeasured: bool,
    plant_violations: usize,
    pc_extract: &BTreeMap<String, String>,
) -> Option<ShapesOutcome> {
    if report.focus_nodes_n == 0 {
        return Some(ShapesOutcome::NoFocus { shapes_n });
    }
    if unmeasured {
        return Some(ShapesOutcome::NoReceipts {
            shapes_n,
            dir: receipts::EVIDENCE_DIR.to_string(),
        });
    }
    let silent = if plant_violations == 0 {
        Some("pc_shape".to_string())
    } else {
        pc_extract
            .iter()
            .find(|(_, v)| v.as_str() != "fired")
            .map(|(k, _)| format!("pc_extract.{k}"))
    };
    silent.map(|which| ShapesOutcome::PositiveControlFailed {
        shapes_n,
        focus_nodes_n: report.focus_nodes_n,
        which,
    })
}

/// The extractor positive controls (R-3: one planted defect per registered extractor), run in memory every gate
/// run, keyed by the Σ entity type each extractor reads. The key set must equal Σ's implemented entity types —
/// [`tests::every_implemented_entity_type_in_sigma_has_an_extract_control_and_it_fires`] holds the two together.
fn extract_controls() -> BTreeMap<String, String> {
    let apr_sample = apr_model::minimal_container(2);
    [
        ("pv-contract", pv_contract::positive_control()),
        ("json", json::positive_control()),
        ("gguf", gguf::positive_control()),
        ("apr-model", apr_model::positive_control(&apr_sample)),
        ("code", code::positive_control()),
        ("lean", lean::positive_control()),
        (
            "parity-receipt",
            parity_receipt::positive_control(&parity_receipt::control_sample()),
        ),
        // aprender#3715: drawn every run, subject or not — a cell owed without a receipt stays a node
        ("release-evidence", release_evidence::positive_control()),
    ]
    .into_iter()
    .map(|(k, fired)| {
        (
            k.to_string(),
            if fired { "fired" } else { "not-fired" }.to_string(),
        )
    })
    .collect()
}

/// The findings of one run, and the counts the verdict is made of.
struct Counted {
    findings: Vec<LintFinding>,
    /// From ARMED shapes, plus every extractor rejection.
    violations: usize,
    warnings: usize,
    /// From unarmed shapes: reported, never in the meet.
    unarmed_violations: usize,
}

fn findings_of(
    report: &Report,
    arming: &ArmedShapes,
    graph: &Graph,
    gguf_stats: &gguf::GgufStats,
    apr_stats: &apr_model::AprStats,
) -> Counted {
    let mut c = Counted {
        findings: Vec::new(),
        violations: 0,
        warnings: 0,
        unarmed_violations: 0,
    };
    for r in &report.results {
        let armed = arming.is_armed(&r.shape);
        let severity = match (armed, r.severity) {
            (true, Severity::Violation) => {
                c.violations += 1;
                RuleSeverity::Error
            }
            (true, Severity::Warning) => {
                c.warnings += 1;
                RuleSeverity::Warning
            }
            (false, Severity::Violation) => {
                c.unarmed_violations += 1;
                RuleSeverity::Warning
            }
            (false, Severity::Warning) => RuleSeverity::Warning,
        };
        // a model node is a sha256 IRI; say which rung that is, since that is what a person acts on
        let rung = graph
            .objects(&r.focus, &gguf::model("id"))
            .first()
            .and_then(|t| t.as_literal())
            .map(|(id, _)| format!(" (rung {id})"))
            .unwrap_or_default();
        let mut f = LintFinding::new(
            "PV-ONT-011",
            severity,
            format!(
                "{}{rung} violates shape `{}`{} ({}): {}",
                shapes::short(&r.focus),
                r.shape,
                if armed { "" } else { " [not armed]" },
                r.component,
                r.message
            ),
            format!("contracts/{}.yaml", r.shape),
        );
        f.contract_stem = Some(r.shape.clone());
        c.findings.push(f);
    }
    for e in gguf_stats.errors.iter().chain(apr_stats.errors.iter()) {
        c.violations += 1;
        let mut f = LintFinding::new(
            "PV-ONT-012",
            RuleSeverity::Error,
            format!("extractor refused {}: {}", e.file, e.what),
            e.file.clone(),
        );
        f.contract_stem = None;
        c.findings.push(f);
    }
    c
}

/// Validate the corpus graph plus the plant. Returns the corpus report (the plant's results removed) and how
/// many violations the plant drew FROM ARMED SHAPES.
#[must_use]
pub fn validate_with_plant(
    graph: &Graph,
    shapes: &[NodeShape],
    arming: &ArmedShapes,
) -> (Report, usize) {
    let mut planted = graph.clone();
    let plant = iri("contract", PLANT_ID);
    let classes: BTreeSet<&str> = shapes
        .iter()
        .filter(|s| !s.target_class.is_empty())
        .map(|s| s.target_class.as_str())
        .collect();
    for c in classes {
        planted.insert(plant.clone(), RDF_TYPE, Term::iri(c));
    }
    let mut report = shapes::validate(&planted, shapes);
    let plant_violations = report
        .results
        .iter()
        .filter(|r| {
            r.focus == plant && r.severity == Severity::Violation && arming.is_armed(&r.shape)
        })
        .count();
    report.results.retain(|r| r.focus != plant);
    report.focus_nodes_n = report.focus_nodes_n.saturating_sub(1);
    (report, plant_violations)
}

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

    fn fixture(name: &str) -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures/ont")
            .join(name)
    }

    fn extra(result: &GateResult) -> (usize, usize, usize, Vec<String>, Vec<String>) {
        match &result.extra {
            Some(GateExtra::Shapes {
                shapes_n,
                focus_nodes_n,
                plant_violations,
                armed_shapes,
                not_armed_shapes,
                ..
            }) => (
                *shapes_n,
                *focus_nodes_n,
                *plant_violations,
                armed_shapes.clone(),
                not_armed_shapes.clone(),
            ),
            other => panic!("{other:?}"),
        }
    }

    #[test]
    fn a_conforming_fixture_corpus_passes_and_the_plant_fires() {
        match run_shapes_gate(&fixture("shapes-ok")) {
            ShapesOutcome::Ran { result, findings } => {
                assert!(result.passed, "{findings:?}");
                assert_eq!(result.verdict, Verdict::Pass);
                let (shapes_n, focus, plant, armed, not_armed) = extra(&result);
                assert_eq!(shapes_n, 1);
                assert_eq!(focus, 3, "the plant is not counted");
                assert_eq!(plant, 1, "one minCount property → exactly one");
                assert_eq!(
                    armed,
                    vec!["shape-holder".to_string()],
                    "no baseline key → all armed"
                );
                assert!(not_armed.is_empty());
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn a_corpus_violation_fails_naming_focus_node_and_shape() {
        match run_shapes_gate(&fixture("shapes-violation")) {
            ShapesOutcome::Ran { result, findings } => {
                assert!(!result.passed);
                assert_eq!(result.verdict, Verdict::Fail);
                assert_eq!(findings.len(), 1, "{findings:?}");
                assert!(
                    findings[0].message.contains("ont:contract/bad-KIND"),
                    "{}",
                    findings[0].message
                );
                assert!(
                    findings[0].message.contains("shape `shape-holder`"),
                    "{}",
                    findings[0].message
                );
                assert_eq!(findings[0].rule_id, "PV-ONT-011");
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn warnings_only_is_unknown_warn_not_pass() {
        match run_shapes_gate(&fixture("shapes-warn")) {
            ShapesOutcome::Ran { result, .. } => {
                assert_eq!(result.verdict, Verdict::Unknown(Reason::Warn));
                assert!(result.passed, "a warning is not a failure");
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn no_shapes_no_focus_and_unsupported_are_not_corpus_verdicts() {
        assert!(matches!(
            run_shapes_gate(&fixture("sigma-ok")),
            ShapesOutcome::NoShapes { .. }
        ));
        assert!(matches!(
            run_shapes_gate(&fixture("shapes-nofocus")),
            ShapesOutcome::NoFocus { shapes_n: 1 }
        ));
        match run_shapes_gate(&fixture("shapes-unsupported")) {
            ShapesOutcome::Unsupported(ShapeError::Unsupported { component, .. }) => {
                assert_eq!(component, "targetNode");
            }
            other => panic!("expected Unsupported, got {other:?}"),
        }
    }

    #[test]
    fn a_shape_set_that_cannot_fire_is_a_positive_control_failure() {
        // a shape with no minCount: a bare plant conforms, so nothing proves the shapes are live
        assert!(matches!(
            run_shapes_gate(&fixture("shapes-noplant")),
            ShapesOutcome::PositiveControlFailed { .. }
        ));
    }

    // ── ONT-4c1 ──────────────────────────────────────────────────────────────────────────────────────────

    fn ladder(name: &str) -> ShapesOutcome {
        run_shapes_gate(&fixture(name).join("contracts"))
    }

    #[test]
    fn an_all_green_ladder_passes_with_measured_armed_and_green_reported_only() {
        match ladder("ladder-green") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(result.verdict, Verdict::Pass, "{findings:?}");
                let (_, _, plant, armed, not_armed) = extra(&result);
                assert!(plant >= 1);
                assert_eq!(
                    armed,
                    vec!["ladder-measured".to_string(), "ont-ladder-v1".to_string()]
                        .into_iter()
                        .filter(|a| armed.contains(a))
                        .collect::<Vec<_>>()
                );
                assert!(armed.contains(&"ladder-measured".to_string()));
                assert_eq!(not_armed, vec!["ladder-green".to_string()]);
                match &result.extra {
                    Some(GateExtra::Shapes {
                        by_entity_type,
                        pc_extract,
                        witnesses,
                        unarmed_violations,
                        ..
                    }) => {
                        assert_eq!(by_entity_type.get("gguf"), Some(&2));
                        assert_eq!(pc_extract.get("gguf").map(String::as_str), Some("fired"));
                        assert_eq!(
                            pc_extract.get("apr-model").map(String::as_str),
                            Some("fired")
                        );
                        assert_eq!(*witnesses, 4, "two rungs × two hosts");
                        assert_eq!(*unarmed_violations, 0, "all green: ladder-green holds too");
                    }
                    other => panic!("{other:?}"),
                }
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn a_fallback_backend_is_reported_by_the_unarmed_green_shape_and_does_not_fail_the_gate() {
        match ladder("ladder-fallback") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(
                    result.verdict,
                    Verdict::Pass,
                    "ladder-green is not armed here"
                );
                let named: Vec<&LintFinding> = findings
                    .iter()
                    .filter(|f| f.message.contains("[not armed]"))
                    .collect();
                assert_eq!(named.len(), 1, "{findings:?}");
                assert!(
                    named[0].message.contains("missingGreenHost"),
                    "{}",
                    named[0].message
                );
                assert!(
                    named[0].message.contains("gx10"),
                    "names the host: {}",
                    named[0].message
                );
                match &result.extra {
                    Some(GateExtra::Shapes {
                        unarmed_violations, ..
                    }) => assert_eq!(*unarmed_violations, 1),
                    other => panic!("{other:?}"),
                }
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn arming_the_green_shape_on_the_fallback_fixture_fails_naming_rung_and_host() {
        match ladder("ladder-fallback-armed") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(result.verdict, Verdict::Fail);
                let f = findings
                    .iter()
                    .find(|f| f.message.contains("ladder-green"))
                    .expect("the green shape fired");
                assert!(f.message.contains("gx10"), "{}", f.message);
                assert!(!f.message.contains("[not armed]"));
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn a_wrong_hex_in_a_receipt_row_fails_ladder_measured_naming_both() {
        match ladder("ladder-wronghex") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(result.verdict, Verdict::Fail);
                let f = findings
                    .iter()
                    .find(|f| f.message.contains("receiptHexMismatch"))
                    .expect("the mismatch fired");
                assert!(f.message.contains("ladder-measured"), "{}", f.message);
                assert!(f.message.contains("lambda.json"), "{}", f.message);
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn a_row_without_sha256_is_not_a_witness_so_a_rung_with_only_such_rows_fails_measured() {
        match ladder("ladder-nosha") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(result.verdict, Verdict::Fail);
                assert!(
                    findings.iter().any(|f| f.message.contains("parityReceipt")),
                    "{findings:?}"
                );
                match &result.extra {
                    Some(GateExtra::Shapes {
                        witnesses,
                        unmeasured_rows,
                        ..
                    }) => {
                        assert_eq!(*witnesses, 0);
                        assert!(*unmeasured_rows >= 1);
                    }
                    other => panic!("{other:?}"),
                }
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn no_receipt_file_at_all_is_a_decline_naming_the_directory() {
        match ladder("ladder-noreceipts") {
            ShapesOutcome::NoReceipts { dir, .. } => assert_eq!(dir, receipts::EVIDENCE_DIR),
            other => panic!("expected NoReceipts, got {other:?}"),
        }
    }

    #[test]
    fn a_foreign_receipt_schema_is_refused_by_name() {
        match ladder("ladder-badschema") {
            ShapesOutcome::ExtractFailed(ExtractFailure::Receipt(e)) => {
                assert!(e.file.ends_with("lambda.json"), "{}", e.file);
                assert!(e.what.contains("refused by name"), "{}", e.what);
            }
            other => panic!("expected ExtractFailed, got {other:?}"),
        }
    }

    #[test]
    fn a_lying_apr_header_is_an_extractor_rejection_naming_the_file() {
        match ladder("ladder-lyingapr") {
            ShapesOutcome::Ran { result, findings } => {
                assert_eq!(result.verdict, Verdict::Fail);
                let f = findings
                    .iter()
                    .find(|f| f.rule_id == "PV-ONT-012")
                    .expect("PV-ONT-012");
                assert!(f.message.contains("lying.apr"), "{}", f.message);
                assert!(f.message.contains("header says 3"), "{}", f.message);
            }
            other => panic!("expected Ran, got {other:?}"),
        }
    }

    #[test]
    fn the_plant_must_fire_from_an_armed_shape() {
        // ladder-plantunarmed arms only ladder-green (no minCount): the plant draws nothing from an armed shape
        assert!(matches!(
            ladder("ladder-plantunarmed"),
            ShapesOutcome::PositiveControlFailed { .. }
        ));
    }

    #[test]
    fn every_implemented_entity_type_in_sigma_has_an_extract_control_and_it_fires() {
        // PMAT-3704 — R-3: `pc_extract`, one planted defect per registered extractor, every run. The control set
        // was a hand-written array beside Σ with nothing tying the two together, so `parity-receipt` (#3600) and
        // `json` (#3516) shipped as implemented entity types the gate never controlled — the same shape as #3624
        // for `by_entity_type`, and as bashrs#266's two lists. Σ is this build's registry (its `extractors[]`
        // name this crate's readers), so the two sets must be EQUAL: an implemented type without a control fails,
        // and so does a control for a type Σ does not implement.
        let sigma_path =
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../contracts/ontology.yaml");
        let text = std::fs::read_to_string(&sigma_path).expect("contracts/ontology.yaml");
        let sigma = crate::ontology::sigma::Sigma::from_yaml(&text).expect("Σ parses");
        let implemented: BTreeSet<String> = sigma
            .entity_types
            .iter()
            .filter(|e| e.implemented)
            .map(|e| e.name.clone())
            .collect();
        assert!(
            !implemented.is_empty(),
            "Σ implements nothing — the comparison would be vacuous"
        );
        let controls = extract_controls();
        let controlled: BTreeSet<String> = controls.keys().cloned().collect();
        assert_eq!(
            controlled, implemented,
            "pc_extract keys (left) must equal Σ's implemented entity types (right)"
        );
        for (k, v) in &controls {
            assert_eq!(v, "fired", "pc_extract.{k}");
        }
    }
}