Skip to main content

provable_contracts/lint/
mod.rs

1//! Contract quality gate: validate + audit + score in one pass.
2//!
3//! Runs three sequential gates across all contracts in a directory:
4//! 1. **validate** — schema completeness (SCHEMA-001..013, PROVABILITY-001)
5//! 2. **audit** — traceability chain (paper→equation→obligation→test→proof)
6//! 3. **score** — 5-dimension quality score vs threshold
7//!
8//! Extended with SARIF output, rule catalog, config file, and findings.
9//! Spec: `docs/specifications/sub/lint.md`
10
11pub mod cache;
12pub mod capability_cells_gate;
13mod composition_gate;
14pub mod config;
15pub mod consistency_gate;
16pub mod diff;
17pub mod duplicate_stems;
18pub mod evidence_gate;
19pub mod finding;
20mod gates;
21pub mod ggplot2_core_gate;
22pub use gates::{collect_yaml_files, UNWALKED_DIRS};
23pub mod bindings_gate;
24mod gates_extended;
25pub mod ratchet_gates;
26pub mod references_gate;
27pub mod refinement_gate;
28pub mod refines_gate;
29pub mod relations_gate;
30pub mod rules;
31pub mod sarif;
32pub mod shapes_gate;
33pub mod sigma_gate;
34pub mod sigma_symbols;
35mod strict_test_binding;
36pub mod subsumption;
37pub mod tbox_gate;
38pub mod trend;
39pub mod valid_under_gate;
40
41use std::collections::{HashMap, HashSet};
42use std::path::Path;
43use std::time::Instant;
44
45use serde::Serialize;
46
47use self::finding::LintFinding;
48use self::gates::{
49    load_binding, load_contracts, run_audit_gate, run_score_gate, run_validate_gate,
50};
51use self::gates_extended::{
52    check_stale_suppressions, run_enforce_gate, run_enforcement_level_gate,
53    run_reverse_coverage_gate, run_verify_gate,
54};
55use self::rules::RuleSeverity;
56use crate::ontology::arming::{meet_armed, ArmedGates};
57use crate::ontology::verdict::Verdict;
58
59/// Result of a single gate execution.
60#[derive(Debug, Clone, Serialize)]
61pub struct GateResult {
62    pub name: String,
63    pub passed: bool,
64    pub skipped: bool,
65    /// ONT-001 §3.4: this gate's element of the one verdict lattice (`Verdict::from_gate(passed, skipped)`).
66    pub verdict: Verdict,
67    pub duration_ms: u64,
68    pub detail: GateDetail,
69    /// Structured payload for gates invented AFTER `GateDetail` was frozen.
70    ///
71    /// See [`GateExtra`] for why this second channel exists. Adding a field to a
72    /// struct is invisible to a `match` on `GateDetail`, which is the property
73    /// the 0.3.1 compatibility corpus depends on; adding a *variant* is not.
74    /// Serialised only when present, so existing JSON output is unchanged.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub extra: Option<GateExtra>,
77}
78
79/// Gate-specific detail payload.
80///
81/// # This enum is FROZEN at the eight variants published in `provable-contracts`
82/// 0.3.1 — do not add a ninth
83///
84/// `GateDetail` is public, is not `#[non_exhaustive]`, and 0.3.1 shipped 28 example
85/// programs that `match` it exhaustively. Those programs are vendored verbatim under
86/// `crates/facades/provable-contracts/compat/0.3.1/`, sha256-verified against their
87/// published checksums by `scripts/check_facade_compat.sh` (row R6), and compiled in
88/// the `ci` job that the required `gate` check depends on. A ninth variant is
89/// `error[E0004]` in that corpus, and the corpus cannot be edited to accommodate it —
90/// being uneditable is the whole point of a compatibility contract. Marking the enum
91/// `#[non_exhaustive]` does not help either: it makes the *existing* exhaustive
92/// matches non-exhaustive, which is the same compile error for the same reason.
93///
94/// So the vocabulary is closed. A gate added after 0.3.1 picks the truest of these
95/// eight for `detail` and carries its own shape in [`GateResult::extra`], which is a
96/// type 0.3.1 never names and is therefore free to grow.
97#[derive(Debug, Clone, Serialize)]
98#[serde(tag = "type")]
99pub enum GateDetail {
100    #[serde(rename = "validate")]
101    Validate {
102        contracts: usize,
103        errors: usize,
104        warnings: usize,
105        error_messages: Vec<String>,
106    },
107    #[serde(rename = "audit")]
108    Audit {
109        contracts: usize,
110        findings: usize,
111        finding_messages: Vec<String>,
112    },
113    #[serde(rename = "score")]
114    Score {
115        contracts: usize,
116        min_score: f64,
117        mean_score: f64,
118        threshold: f64,
119        below_threshold: Vec<String>,
120    },
121    #[serde(rename = "verify")]
122    Verify {
123        total_refs: usize,
124        existing: usize,
125        missing: usize,
126    },
127    #[serde(rename = "enforce")]
128    Enforce {
129        equations_total: usize,
130        equations_with_pre: usize,
131        equations_with_post: usize,
132        equations_with_lean: usize,
133    },
134    #[serde(rename = "reverse_coverage")]
135    ReverseCoverage {
136        total_pub_fns: usize,
137        bound_fns: usize,
138        unbound_fns: usize,
139        coverage_pct: f64,
140        threshold_pct: f64,
141    },
142    #[serde(rename = "composition")]
143    Composition {
144        edges_checked: usize,
145        edges_satisfied: usize,
146        edges_broken: usize,
147    },
148    #[serde(rename = "skipped")]
149    Skipped { reason: String },
150}
151
152/// The `shapes` gate's positive controls and ONT-4c5's cell report — one boxed, flattened block of
153/// [`GateExtra::Shapes`].
154#[derive(Debug, Clone, Serialize)]
155pub struct ShapesControls {
156    /// The extractor positive controls: `gguf` (corrupt magic refused), `apr-model` (lying header refused).
157    pub pc_extract: std::collections::BTreeMap<String, String>,
158    /// ONT-4c5: per-shape positive controls (`capability-cells` → `fired`); the gate never reaches `Ran` with
159    /// one that is not.
160    pub pc_shapes: std::collections::BTreeMap<String, String>,
161    /// ONT-4c5: the capability-cell domain D and its NotRun cells at the current release — absent unless a
162    /// contract declares the `capability-cells` shape.
163    #[serde(skip_serializing_if = "Option::is_none")]
164    pub capability_cells: Option<capability_cells_gate::CapabilityCellsReport>,
165    /// PLOT-GG-001: the ggplot2 core rows and which are proven — absent unless a contract declares the
166    /// `ggplot2-core` shape or a core row exists.
167    #[serde(skip_serializing_if = "Option::is_none")]
168    pub ggplot2_core: Option<ggplot2_core_gate::Ggplot2CoreReport>,
169}
170
171/// Out-of-band structured detail for gates that post-date the frozen [`GateDetail`]
172/// vocabulary.
173///
174/// This type did not exist in `provable-contracts` 0.3.1, so no 0.3.1 program names
175/// it and none can `match` it. That is what makes it extensible where `GateDetail` is
176/// not, and it is `#[non_exhaustive]` from birth so the *next* post-0.3.1 gate does
177/// not have to repeat this exercise.
178// `Shapes` is 304 bytes against a 88-byte second-largest, and adding `declines` to it is what
179// crossed the threshold — `origin/main` at 237fbc32f lints clean, this branch does not, so the
180// finding is this PR's and not inherited.
181//
182// ALLOWED RATHER THAN BOXED, deliberately. `large_enum_variant` is a cost heuristic about copying
183// and stack size: a `GateExtra` is built ONCE PER GATE RUN, moved a handful of times, and then
184// serialised. There is no hot path here for 216 bytes to matter on, so the lint is measuring a cost
185// this type does not pay.
186//
187// The alternatives are worse. Boxing one field (clippy suggests `pc_extract`) reclaims 16 bytes and
188// does not clear the ratio, so it would be churn that silences nothing. Boxing the whole payload —
189// `Shapes(Box<ShapesExtra>)` — turns a struct variant into a newtype variant, which CHANGES THE
190// SERDE REPRESENTATION of a `#[serde(tag = "type")]` enum that downstream consumers parse; the SLK
191// gate reads this JSON. Breaking a wire format to satisfy a stack-size heuristic is the wrong trade.
192//
193// If `GateExtra` ever ends up in a loop or a large collection, this allow is the thing to revisit.
194#[allow(clippy::large_enum_variant)]
195#[derive(Debug, Clone, Serialize)]
196// One value per `pv lint` run, built once and serialised: the Shapes variant's size is not a hot-path cost.
197#[serde(tag = "type")]
198#[non_exhaustive]
199pub enum GateExtra {
200    /// PV-DUP-001: contract stems claimed by several files with divergent content.
201    #[serde(rename = "duplicate_stems")]
202    DuplicateStems {
203        /// Total ambiguous stems found in the tree.
204        divergent: usize,
205        /// How many of those are recorded in the ratchet baseline.
206        baselined: usize,
207        /// Ambiguous stems NOT in the baseline — these fail the gate.
208        unbaselined: Vec<String>,
209        /// Baseline entries that no longer diverge — these fail the gate too.
210        stale: Vec<String>,
211        /// Every ambiguous stem, with its variant count and paths, for the report.
212        divergent_stems: Vec<String>,
213    },
214    /// ONT-2b: what Σ declares and what the corpus was checked against.
215    #[serde(rename = "sigma")]
216    Sigma {
217        /// `entity_types` Σ declares.
218        entity_types: usize,
219        /// `roles` Σ declares.
220        roles: usize,
221        /// `symbols` Σ declares.
222        symbols: usize,
223        /// Contract files read (never counting `ontology.yaml` itself).
224        contracts_checked: usize,
225        /// Findings: undeclared entity types, undeclared roles, undeclared glyphs.
226        violations: usize,
227        /// `formal:` expressions read.
228        formal_total: usize,
229        /// Of those, how many carry NO symbol Σ declares — the `formal_prose` debt, shrink-only.
230        formal_prose: usize,
231    },
232    /// ONT-4: the corpus's typed relations, checked against Σ's roles.
233    #[serde(rename = "relations")]
234    Relations {
235        /// Typed edges after symmetric closure.
236        relations_n: usize,
237        /// Contracts carrying a `relations:` block.
238        contracts_with_relations: usize,
239        /// `role=count` per role used.
240        roles_used: Vec<String>,
241        /// Cycles through acyclic roles, as `role: a -> b -> a`.
242        cycles: Vec<String>,
243        /// `metadata.depends_on` edges, read and counted, never rewritten (R-5).
244        legacy_depends_on: usize,
245        /// Of those, how many name no contract — ratcheted shrink-only in the baseline.
246        legacy_unresolved_depends_on: usize,
247        /// Findings.
248        violations: usize,
249    },
250    /// ONT-8: one evidence block — PROV-O names, one L-enum, every entity type.
251    #[serde(rename = "evidence")]
252    Evidence {
253        /// Contract files read.
254        contracts_checked: usize,
255        /// Of those, how many carry an `evidence` block.
256        contracts_with_evidence: usize,
257        /// Distinct `entity.type` among the contracts carrying evidence — counted, never branched on (R-17).
258        entity_types_checked: usize,
259        /// Those types, sorted.
260        entity_types: Vec<String>,
261        /// `enum`: levels are parsed through `ProofLevel`, never matched against a list kept in the gate.
262        levels_source: String,
263        /// `level=count` over the evidence blocks that passed every rule.
264        by_level: Vec<String>,
265        /// The census `git_sha` a `[V]` claim binds to; `None` (the 2026-09-16 ruling) binds it to the repository.
266        census_git_sha: Option<String>,
267        /// `[V]` shas git could not look for — non-zero makes the verdict `Unknown{ToolAbsent}`, never `Pass`.
268        unresolved_git_shas: usize,
269        /// Findings.
270        violations: usize,
271    },
272    /// ONT-7: kernel-kind contracts carry a world index (`metadata.valid_under.world`, a key of Σ's `worlds`).
273    #[serde(rename = "valid_under")]
274    ValidUnder {
275        /// The worlds Σ declares — the index a `valid_under.world` must resolve into.
276        worlds: Vec<String>,
277        /// Contract files read.
278        contracts_checked: usize,
279        /// Of those, kernel-kind and not a registry — the class the row obliges.
280        kernel_contracts: usize,
281        /// Contracts (any kind) carrying `metadata.valid_under`.
282        contracts_with_valid_under: usize,
283        /// Kernel-kind contracts carrying none — the debt, shrink-only against the baseline.
284        contracts_without_valid_under: usize,
285        /// The top-level `contracts_without_valid_under` in `lint-baseline.json`; `None` = not recorded.
286        baseline: Option<usize>,
287        /// `world=count` over the contracts whose `valid_under` passed every rule.
288        by_world: Vec<String>,
289        /// Findings.
290        violations: usize,
291    },
292    /// PVL-001 EV-11: Lean theorem modules named by a book page — the `unpaired_theorem_modules` ratchet.
293    #[serde(rename = "theorem_pairing")]
294    TheoremPairing {
295        /// The Lean base the modules were read under.
296        lean_base: String,
297        /// `.md` pages read under the book roots.
298        book_pages: usize,
299        /// `.lean` files under `<base>/ProvableContracts/Theorems/`.
300        theorem_modules: usize,
301        /// Of those, named in full by at least one book page.
302        paired: usize,
303        /// The debt, shrink-only against the baseline.
304        unpaired_theorem_modules: usize,
305        /// The top-level `unpaired_theorem_modules` in `lint-baseline.json`; `None` = not recorded (reported only).
306        baseline: Option<usize>,
307        /// The unpaired modules, dotted, in byte order.
308        unpaired: Vec<String>,
309        /// Findings.
310        violations: usize,
311    },
312    /// PVL-001 EV-11: kernel-kind contracts with an empty `metadata.depends_on` — the ratchet.
313    #[serde(rename = "depends_on_present")]
314    DependsOnPresent {
315        /// Contract files parsed.
316        contracts_checked: usize,
317        /// Of those, kernel-kind and not a registry.
318        kernel_contracts: usize,
319        /// Kernel-kind contracts whose `metadata.depends_on` is empty — the debt, shrink-only.
320        contracts_without_depends_on: usize,
321        /// The top-level `contracts_without_depends_on` in `lint-baseline.json`; `None` = not recorded (reported only).
322        baseline: Option<usize>,
323        /// Findings.
324        violations: usize,
325    },
326    /// aprender#6397: `metadata.references` repo paths that do not exist — the ratchet.
327    #[serde(rename = "references_resolve")]
328    ReferencesResolve {
329        /// Contract files parsed.
330        contracts_checked: usize,
331        /// References classified as repo paths.
332        path_references: usize,
333        /// Repo-path references that do not exist — the debt, shrink-only.
334        dead_references: usize,
335        /// The top-level `dead_references` in `lint-baseline.json`; `None` = not recorded.
336        baseline: Option<usize>,
337        /// `stem: path`, in byte order.
338        dead: Vec<String>,
339        /// Findings.
340        violations: usize,
341    },
342    /// PVL-001 EV-8a (#4202): `status: proved` claims no green `discharge-summary.json` derives — the ratchet.
343    #[serde(rename = "proved_is_derived")]
344    ProvedIsDerived {
345        /// The summary read (beside the Lean base); `None` = no Lean base.
346        summary: Option<String>,
347        /// Why it derived nothing when it could not be read; `None` = it was read.
348        summary_error: Option<String>,
349        /// Every Lean step ran and passed. Only a green summary derives a claim.
350        summary_green: bool,
351        /// Contract files parsed.
352        contracts_checked: usize,
353        /// `proof_obligations[].lean.status: proved` claims.
354        proved_claims: usize,
355        /// Of those, not derived — the debt, shrink-only against the baseline, and it must reach 0.
356        underived_proved_claims: usize,
357        /// The top-level `underived_proved_claims` in `lint-baseline.json`; `None` = not recorded (reported only).
358        baseline: Option<usize>,
359        /// The underived claims, as `contract: theorem`, in contract order.
360        underived: Vec<String>,
361        /// Findings.
362        violations: usize,
363    },
364    /// PVL-001 EV-7a (#4200): `<lean>/Challenge/` against its regeneration (`pv challenge check`).
365    #[serde(rename = "challenge_fresh")]
366    ChallengeFresh {
367        /// The Lean dir judged.
368        lean_dir: String,
369        /// Challenge files the contracts render.
370        files: usize,
371        /// Extra, missing or differing files, one line each.
372        stale: Vec<String>,
373        /// Bound roots whose statement could not be lifted, as `contract: fqn: why`.
374        unrestated: Vec<String>,
375    },
376    /// ONT-4b: the shapes gate — every `shape:` block over the extracted graph, with the plant.
377    #[serde(rename = "shapes")]
378    Shapes {
379        /// `shape:` blocks read.
380        shapes_n: usize,
381        /// Distinct focus nodes across the shapes (the plant excluded).
382        focus_nodes_n: usize,
383        /// `fired` — the plant drew a violation; the gate never reaches `Ran` otherwise.
384        pc_shape: String,
385        /// How many violations the plant drew.
386        plant_violations: usize,
387        /// Corpus violations (the plant excluded).
388        violations: usize,
389        /// Corpus warnings.
390        warnings: usize,
391        /// `shape=focus-count` per shape.
392        by_shape: Vec<String>,
393        /// Triples in the extracted graph.
394        triples: usize,
395        /// ONT-4c1 (§3.9 per-shape arming): shapes that feed the verdict, in corpus order.
396        armed_shapes: Vec<String>,
397        /// Shapes computed and reported but not armed — their violations are in `unarmed_violations`.
398        not_armed_shapes: Vec<String>,
399        /// #3610: shapes that graded ZERO focus nodes, named — the reach the gate did not have.
400        ///
401        /// A separate list from `not_armed_shapes` on purpose. "Not armed by policy" and "armed and
402        /// measured nothing" are different facts, and folding the second into the first would file a
403        /// vacuity as a deliberate choice — which is how the defect hid in the first place.
404        ///
405        /// **This carries EVERY shape that graded zero, armed or unarmed**, and it is the only list
406        /// any of them appears in: a vacuity is in neither `armed_shapes` (the tool's claim about
407        /// what it MEASURED) nor `not_armed_shapes` (a policy choice it never made).
408        ///
409        /// The two differ in what they do to the verdict, not in whether they are listed here. An
410        /// ARMED vacuity drives the verdict to `Unknown(NoFocus)` and the run declines — unless an
411        /// armed shape that DID grade something found a violation, in which case the verdict is
412        /// `Fail` (a measured violation outranks a vacuity, #3622). An UNARMED one leaves the
413        /// verdict alone, because it never fed it. Both are named, because a reader
414        /// needs to know the gate looked at nothing for them either way.
415        ///
416        /// An earlier draft of this comment said an armed vacuity "does not reach here at all",
417        /// which was false — nothing returns early at the verdict, and both kinds reach this field.
418        /// A quorum lane caught the sentence; the code beside it had the matching bug.
419        declines: Vec<String>,
420        /// Violations from unarmed shapes (named in the findings as warnings; never in the meet).
421        unarmed_violations: usize,
422        /// Focus nodes each extractor produced: `pv-contract`, `gguf`, `apr-model`.
423        by_entity_type: std::collections::BTreeMap<String, usize>,
424        /// The positive controls (`pc_extract`, `pc_shapes`) and ONT-4c5's `capability_cells`, boxed and
425        /// FLATTENED: the JSON keys stay top-level where the §5 probes read them, and the variant stays under
426        /// clippy's large-enum-variant bound (it sat exactly at it before ONT-4c5).
427        #[serde(flatten)]
428        controls: Box<ShapesControls>,
429        /// Ladder receipt files read under `evidence/dogfood/models/`.
430        receipts: usize,
431        /// Receipt rows whose `sha256` equals a rung's.
432        witnesses: usize,
433        /// Receipt rows whose `sha256` differs from the rung's.
434        hex_mismatches: usize,
435        /// Receipt rows without a `sha256` (never a witness).
436        unmeasured_rows: usize,
437        /// ONT-4b2: vendored W3C SHACL-Core cases that passed this run, and how many are vendored.
438        w3c_cases_passed: usize,
439        w3c_cases_n: usize,
440        /// The ONT-4b2 extractor counters and ONT-4d's inheritance, FLATTENED into this object: the JSON keys
441        /// (`symbols_resolved`, …, `inherited_shapes_applied`) are unchanged. They are boxed only so the variant
442        /// stays under clippy's `large_enum_variant` once ONT-4d's two fields joined it.
443        #[serde(flatten)]
444        counters: Box<ShapesCounters>,
445        /// aprender#3715: what `extract:release-evidence` derived — absent unless a release subject was given.
446        #[serde(skip_serializing_if = "Option::is_none")]
447        release: Option<Box<crate::ontology::extract::release_evidence::ReleaseStats>>,
448        /// ONT-4c (v4.14): the README claim commands a merge-path workflow runs — the MEASURED set F-33 compares.
449        readme: MeasuredSet,
450        /// ONT-4c (v4.14): the same for `CLAUDE.md` (`extract:llm-context`).
451        claude_md: MeasuredSet,
452        /// ONT-4c (v4.14): whether the measured-set ratchets (F-33 and F-34) were checked this run.
453        ratchets: Ratchets,
454    },
455    /// ONT-5: the typed relations are jointly satisfiable, by a witness pv-sat wrote and this run re-checked.
456    #[serde(rename = "ont_consistency")]
457    Consistency {
458        /// Clauses a typed relation produced (`depends_on`/`refines` implications, `contradicts` conflicts).
459        checkable_n: usize,
460        /// Contracts asserted in force (every id no contract supersedes).
461        units: usize,
462        /// Typed edges through a role the encoding does not name.
463        unencoded_edges: usize,
464        /// `fired` — the checker refused the corrupt-core fixture this run.
465        pc_checker: String,
466        /// The contracts of a checked unsat core; empty when the witness is a model.
467        core: Vec<String>,
468        /// Findings.
469        violations: usize,
470        /// The witness this run checked.
471        witness: consistency_gate::WitnessReport,
472    },
473    /// ONT-4e (R-20): every `A refines B` is Liskov, by a witness pv-sat wrote and this run re-checked.
474    #[serde(rename = "refines")]
475    Refines(Box<refines_gate::RefinesCounters>),
476    /// ONT-3a: every implemented/partial binding resolves to workspace code, or the allowlist names it.
477    #[serde(rename = "bindings")]
478    Bindings(Box<bindings_gate::BindingsCounters>),
479    /// ONT-3b: every `model_of` resolves, and the unrefined-module count holds its shrink-only baseline.
480    #[serde(rename = "refinement")]
481    Refinement(Box<refinement_gate::RefinementCounters>),
482}
483
484/// Counters a `shapes` run reports, flattened into [`GateExtra::Shapes`]'s JSON.
485#[derive(Debug, Clone, Default, Serialize)]
486pub struct ShapesCounters {
487    /// ONT-4b2: bound Rust symbols the `syn` walk resolved / could not resolve.
488    pub symbols_resolved: usize,
489    pub symbols_unresolved: usize,
490    /// ONT-4b2: Lean theorems extracted, and contract `lean_theorem:` references naming none of them.
491    pub lean_statements: usize,
492    pub lean_refs_unresolved: usize,
493    /// ONT-4d (R-19): applications of a shape to instances of a strict sub-concept of its target, summed over shapes. Such a
494    /// node may ALSO be typed the target directly (`pv_contract` asserts `ont:Contract` on every contract), so
495    /// this counts the hierarchy being applied, not reach that exists only through it. The fixture
496    /// `subsumption-inherit` is where inheritance is the ONLY path.
497    pub inherited_shapes_applied: usize,
498    /// `<shape> <- <sub-concept>=<n>` for each shape inherited down the hierarchy, sorted.
499    pub inherited_by_shape: Vec<String>,
500}
501
502/// ONT-4c: one measured claim set, sorted.
503#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
504pub struct MeasuredSet {
505    pub verified_commands: Vec<String>,
506}
507
508/// ONT-4c: `measured_sets` is `checked` only when F-34 ran against a comparand (the CLI resolves it from git);
509/// outside a work tree it is `not-checked`, which a probe must read as RED, never as a pass.
510#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
511pub struct Ratchets {
512    pub measured_sets: String,
513}
514
515impl Default for Ratchets {
516    fn default() -> Self {
517        Self {
518            measured_sets: "not-checked".into(),
519        }
520    }
521}
522
523/// Overall lint report.
524#[derive(Debug, Clone, Serialize)]
525pub struct LintReport {
526    pub passed: bool,
527    pub gates: Vec<GateResult>,
528    pub total_duration_ms: u64,
529    #[serde(skip_serializing_if = "Vec::is_empty")]
530    pub findings: Vec<LintFinding>,
531    #[serde(skip)]
532    pub cache_stats: cache::CacheStats,
533    /// Per-contract processing times: `(contract_stem, duration_ms)`.
534    #[serde(default, skip_serializing_if = "Vec::is_empty")]
535    pub contract_timings: Vec<(String, u64)>,
536    /// ONT-001 §3.9: the meet over the armed gates — what the exit code reports. `passed` is the legacy
537    /// every-gate-passed-or-skipped flag and is kept unchanged for existing readers.
538    pub verdict: Verdict,
539    /// Each armed gate, in armed order, with the verdict it contributed (`Unknown(NotRun)` if it did not run).
540    pub armed_gates: Vec<ArmedGateVerdict>,
541    /// Gates that ran but are not armed: printed as `Unknown(NotArmed)` and excluded from the meet.
542    pub not_armed: Vec<String>,
543    /// The `armed_gates` monotone check, as the CLI measured it; `None` when nothing checked it.
544    #[serde(skip_serializing_if = "Option::is_none")]
545    pub armed_monotone: Option<String>,
546    /// ONT-4c1: the `armed_shapes` monotone check, as the CLI measured it.
547    #[serde(skip_serializing_if = "Option::is_none")]
548    pub armed_shapes_monotone: Option<String>,
549}
550
551/// One armed gate's contribution to [`LintReport::verdict`].
552#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
553pub struct ArmedGateVerdict {
554    pub name: String,
555    pub verdict: Verdict,
556}
557
558impl LintReport {
559    /// Recompute the meet over `armed`. Gates that ran but are not armed are listed in `not_armed`.
560    pub fn arm(&mut self, armed: &ArmedGates) {
561        let results: Vec<(String, Verdict)> = self
562            .gates
563            .iter()
564            .map(|g| (g.name.clone(), g.verdict))
565            .collect();
566        let meet = meet_armed(&results, armed);
567        self.verdict = meet.verdict;
568        self.armed_gates = meet
569            .armed
570            .into_iter()
571            .map(|(name, verdict)| ArmedGateVerdict { name, verdict })
572            .collect();
573        self.not_armed = meet.not_armed;
574    }
575}
576
577/// Configuration for `pv lint`.
578pub struct LintConfig<'a> {
579    pub contract_dir: &'a Path,
580    pub binding_path: Option<&'a Path>,
581    pub min_score: f64,
582    pub severity_filter: Option<RuleSeverity>,
583    pub severity_overrides: HashMap<String, RuleSeverity>,
584    pub suppressed_findings: Vec<String>,
585    pub suppressed_rules: Vec<String>,
586    pub suppressed_files: Vec<String>,
587    pub strict: bool,
588    pub no_cache: bool,
589    pub cache_stats: bool,
590    /// Optional crate directory for reverse coverage gate (Gate 7).
591    pub crate_dir: Option<&'a Path>,
592    /// Minimum enforcement level for Gate 6 (from `--min-level`).
593    pub min_level: Option<crate::schema::EnforcementLevel>,
594    /// Enable Gate 9 (strict test-binding, PV-VER-002). Issue #1510.
595    pub strict_test_binding: bool,
596    /// Run only gate 1 (validate, the precondition) and the strict test-binding gate; gates 2-22 do not
597    /// run and nothing is cached (aprender#4974). Every armed gate that did not run meets as `NotRun`,
598    /// so the report can never read as a full-lint pass. Requires `strict_test_binding`.
599    pub strict_test_binding_only: bool,
600}
601
602impl<'a> LintConfig<'a> {
603    /// Create a basic config (backward compatible).
604    pub fn new(contract_dir: &'a Path, binding_path: Option<&'a Path>, min_score: f64) -> Self {
605        Self {
606            contract_dir,
607            binding_path,
608            min_score,
609            severity_filter: None,
610            severity_overrides: HashMap::new(),
611            suppressed_findings: Vec::new(),
612            suppressed_rules: Vec::new(),
613            suppressed_files: Vec::new(),
614            strict: false,
615            no_cache: false,
616            cache_stats: false,
617            crate_dir: None,
618            min_level: None,
619            strict_test_binding: false,
620            strict_test_binding_only: false,
621        }
622    }
623}
624
625/// Run one gate and record it, or record it as skipped when gate 1 (validate) failed.
626///
627/// Every gate after validate repeats the same `if validation_passed { run } else
628/// { skipped_gate(name, "validation failed") }` shape; this is that shape, once.
629fn push_gate<F>(
630    gates: &mut Vec<GateResult>,
631    all_findings: &mut Vec<LintFinding>,
632    run: F,
633    name: &str,
634    validation_passed: bool,
635) where
636    F: FnOnce() -> (GateResult, Vec<LintFinding>),
637{
638    let (result, mut findings) = if validation_passed {
639        run()
640    } else {
641        (skipped_gate(name, "validation failed"), Vec::new())
642    };
643    gates.push(result);
644    all_findings.append(&mut findings);
645}
646
647/// Per-contract timing: measure how long each contract's findings take to process,
648/// sorted by duration descending.
649fn per_contract_timings(
650    contracts: &[(String, crate::schema::Contract)],
651    binding: Option<&crate::binding::BindingRegistry>,
652) -> Vec<(String, u64)> {
653    let mut contract_timings: Vec<(String, u64)> = Vec::with_capacity(contracts.len());
654    for (stem, contract) in contracts {
655        let ct_start = Instant::now();
656        // Validate
657        let _ = crate::schema::validate_contract(contract);
658        // Audit
659        let _ = crate::audit::audit_contract(contract);
660        // Score
661        let _ = crate::scoring::score_contract(contract, binding, stem);
662        let ct_ms = u64::try_from(ct_start.elapsed().as_micros() / 1000).unwrap_or(0);
663        contract_timings.push((format!("{stem}.yaml"), ct_ms));
664    }
665    // Sort by duration descending
666    contract_timings.sort_by_key(|b| std::cmp::Reverse(b.1));
667    contract_timings
668}
669
670/// Cache: store findings per-contract for future runs.
671fn store_findings_in_cache(
672    root: &std::path::Path,
673    config: &LintConfig,
674    contracts: &[(String, crate::schema::Contract)],
675    all_findings: &[LintFinding],
676    stats: &mut cache::CacheStats,
677) {
678    let rule_cfg = format!("{:?}{:?}", config.severity_overrides, config.strict);
679    for (stem, _) in contracts {
680        stats.total += 1;
681        let yaml_path = config.contract_dir.join(format!("{stem}.yaml"));
682        let yaml_content = std::fs::read_to_string(&yaml_path).unwrap_or_default();
683        let hash = cache::content_hash(&yaml_content, &rule_cfg);
684        if cache::cache_get(root, &hash).is_some() {
685            stats.hits += 1;
686        } else {
687            stats.misses += 1;
688            let contract_findings: Vec<_> = all_findings
689                .iter()
690                .filter(|f| f.contract_stem.as_deref() == Some(stem.as_str()))
691                .cloned()
692                .collect();
693            let _ = cache::cache_put(root, &hash, &contract_findings);
694        }
695    }
696}
697
698/// Gates 2-9: audit, score, verify, enforce, enforcement-level, reverse-coverage, duplicate-stems, composition.
699/// Each is skipped (not run) when `validation_passed` is false, per `push_gate`'s contract.
700fn run_gates_2_to_9(
701    config: &LintConfig,
702    contracts: &[(String, crate::schema::Contract)],
703    binding: Option<&crate::binding::BindingRegistry>,
704    validation_passed: bool,
705    gates: &mut Vec<GateResult>,
706    all_findings: &mut Vec<LintFinding>,
707) {
708    // Gate 2: audit (skip if validation failed)
709    push_gate(
710        gates,
711        all_findings,
712        || run_audit_gate(contracts),
713        "audit",
714        validation_passed,
715    );
716
717    // Gate 3: score (skip if validation failed)
718    push_gate(
719        gates,
720        all_findings,
721        || run_score_gate(contracts, binding, config.min_score),
722        "score",
723        validation_passed,
724    );
725
726    // Gate 4: verify (source code fulfillment)
727    push_gate(
728        gates,
729        all_findings,
730        || {
731            let project_root = config.contract_dir.parent().unwrap_or(config.contract_dir);
732            run_verify_gate(contracts, project_root)
733        },
734        "verify",
735        validation_passed,
736    );
737
738    // Gate 5: enforce (equations must have preconditions/postconditions)
739    push_gate(
740        gates,
741        all_findings,
742        || run_enforce_gate(contracts),
743        "enforce",
744        validation_passed,
745    );
746
747    // Gate 6: enforcement level (Section 17, Gap 1 + Gap 5 level lock)
748    push_gate(
749        gates,
750        all_findings,
751        || {
752            let min_level = config
753                .min_level
754                .unwrap_or(crate::schema::EnforcementLevel::Standard);
755            run_enforcement_level_gate(contracts, min_level)
756        },
757        "enforcement-level",
758        validation_passed,
759    );
760
761    // Gate 7: reverse coverage (optional — skip if no binding or crate dir)
762    push_gate(
763        gates,
764        all_findings,
765        || match (config.binding_path, config.crate_dir) {
766            (Some(bp), Some(cd)) => run_reverse_coverage_gate(bp, cd),
767            _ => (
768                skipped_gate("reverse-coverage", "no --binding or --crate-dir provided"),
769                Vec::new(),
770            ),
771        },
772        "reverse-coverage",
773        validation_passed,
774    );
775
776    // Gate 8: duplicate stems (PV-DUP-001). Must run BEFORE composition — it tells
777    // the composition gate which stems are unresolvable, which is the difference
778    // between a defined verdict and one decided by `read_dir` order.
779    let duplicates = duplicate_stems::scan_duplicate_stems(config.contract_dir);
780    let ambiguous = duplicate_stems::ambiguous_stems(&duplicates);
781    push_gate(
782        gates,
783        all_findings,
784        || {
785            let project_root = config.contract_dir.parent().unwrap_or(config.contract_dir);
786            let baseline = duplicate_stems::read_baseline(project_root);
787            duplicate_stems::run_duplicate_stem_gate(&duplicates, &baseline)
788        },
789        "duplicate-stems",
790        validation_passed,
791    );
792
793    // Gate 9: composition (assumes/guarantees chain verification)
794    push_gate(
795        gates,
796        all_findings,
797        || composition_gate::run_composition_gate(contracts, &ambiguous),
798        "composition",
799        validation_passed,
800    );
801}
802
803/// Gates 10-22: the ONT-* ontology gates. Same R-8 shape throughout — each is computed on every run and armed
804/// per repo, never skipped by `validation_passed` the way gates 2-9 are.
805fn run_ontology_gates_10_to_22(
806    contract_dir: &Path,
807    validation_passed: bool,
808    gates: &mut Vec<GateResult>,
809    all_findings: &mut Vec<LintFinding>,
810) {
811    // Gate 10: sigma (ONT-2b). R-8: a new gate is COMPUTED everywhere and armed per repo — so it runs here as
812    // well as under `--gate sigma`, or `armed_gates` could name a gate no run ever computes.
813    let (sigma_gate_result, mut sigma_findings) = sigma_result(contract_dir, validation_passed);
814    gates.push(sigma_gate_result);
815    all_findings.append(&mut sigma_findings);
816
817    // Gate 11: relations (ONT-4). Same R-8 shape as sigma: computed in every run, armed per repo.
818    let (relations_gate_result, mut relations_findings) =
819        relations_result(contract_dir, validation_passed);
820    gates.push(relations_gate_result);
821    all_findings.append(&mut relations_findings);
822
823    // Gate 12: shapes (ONT-4b). Same R-8 shape: computed in every run, armed per repo.
824    let (shapes_gate_result, mut shapes_findings) = shapes_result(contract_dir, validation_passed);
825    gates.push(shapes_gate_result);
826    all_findings.append(&mut shapes_findings);
827
828    // Gate 13: valid-under (ONT-7). Same R-8 shape: computed in every run, armed per repo.
829    let (valid_under_gate_result, mut valid_under_findings) =
830        valid_under_result(contract_dir, validation_passed);
831    gates.push(valid_under_gate_result);
832    all_findings.append(&mut valid_under_findings);
833
834    // Gates 14, 15, 16: theorem-pairing, depends-on-present (PVL-001 EV-11), proved-is-derived (EV-8a). Same R-8
835    // shape: computed in every run, armed per repo.
836    for (name, run) in RATCHET_GATES {
837        let (result, mut findings) = ratchet_result(contract_dir, validation_passed, name, run);
838        gates.push(result);
839        all_findings.append(&mut findings);
840    }
841
842    // Gate 17: challenge-fresh (PVL-001 EV-7a). Same R-8 shape: computed wherever a Lean theorem base exists,
843    // armed per repo (only through `make ont-ratchet`).
844    gates.push(challenge_result(contract_dir));
845
846    // Gate 18 (numbered by agreement: ONT-7 13, EV-11 14-16, EV-7a 17): ont-consistency (ONT-5). Same R-8 shape:
847    // computed in every run, armed per repo.
848    let (consistency_gate_result, mut consistency_findings) =
849        consistency_result(contract_dir, validation_passed);
850    gates.push(consistency_gate_result);
851    all_findings.append(&mut consistency_findings);
852
853    // Gate 19: refines (ONT-4e, R-20). Same R-8 shape: computed in every run, armed per repo.
854    let (refines_gate_result, mut refines_findings) =
855        refines_result(contract_dir, validation_passed);
856    gates.push(refines_gate_result);
857    all_findings.append(&mut refines_findings);
858
859    // Gate 20: bindings (ONT-3a). Same R-8 shape: computed in every run, armed per repo.
860    let (bindings_gate_result, mut bindings_findings) = ratchet_result(
861        contract_dir,
862        validation_passed,
863        bindings_gate::GATE,
864        bindings_gate::run_bindings_gate,
865    );
866    gates.push(bindings_gate_result);
867    all_findings.append(&mut bindings_findings);
868
869    // Gate 21: refinement (ONT-3b). Same R-8 shape.
870    let (refinement_gate_result, mut refinement_findings) = ratchet_result(
871        contract_dir,
872        validation_passed,
873        refinement_gate::GATE,
874        refinement_gate::run_refinement_gate,
875    );
876    gates.push(refinement_gate_result);
877    all_findings.append(&mut refinement_findings);
878
879    // Gate 22: evidence (ONT-8). Same R-8 shape: computed in every run, armed per repo.
880    let (evidence_gate_result, mut evidence_findings) =
881        evidence_result(contract_dir, validation_passed);
882    gates.push(evidence_gate_result);
883    all_findings.append(&mut evidence_findings);
884}
885
886/// Gate 9 (again, by original numbering): strict test-binding (Issue #1510), opt-in via `--strict-test-binding`.
887fn run_strict_test_binding_gate_if_enabled(
888    config: &LintConfig,
889    contracts: &[(String, crate::schema::Contract)],
890    validation_passed: bool,
891    gates: &mut Vec<GateResult>,
892    all_findings: &mut Vec<LintFinding>,
893) {
894    if !config.strict_test_binding {
895        return;
896    }
897    push_gate(
898        gates,
899        all_findings,
900        || {
901            let project_root = config.contract_dir.parent().unwrap_or(config.contract_dir);
902            strict_test_binding::run_strict_test_binding_gate(
903                contracts,
904                project_root,
905                config.strict,
906            )
907        },
908        "strict-test-binding",
909        validation_passed,
910    );
911}
912
913/// Post-gate passes: fold in the validate gate's own findings, time contracts, detect stale suppressions, mark
914/// new-vs-pre-existing findings, cache them, then apply suppressions/overrides/severity filter.
915#[allow(clippy::too_many_arguments)]
916fn finalize_findings(
917    config: &LintConfig,
918    contracts: &[(String, crate::schema::Contract)],
919    binding: Option<&crate::binding::BindingRegistry>,
920    validation_passed: bool,
921    cache_root: Option<&std::path::Path>,
922    stats: &mut cache::CacheStats,
923    all_findings: &mut Vec<LintFinding>,
924    mut validate_findings: Vec<LintFinding>,
925) -> Vec<(String, u64)> {
926    all_findings.append(&mut validate_findings);
927
928    // Per-contract timing: measure how long each contract's findings take to process
929    let contract_timings = if validation_passed {
930        per_contract_timings(contracts, binding)
931    } else {
932        Vec::new()
933    };
934
935    // Stale suppression detection (PV-SUP-001, Section 17 Gap 2)
936    let mut stale_findings = check_stale_suppressions(
937        all_findings,
938        &config.suppressed_rules,
939        &config.suppressed_findings,
940    );
941    all_findings.append(&mut stale_findings);
942
943    // Issue lifecycle: mark each finding as new or pre-existing
944    mark_new_findings(all_findings, config.contract_dir);
945
946    // Cache: store findings per-contract for future runs
947    if let Some(root) = cache_root {
948        store_findings_in_cache(root, config, contracts, all_findings, stats);
949    }
950
951    // Apply suppressions, severity overrides, strict mode, and severity filter
952    apply_suppressions(all_findings, config);
953    apply_severity_overrides(all_findings, config);
954    if let Some(min_sev) = config.severity_filter {
955        all_findings.retain(|f| f.severity >= min_sev);
956    }
957
958    contract_timings
959}
960
961/// Run all lint gates across a contract directory.
962pub fn run_lint(config: &LintConfig) -> LintReport {
963    let overall_start = Instant::now();
964    let mut gates = Vec::with_capacity(3);
965    let mut all_findings = Vec::new();
966    let mut stats = cache::CacheStats::default();
967
968    // A scoped run's findings are a subset; caching them would store a partial answer per contract.
969    let cache_root = if config.no_cache || config.strict_test_binding_only {
970        None
971    } else {
972        Some(cache::cache_dir(config.contract_dir))
973    };
974
975    let (contracts, parse_errors) = load_contracts(config.contract_dir);
976    let binding = load_binding(config.binding_path);
977
978    // Gate 1: validate
979    let (validate_result, validate_findings) = run_validate_gate(&contracts, &parse_errors);
980    let validation_passed = validate_result.passed;
981    gates.push(validate_result);
982
983    if !config.strict_test_binding_only {
984        run_gates_2_to_9(
985            config,
986            &contracts,
987            binding.as_ref(),
988            validation_passed,
989            &mut gates,
990            &mut all_findings,
991        );
992        run_ontology_gates_10_to_22(
993            config.contract_dir,
994            validation_passed,
995            &mut gates,
996            &mut all_findings,
997        );
998    }
999    run_strict_test_binding_gate_if_enabled(
1000        config,
1001        &contracts,
1002        validation_passed,
1003        &mut gates,
1004        &mut all_findings,
1005    );
1006
1007    let contract_timings = finalize_findings(
1008        config,
1009        &contracts,
1010        binding.as_ref(),
1011        validation_passed,
1012        cache_root.as_deref(),
1013        &mut stats,
1014        &mut all_findings,
1015        validate_findings,
1016    );
1017
1018    let passed = gates.iter().all(|g| g.passed || g.skipped);
1019
1020    let mut report = LintReport {
1021        passed,
1022        gates,
1023        total_duration_ms: u64::try_from(overall_start.elapsed().as_millis()).unwrap_or(u64::MAX),
1024        findings: all_findings,
1025        cache_stats: stats,
1026        contract_timings,
1027        verdict: Verdict::Unknown(crate::ontology::verdict::Reason::NotArmed),
1028        armed_gates: Vec::new(),
1029        not_armed: Vec::new(),
1030        armed_monotone: None,
1031        armed_shapes_monotone: None,
1032    };
1033    // The default set. `pv lint` re-arms from the corpus's `lint-baseline.json` (ONT-001 §3.9): a gate a flag
1034    // ran but the declaration does not arm is printed and excluded, like every other unarmed gate.
1035    report.arm(&ArmedGates::default_set());
1036    report
1037}
1038
1039/// ONT-2b: what `--gate <name>` answered. Only `Ran` and `Sigma(Ran)` are verdicts about the corpus.
1040pub enum NamedGateOutcome {
1041    /// `--gate` was given a name this build does not compute alone.
1042    UnknownGate,
1043    /// The `sigma` gate, which has two non-verdict answers of its own (no Σ, malformed Σ).
1044    Sigma(sigma_gate::SigmaOutcome),
1045    /// The `relations` gate (ONT-4), with three non-verdict answers (no Σ, malformed Σ, no typed relations).
1046    Relations(relations_gate::RelationsOutcome),
1047    /// The `shapes` gate (ONT-4b), with four non-verdict answers (unsupported shape, no shapes, no focus, control failed).
1048    Shapes(shapes_gate::ShapesOutcome),
1049    /// The `ont-consistency` gate (ONT-5): no Σ, malformed Σ, nothing checkable, a control that did not fire, a stale witness.
1050    Consistency(consistency_gate::ConsistencyOutcome),
1051    /// The `refines` gate (ONT-4e): no Σ, malformed Σ, a control that did not fire, a stale witness.
1052    Refines(refines_gate::RefinesOutcome),
1053    /// The `tbox` gate (ONT-2c): advisory classification. It has no Pass answer at all (R-7).
1054    Tbox(tbox_gate::TboxOutcome),
1055    /// The `evidence` gate (ONT-8), with three non-verdict answers (no Σ, malformed Σ, no evidence block).
1056    Evidence(evidence_gate::EvidenceOutcome),
1057    /// The `valid-under` gate (ONT-7), with three non-verdict answers (no Σ, malformed Σ, no kernel contract).
1058    ValidUnder(valid_under_gate::ValidUnderOutcome),
1059    /// A PVL-001 EV-11 ratchet (`theorem-pairing`, `depends-on-present`), whose one non-verdict answer is a decline.
1060    Ratchet(ratchet_gates::RatchetOutcome),
1061    /// A gate that ran and judged the corpus.
1062    Ran {
1063        result: Box<GateResult>,
1064        findings: Vec<LintFinding>,
1065    },
1066}
1067
1068/// Run ONE named gate and nothing else (ONT-001 §5 ONT-2b).
1069///
1070/// Only the gates that are meaningful ALONE are offered: `sigma` reads Σ and the corpus, `validate` parses the
1071/// corpus. The rest of `run_lint`'s gates are skipped when validation fails, so running one of them by itself would
1072/// report a verdict whose precondition nobody checked — `UnknownGate` is the honest answer, not a silent pass.
1073#[must_use]
1074pub fn run_named_gate(contract_dir: &Path, name: &str) -> NamedGateOutcome {
1075    run_named_gate_with(contract_dir, name, &shapes_gate::ShapesOptions::default())
1076}
1077
1078/// [`run_named_gate`] with the shapes gate's `--shape` / `--release-*` options (aprender#3715).
1079pub fn run_named_gate_with(
1080    contract_dir: &Path,
1081    name: &str,
1082    shapes_opts: &shapes_gate::ShapesOptions,
1083) -> NamedGateOutcome {
1084    match name {
1085        "evidence" => NamedGateOutcome::Evidence(evidence_gate::run_evidence_gate(contract_dir)),
1086        "relations" => {
1087            NamedGateOutcome::Relations(relations_gate::run_relations_gate(contract_dir))
1088        }
1089        "shapes" => {
1090            NamedGateOutcome::Shapes(shapes_gate::run_shapes_gate_with(contract_dir, shapes_opts))
1091        }
1092        "sigma" => NamedGateOutcome::Sigma(sigma_gate::run_sigma_gate(contract_dir)),
1093        consistency_gate::GATE => {
1094            NamedGateOutcome::Consistency(consistency_gate::run_consistency_gate(contract_dir))
1095        }
1096        refines_gate::GATE => {
1097            NamedGateOutcome::Refines(refines_gate::run_refines_gate(contract_dir))
1098        }
1099        bindings_gate::GATE => {
1100            NamedGateOutcome::Ratchet(bindings_gate::run_bindings_gate(contract_dir))
1101        }
1102        refinement_gate::GATE => {
1103            NamedGateOutcome::Ratchet(refinement_gate::run_refinement_gate(contract_dir))
1104        }
1105        "tbox" => NamedGateOutcome::Tbox(tbox_gate::run_tbox_gate(contract_dir)),
1106        "valid-under" => {
1107            NamedGateOutcome::ValidUnder(valid_under_gate::run_valid_under_gate(contract_dir))
1108        }
1109        "theorem-pairing" => {
1110            NamedGateOutcome::Ratchet(ratchet_gates::run_theorem_pairing_gate(contract_dir))
1111        }
1112        "depends-on-present" => {
1113            NamedGateOutcome::Ratchet(ratchet_gates::run_depends_on_present_gate(contract_dir))
1114        }
1115        references_gate::GATE => {
1116            NamedGateOutcome::Ratchet(references_gate::run_references_gate(contract_dir))
1117        }
1118        "proved-is-derived" => {
1119            NamedGateOutcome::Ratchet(ratchet_gates::run_proved_is_derived_gate(contract_dir))
1120        }
1121        "validate" => {
1122            let (contracts, parse_errors) = load_contracts(contract_dir);
1123            let (result, findings) = run_validate_gate(&contracts, &parse_errors);
1124            NamedGateOutcome::Ran {
1125                result: Box::new(result),
1126                findings,
1127            }
1128        }
1129        _ => NamedGateOutcome::UnknownGate,
1130    }
1131}
1132
1133/// The gate names `--gate` computes alone, for the refusal message.
1134pub const NAMED_GATES: [&str; 15] = [
1135    references_gate::GATE,
1136    bindings_gate::GATE,
1137    refinement_gate::GATE,
1138    "depends-on-present",
1139    "evidence",
1140    consistency_gate::GATE,
1141    "proved-is-derived",
1142    refines_gate::GATE,
1143    "relations",
1144    "shapes",
1145    "sigma",
1146    "tbox",
1147    "theorem-pairing",
1148    "valid-under",
1149    "validate",
1150];
1151
1152/// The EV-11 ratchet gates, by name, in the order the full run computes them.
1153type RatchetRun = fn(&Path) -> ratchet_gates::RatchetOutcome;
1154const RATCHET_GATES: [(&str, RatchetRun); 4] = [
1155    ("theorem-pairing", ratchet_gates::run_theorem_pairing_gate),
1156    (
1157        "depends-on-present",
1158        ratchet_gates::run_depends_on_present_gate,
1159    ),
1160    (
1161        "proved-is-derived",
1162        ratchet_gates::run_proved_is_derived_gate,
1163    ),
1164    (references_gate::GATE, references_gate::run_references_gate),
1165];
1166
1167/// An EV-11 ratchet as `run_lint` reports it. Its decline becomes a SKIPPED gate here, as sigma's non-verdict
1168/// answers do — under `--gate <name>` it is an exit of its own (2).
1169fn ratchet_result(
1170    contract_dir: &Path,
1171    validation_passed: bool,
1172    name: &str,
1173    run: RatchetRun,
1174) -> (GateResult, Vec<LintFinding>) {
1175    if !validation_passed {
1176        return (skipped_gate(name, "validation failed"), Vec::new());
1177    }
1178    match run(contract_dir) {
1179        ratchet_gates::RatchetOutcome::Ran { result, findings } => (*result, findings),
1180        ratchet_gates::RatchetOutcome::Declined(why) => (skipped_gate(name, &why), Vec::new()),
1181    }
1182}
1183
1184/// The `sigma` gate as `run_lint` reports it. Σ's two non-verdict answers become SKIPPED gates here — under
1185/// `--gate sigma` they are an exit of their own (decline / error), but inside a full run "skipped" is how the
1186/// lattice already says "not measured".
1187fn sigma_result(contract_dir: &Path, validation_passed: bool) -> (GateResult, Vec<LintFinding>) {
1188    if !validation_passed {
1189        return (skipped_gate("sigma", "validation failed"), Vec::new());
1190    }
1191    match sigma_gate::run_sigma_gate(contract_dir) {
1192        sigma_gate::SigmaOutcome::Ran { result, findings } => (*result, findings),
1193        sigma_gate::SigmaOutcome::NoSigma => (
1194            skipped_gate("sigma", "no contracts/ontology.yaml"),
1195            Vec::new(),
1196        ),
1197        sigma_gate::SigmaOutcome::Malformed(e) => (
1198            skipped_gate("sigma", &format!("Σ is malformed: {e}")),
1199            Vec::new(),
1200        ),
1201    }
1202}
1203
1204/// The `evidence` gate as `run_lint` reports it (ONT-8). Its three non-verdict answers become SKIPPED gates here, as
1205/// sigma's do — under `--gate evidence` they are exits of their own (decline / error).
1206fn evidence_result(contract_dir: &Path, validation_passed: bool) -> (GateResult, Vec<LintFinding>) {
1207    if !validation_passed {
1208        return (skipped_gate("evidence", "validation failed"), Vec::new());
1209    }
1210    match evidence_gate::run_evidence_gate(contract_dir) {
1211        evidence_gate::EvidenceOutcome::Ran { result, findings } => (*result, findings),
1212        evidence_gate::EvidenceOutcome::NoSigma => (
1213            skipped_gate("evidence", "no contracts/ontology.yaml"),
1214            Vec::new(),
1215        ),
1216        evidence_gate::EvidenceOutcome::Malformed(e) => (
1217            skipped_gate("evidence", &format!("Σ is malformed: {e}")),
1218            Vec::new(),
1219        ),
1220        evidence_gate::EvidenceOutcome::NoEvidence { contracts_checked } => (
1221            skipped_gate(
1222                "evidence",
1223                &format!(
1224                    "no evidence block in {contracts_checked} contracts — R-2: zero is a decline"
1225                ),
1226            ),
1227            Vec::new(),
1228        ),
1229    }
1230}
1231
1232/// The `valid-under` gate as `run_lint` reports it (ONT-7). Its three non-verdict answers become SKIPPED gates
1233/// here, as sigma's do — under `--gate valid-under` they are exits of their own (decline / error).
1234fn valid_under_result(
1235    contract_dir: &Path,
1236    validation_passed: bool,
1237) -> (GateResult, Vec<LintFinding>) {
1238    if !validation_passed {
1239        return (skipped_gate("valid-under", "validation failed"), Vec::new());
1240    }
1241    match valid_under_gate::run_valid_under_gate(contract_dir) {
1242        valid_under_gate::ValidUnderOutcome::Ran { result, findings } => (*result, findings),
1243        valid_under_gate::ValidUnderOutcome::NoSigma => (
1244            skipped_gate("valid-under", "no contracts/ontology.yaml"),
1245            Vec::new(),
1246        ),
1247        valid_under_gate::ValidUnderOutcome::Malformed(e) => (
1248            skipped_gate("valid-under", &format!("Σ is malformed: {e}")),
1249            Vec::new(),
1250        ),
1251        valid_under_gate::ValidUnderOutcome::NoKernels { contracts_checked } => (
1252            skipped_gate(
1253                "valid-under",
1254                &format!("no kernel-kind contract and no valid_under in {contracts_checked} contracts — R-2: zero is a decline"),
1255            ),
1256            Vec::new(),
1257        ),
1258    }
1259}
1260
1261/// The `relations` gate as `run_lint` reports it. Its three non-verdict answers become SKIPPED gates here, as
1262/// sigma's do — under `--gate relations` they are exits of their own (decline / error).
1263fn relations_result(
1264    contract_dir: &Path,
1265    validation_passed: bool,
1266) -> (GateResult, Vec<LintFinding>) {
1267    if !validation_passed {
1268        return (skipped_gate("relations", "validation failed"), Vec::new());
1269    }
1270    match relations_gate::run_relations_gate(contract_dir) {
1271        relations_gate::RelationsOutcome::Ran { result, findings } => (*result, findings),
1272        relations_gate::RelationsOutcome::NoSigma => (
1273            skipped_gate("relations", "no contracts/ontology.yaml"),
1274            Vec::new(),
1275        ),
1276        relations_gate::RelationsOutcome::Malformed(e) => (
1277            skipped_gate("relations", &format!("Σ is malformed: {e}")),
1278            Vec::new(),
1279        ),
1280        relations_gate::RelationsOutcome::NoRelations {
1281            contracts_checked,
1282            legacy_depends_on,
1283        } => (
1284            skipped_gate(
1285                "relations",
1286                &format!("no typed relations in {contracts_checked} contracts ({legacy_depends_on} legacy metadata.depends_on edges) — R-2: zero is a decline"),
1287            ),
1288            Vec::new(),
1289        ),
1290    }
1291}
1292
1293/// The `shapes` gate as `run_lint` reports it. Its four non-verdict answers become SKIPPED gates here (under
1294/// `--gate shapes` they are exits of their own); an `Unknown{Warn}` run is reported as the gate returned it.
1295fn shapes_result(contract_dir: &Path, validation_passed: bool) -> (GateResult, Vec<LintFinding>) {
1296    if !validation_passed {
1297        return (skipped_gate("shapes", "validation failed"), Vec::new());
1298    }
1299    match shapes_gate::run_shapes_gate(contract_dir) {
1300        shapes_gate::ShapesOutcome::Ran { result, findings } => (*result, findings),
1301        shapes_gate::ShapesOutcome::Unsupported(e) => (skipped_gate("shapes", &format!("{e}")), Vec::new()),
1302        shapes_gate::ShapesOutcome::ExtractFailed(e) => (skipped_gate("shapes", &format!("{e}")), Vec::new()),
1303        shapes_gate::ShapesOutcome::NoShapes { contracts_checked } => (
1304            skipped_gate("shapes", &format!("no `shape:` block in {contracts_checked} contracts — R-2: zero is a decline")),
1305            Vec::new(),
1306        ),
1307        shapes_gate::ShapesOutcome::NoFocus { shapes_n } => (
1308            skipped_gate("shapes", &format!("{shapes_n} shape(s), no focus node")),
1309            Vec::new(),
1310        ),
1311        shapes_gate::ShapesOutcome::WrongCorpus { shapes_n, expected, found, refused } => (
1312            skipped_gate("shapes", &format!("extract:parity-receipt matched {found} focus node(s) and evidence/parity/EXPECTED_RECEIPTS says {expected} ({shapes_n} shape(s)){} — an extractor that saw the wrong corpus reports the same \"no violations\" as one that saw all of it", if refused.is_empty() { String::new() } else { format!("; refused: {}", refused.join("; ")) })),
1313            Vec::new(),
1314        ),
1315        shapes_gate::ShapesOutcome::HarnessBroken { causes } => (
1316            skipped_gate("shapes", &format!("the CRUX harness measured itself, not apr: {}", causes.join("; "))),
1317            Vec::new(),
1318        ),
1319        shapes_gate::ShapesOutcome::NoReceipts { shapes_n, dir } => (
1320            skipped_gate("shapes", &format!("{shapes_n} shape(s) resolve receipts and the tree holds none under {dir}/ — R-2: unmeasured is a decline")),
1321            Vec::new(),
1322        ),
1323        shapes_gate::ShapesOutcome::EmptyDomain { shapes_n } => (
1324            skipped_gate("shapes", &format!("capability-cells: the required-cell domain D is empty ({shapes_n} shape(s)) — R-2: zero is a decline, never a pass")),
1325            Vec::new(),
1326        ),
1327        shapes_gate::ShapesOutcome::PositiveControlFailed { shapes_n, focus_nodes_n, which } => (
1328            skipped_gate("shapes", &format!("positive control {which} did not fire ({shapes_n} shape(s), {focus_nodes_n} focus node(s)) — the gate cannot reject")),
1329            Vec::new(),
1330        ),
1331        shapes_gate::ShapesOutcome::Differential { shapes_n, focus_nodes_n, passed, n, failed } => {
1332            let mut g = skipped_gate(
1333                "shapes",
1334                &format!(
1335                    "W3C SHACL-Core differential: {passed} of {n} vendored case(s) pass; failed: {} ({shapes_n} shape(s), {focus_nodes_n} focus node(s)) — the validator disagrees with the standard, so no corpus verdict",
1336                    failed.join(" | ")
1337                ),
1338            );
1339            g.verdict = Verdict::Unknown(crate::ontology::verdict::Reason::Differential);
1340            (g, Vec::new())
1341        }
1342    }
1343}
1344
1345/// The `ont-consistency` gate as `run_lint` reports it. Its declines keep their lattice reason here (a stale witness
1346/// is `Unknown{WitnessStale}`, not a bare skip), so the meet says what could not be checked.
1347fn consistency_result(
1348    contract_dir: &Path,
1349    validation_passed: bool,
1350) -> (GateResult, Vec<LintFinding>) {
1351    if !validation_passed {
1352        return (
1353            skipped_gate(consistency_gate::GATE, "validation failed"),
1354            Vec::new(),
1355        );
1356    }
1357    let outcome = consistency_gate::run_consistency_gate(contract_dir);
1358    if let consistency_gate::ConsistencyOutcome::Ran { result, findings } = outcome {
1359        return (*result, findings);
1360    }
1361    let mut g = skipped_gate(consistency_gate::GATE, &consistency_gate::why(&outcome));
1362    if let Some(reason) = consistency_gate::decline_reason(&outcome) {
1363        g.verdict = Verdict::Unknown(reason);
1364    }
1365    (g, Vec::new())
1366}
1367
1368/// The `refines` gate as `run_lint` reports it; declines keep their lattice reason, as `ont-consistency`'s do.
1369fn refines_result(contract_dir: &Path, validation_passed: bool) -> (GateResult, Vec<LintFinding>) {
1370    if !validation_passed {
1371        return (
1372            skipped_gate(refines_gate::GATE, "validation failed"),
1373            Vec::new(),
1374        );
1375    }
1376    let outcome = refines_gate::run_refines_gate(contract_dir);
1377    if let refines_gate::RefinesOutcome::Ran { result, findings } = outcome {
1378        return (*result, findings);
1379    }
1380    let mut g = skipped_gate(refines_gate::GATE, &refines_gate::why(&outcome));
1381    if let Some(reason) = refines_gate::decline_reason(&outcome) {
1382        g.verdict = Verdict::Unknown(reason);
1383    }
1384    (g, Vec::new())
1385}
1386
1387/// The `challenge-fresh` gate: `pv challenge check` as a gate. No Lean theorem base, a tree that does not load, or
1388/// zero challenges is SKIPPED (not measured), never green.
1389fn challenge_result(contract_dir: &Path) -> GateResult {
1390    const NAME: &str = "challenge-fresh";
1391    let start = Instant::now();
1392    let root = crate::ontology::extract::repo_root(contract_dir);
1393    let Some(lean) = crate::ontology::extract::lean::base_under(&root) else {
1394        return skipped_gate(NAME, "no Lean theorem base under the repo root");
1395    };
1396    let r = match crate::discharge::challenge::render(&lean, contract_dir) {
1397        Ok(r) => r,
1398        Err(e) => return skipped_gate(NAME, &format!("the Lean tree does not load: {e}")),
1399    };
1400    if r.files.is_empty() && r.unrestated.is_empty() {
1401        return skipped_gate(
1402            NAME,
1403            "zero challenges: no contract binds a theorem — R-2: zero is a decline",
1404        );
1405    }
1406    let stale = crate::discharge::challenge::diff(&lean, &r);
1407    let unrestated: Vec<String> = r
1408        .unrestated
1409        .iter()
1410        .map(|(c, fqn, why)| format!("{c}: {fqn}: {why}"))
1411        .collect();
1412    let passed = stale.is_empty() && unrestated.is_empty();
1413    GateResult {
1414        name: NAME.into(),
1415        passed,
1416        skipped: false,
1417        verdict: Verdict::from_gate(passed, false),
1418        duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
1419        // `GateDetail` is FROZEN at the 0.3.1 variants: the shape is borrowed, the payload rides in `GateExtra`.
1420        detail: GateDetail::Validate {
1421            contracts: r.files.len(),
1422            errors: stale.len() + unrestated.len(),
1423            warnings: 0,
1424            error_messages: stale.iter().chain(&unrestated).cloned().collect(),
1425        },
1426        extra: Some(GateExtra::ChallengeFresh {
1427            lean_dir: lean.display().to_string(),
1428            files: r.files.len(),
1429            stale,
1430            unrestated,
1431        }),
1432    }
1433}
1434
1435fn skipped_gate(name: &str, reason: &str) -> GateResult {
1436    GateResult {
1437        name: name.into(),
1438        passed: false,
1439        skipped: true,
1440        verdict: Verdict::from_gate(false, true),
1441        duration_ms: 0,
1442        detail: GateDetail::Skipped {
1443            reason: reason.into(),
1444        },
1445        extra: None,
1446    }
1447}
1448
1449fn apply_suppressions(findings: &mut [LintFinding], config: &LintConfig) {
1450    for f in findings.iter_mut() {
1451        if config.suppressed_rules.iter().any(|r| r == &f.rule_id) {
1452            f.suppressed = true;
1453            f.suppression_reason = Some("Suppressed by --suppress-rule".into());
1454        }
1455        if let Some(ref stem) = f.contract_stem {
1456            if config.suppressed_findings.iter().any(|s| s == stem) {
1457                f.suppressed = true;
1458                f.suppression_reason = Some("Suppressed by --suppress".into());
1459            }
1460        }
1461        if config.suppressed_files.iter().any(|p| f.file.contains(p)) {
1462            f.suppressed = true;
1463            f.suppression_reason = Some("Suppressed by --suppress-file".into());
1464        }
1465    }
1466}
1467
1468/// Resolve the `.pv/` state directory relative to the contract directory's parent.
1469fn pv_state_dir(contract_dir: &Path) -> std::path::PathBuf {
1470    contract_dir.parent().unwrap_or(contract_dir).join(".pv")
1471}
1472
1473/// Load previous fingerprints, compare with current findings, mark new ones,
1474/// and persist the current fingerprint set for the next run.
1475fn mark_new_findings(findings: &mut [LintFinding], contract_dir: &Path) {
1476    let state_dir = pv_state_dir(contract_dir);
1477    let previous_path = state_dir.join("lint-previous.json");
1478
1479    // Load previous fingerprints (empty set if file missing or unreadable)
1480    let previous: HashSet<String> = std::fs::read_to_string(&previous_path)
1481        .ok()
1482        .and_then(|s| serde_json::from_str(&s).ok())
1483        .unwrap_or_default();
1484
1485    // Compute current fingerprints and mark new findings
1486    let mut current = HashSet::new();
1487    for f in findings.iter_mut() {
1488        let fp = f.fingerprint();
1489        if !previous.contains(&fp) {
1490            f.is_new = true;
1491        }
1492        current.insert(fp);
1493    }
1494
1495    // Persist current fingerprints for the next run
1496    if let Err(e) = std::fs::create_dir_all(&state_dir) {
1497        eprintln!("pv lint: cannot create {}: {e}", state_dir.display());
1498        return;
1499    }
1500    if let Ok(json) = serde_json::to_string(&current) {
1501        let _ = std::fs::write(&previous_path, json);
1502    }
1503}
1504
1505fn apply_severity_overrides(findings: &mut [LintFinding], config: &LintConfig) {
1506    for f in findings.iter_mut() {
1507        if let Some(&sev) = config.severity_overrides.get(&f.rule_id) {
1508            f.severity = sev;
1509        }
1510    }
1511    if config.strict {
1512        for f in findings.iter_mut() {
1513            if f.severity == RuleSeverity::Warning {
1514                f.severity = RuleSeverity::Error;
1515            }
1516        }
1517    }
1518}
1519
1520#[cfg(test)]
1521#[path = "mod_tests.rs"]
1522mod tests;