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