Skip to main content

logicaffeine_proof/
verify.rs

1//! Unified theorem verification — the single door.
2//!
3//! Every public theorem entry point in the workspace funnels through
4//! [`prove_certify_check`], so they all share one trust guarantee:
5//!
6//! > A proof is `verified` **iff** the backward chainer produced a derivation,
7//! > the certifier turned it into a kernel term, **and** the kernel type-checked
8//! > that term.
9//!
10//! A derivation alone never counts as verified — `verified == true` is always
11//! backed by a [`Term`] that re-checks under [`infer_type`] in the returned
12//! [`Context`]. This core lives in the proof crate (not the compile crate) so
13//! both `logicaffeine_language` and `logicaffeine_compile` can reach it without
14//! a dependency cycle.
15
16use std::collections::{BTreeSet, HashMap, HashSet};
17
18use logicaffeine_kernel::{
19    double_check, infer_type, is_subtype, prelude::StandardLibrary, Context, DoubleCheck, Term,
20    Universe,
21};
22
23use crate::certifier::{certify, proof_expr_to_type, proof_expr_to_type_ctx, CertificationContext};
24use crate::symbols::{KernelNames, SymbolCollector};
25use crate::{BackwardChainer, DerivationTree, ProofExpr, ProofTerm};
26
27/// Outcome of running a goal through prove → certify → kernel type-check.
28///
29/// The invariant: `verified == true` **iff** `proof_term.is_some()` and that
30/// term type-checks in `kernel_ctx`. When verification fails, `derivation` may
31/// still be present (the chainer found *a* derivation) but it is never reported
32/// as verified — `verification_error` explains where the chain broke.
33pub struct VerifiedProof {
34    /// The derivation found by backward chaining, if any.
35    pub derivation: Option<DerivationTree>,
36    /// The certified kernel proof term, present only when `verified`.
37    pub proof_term: Option<Term>,
38    /// The kernel context the proof term was checked in (predicates,
39    /// constants, and premise hypotheses registered).
40    pub kernel_ctx: Context,
41    /// True iff a proof term was certified and kernel type-checked.
42    pub verified: bool,
43    /// Where the chain broke (search, certification, or type-check), if it did.
44    pub verification_error: Option<String>,
45}
46
47impl VerifiedProof {
48    /// The axioms this proof transitively rests on — see [`AxiomFootprint`].
49    ///
50    /// Read off the kernel TERM, never the derivation: the derivation is producer
51    /// data the kernel has not vouched for, while the term is exactly what
52    /// `infer_type` accepted. An unverified proof has no term, so it reports
53    /// nothing — there is no proof for anything to rest on.
54    ///
55    /// Transitive through definitions, which is the half no per-declaration
56    /// warning can reach: a term whose body is the bare name `taintedLemma` rests
57    /// on everything `taintedLemma` rests on, and mentions none of it.
58    pub fn axiom_footprint(&self) -> AxiomFootprint {
59        let Some(term) = self.proof_term.as_ref() else {
60            return AxiomFootprint::default();
61        };
62
63        let usage = logicaffeine_kernel::axiom_dependencies(&self.kernel_ctx, term);
64        let cited: BTreeSet<String> = usage.axioms.into_iter().chain(usage.unresolved).collect();
65
66        // The split: ask the trusted base, the standard library's own registration. A
67        // name the prelude declares AT THE SAME TYPE is trusted; anything else — absent,
68        // or present at a different type — was introduced by this run, and that is the
69        // list an admission lands in.
70        let trusted_axioms: HashMap<&str, &Term> =
71            StandardLibrary::context().iter_declarations().collect();
72        let mut footprint = AxiomFootprint::default();
73        for name in cited {
74            let here = self.kernel_ctx.get_global(&name);
75            match trusted_axioms.get(name.as_str()) {
76                Some(prelude_type) if Some(*prelude_type) == here => footprint.trusted.push(name),
77                _ => footprint.introduced.push(name),
78            }
79        }
80        footprint
81    }
82}
83
84/// Every `Global`/`Const` name occurring in `term`, in traversal order (duplicates
85/// included — the caller deduplicates). Exhaustive over [`Term`]: a variant added
86/// without an arm here would silently drop the axioms underneath it.
87fn collect_global_names(term: &Term, out: &mut Vec<String>) {
88    match term {
89        Term::Global(name) => out.push(name.clone()),
90        Term::Const { name, .. } => out.push(name.clone()),
91        Term::Sort(_) | Term::Var(_) | Term::Lit(_) | Term::Hole => {}
92        Term::Pi {
93            param_type,
94            body_type,
95            ..
96        } => {
97            collect_global_names(param_type, out);
98            collect_global_names(body_type, out);
99        }
100        Term::Lambda {
101            param_type, body, ..
102        } => {
103            collect_global_names(param_type, out);
104            collect_global_names(body, out);
105        }
106        Term::App(f, a) => {
107            collect_global_names(f, out);
108            collect_global_names(a, out);
109        }
110        Term::Match {
111            discriminant,
112            motive,
113            cases,
114        } => {
115            collect_global_names(discriminant, out);
116            collect_global_names(motive, out);
117            for case in cases {
118                collect_global_names(case, out);
119            }
120        }
121        Term::Fix { body, .. } => collect_global_names(body, out),
122        Term::MutualFix { defs, .. } => {
123            for (_, body) in defs {
124                collect_global_names(body, out);
125            }
126        }
127        Term::Let {
128            ty, value, body, ..
129        } => {
130            collect_global_names(ty, out);
131            collect_global_names(value, out);
132            collect_global_names(body, out);
133        }
134        Term::Annotated { term, .. } => collect_global_names(term, out),
135    }
136}
137
138/// What a certified proof term actually RESTS ON — the `#print axioms` analogue.
139///
140/// Two kernels give ZERO protection against an added axiom: `double_check` asks
141/// both the same question against the same context, so
142/// `double_check(ctx, sorryAx (2 = 3))` returns `Agreed`. The only thing that
143/// catches an admission is asking what the proof term CITES and comparing that
144/// against a freshly rebuilt trusted base — which is what this report does.
145///
146/// The split is the point. `trusted` is the part of the prelude the proof used,
147/// so a classical theorem is distinguishable from a constructive one by reading
148/// its certificate rather than its prose. `introduced` is everything else the
149/// term cites: this theorem's premise hypotheses and symbols — and anything
150/// smuggled into the context, which is the slot a `sorryAx` lands in.
151#[derive(Debug, Clone, PartialEq, Eq, Default)]
152pub struct AxiomFootprint {
153    /// Declarations the term cites that a freshly-registered [`StandardLibrary`]
154    /// also declares, with the same type: the trusted base this proof used.
155    /// Sorted, deduplicated.
156    pub trusted: Vec<String>,
157    /// Declarations the term cites that a rebuilt prelude does NOT declare (or
158    /// declares at a different type). Sorted, deduplicated.
159    pub introduced: Vec<String>,
160}
161
162/// A user-introduced predicate definition (Rung 0a), expressed in the proof
163/// layer's own vocabulary so `logicaffeine_proof` keeps its
164/// no-language-dependency invariant. Read as `name(params) :↔ definiens`.
165///
166/// Registered as a δ-unfoldable kernel definition (not an inlined expansion), so
167/// the definiendum stays a first-class, citable node: `bachelor(x)` remains
168/// `bachelor(x)` in the proposition, defeq to its meaning by δ-reduction.
169#[derive(Debug, Clone)]
170pub struct Definition {
171    /// The definiendum predicate name (e.g. `"bachelor"`).
172    pub name: String,
173    /// The parameter names the definiendum binds (e.g. `["x"]`).
174    pub params: Vec<String>,
175    /// The definiens — the body the definiendum abbreviates.
176    pub definiens: ProofExpr,
177}
178
179/// Prove `goal` from `premises`, certify the derivation, and kernel-check it.
180///
181/// This is the canonical pipeline. Symbols are extracted from the premises and
182/// goal and registered in a fresh kernel context (predicates as `Entity → Prop`,
183/// constants as `Entity`); each premise is registered as a hypothesis using the
184/// **same** conversion the certifier uses for hypothesis lookup, so a registered
185/// premise is guaranteed to match.
186pub fn prove_certify_check(premises: &[ProofExpr], goal: &ProofExpr) -> VerifiedProof {
187    prove_certify_check_bounded(premises, goal, 100)
188}
189
190/// One theorem in a dependency-ordered library: proved from its own `premises` plus
191/// the conclusions of the theorems it `cites`. This is the unit the multi-theorem
192/// driver discharges in citation order (the Euclid-graph engine).
193#[derive(Debug, Clone, PartialEq)]
194pub struct LibraryTheorem {
195    pub name: String,
196    pub premises: Vec<ProofExpr>,
197    pub goal: ProofExpr,
198    /// Names of earlier theorems whose conclusions this proof relies on.
199    pub cites: Vec<String>,
200}
201
202/// The outcome of proving one theorem in a library.
203pub struct LibraryResult {
204    pub name: String,
205    pub verified: bool,
206    pub verification_error: Option<String>,
207}
208
209/// Order theorems so every citation precedes its citer. A theorem is ready once all
210/// the theorems it cites (by name; unknown names are treated as external givens) are
211/// already ordered. Any theorems left in a citation cycle are appended last (they
212/// will simply fail to find their cyclic lemma). Stable: independent theorems keep
213/// their input order.
214pub(crate) fn citation_order(theorems: &[LibraryTheorem]) -> Vec<usize> {
215    use std::collections::HashSet;
216    let known: HashSet<&str> = theorems.iter().map(|t| t.name.as_str()).collect();
217    let mut placed: HashSet<usize> = HashSet::new();
218    let mut placed_names: HashSet<&str> = HashSet::new();
219    let mut order = Vec::with_capacity(theorems.len());
220    loop {
221        let mut progressed = false;
222        for (i, t) in theorems.iter().enumerate() {
223            if placed.contains(&i) {
224                continue;
225            }
226            let ready = t
227                .cites
228                .iter()
229                .all(|c| !known.contains(c.as_str()) || placed_names.contains(c.as_str()));
230            if ready {
231                order.push(i);
232                placed.insert(i);
233                placed_names.insert(t.name.as_str());
234                progressed = true;
235            }
236        }
237        if !progressed {
238            break;
239        }
240    }
241    for i in 0..theorems.len() {
242        if !placed.contains(&i) {
243            order.push(i);
244        }
245    }
246    order
247}
248
249/// Discharge a library of theorems in citation order. Each theorem is proved from
250/// its own premises plus the conclusions of the (already-proved) theorems it cites,
251/// so a citation graph is walked exactly like the scraped Euclid dependency graph.
252/// Results are returned in the INPUT order. A citation of an unproved/failed theorem
253/// simply isn't available as a premise (so the dependent proof fails too).
254pub fn prove_library(theorems: &[LibraryTheorem]) -> Vec<LibraryResult> {
255    prove_library_with_axioms(&[], theorems)
256}
257
258/// Like [`prove_library`] but with a shared `axioms` base in scope for every
259/// theorem — a named theory (e.g. the Tarski geometry axioms) on which the whole
260/// dependency graph is discharged.
261pub fn prove_library_with_axioms(
262    axioms: &[ProofExpr],
263    theorems: &[LibraryTheorem],
264) -> Vec<LibraryResult> {
265    use std::collections::HashMap;
266    let mut proved: HashMap<&str, &ProofExpr> = HashMap::new();
267    let mut by_name: HashMap<&str, LibraryResult> = HashMap::new();
268
269    for &i in &citation_order(theorems) {
270        let t = &theorems[i];
271        let mut premises = axioms.to_vec();
272        premises.extend(t.premises.iter().cloned());
273        for cite in &t.cites {
274            if let Some(goal) = proved.get(cite.as_str()) {
275                premises.push((*goal).clone());
276            }
277        }
278        let vp = prove_certify_check(&premises, &t.goal);
279        if vp.verified {
280            proved.insert(t.name.as_str(), &t.goal);
281        }
282        by_name.insert(
283            t.name.as_str(),
284            LibraryResult {
285                name: t.name.clone(),
286                verified: vp.verified,
287                verification_error: vp.verification_error,
288            },
289        );
290    }
291
292    theorems
293        .iter()
294        .map(|t| {
295            by_name
296                .remove(t.name.as_str())
297                .expect("every theorem produces a result")
298        })
299        .collect()
300}
301
302/// Like [`prove_certify_check`] but with user [`Definition`]s in scope (Rung 0a).
303pub fn prove_certify_check_with_defs(
304    premises: &[ProofExpr],
305    goal: &ProofExpr,
306    definitions: &[Definition],
307) -> VerifiedProof {
308    prove_certify_check_bounded_with_defs(premises, goal, definitions, 100)
309}
310
311/// Like [`prove_certify_check`] but caps the backward-chainer search depth, so a
312/// goal the kernel cannot reach fails FAST instead of exhausting the default depth.
313/// Keeps "prove-with-ours-first" cheap when answering a grid cell by cell: a
314/// shallow kernel attempt certifies what it can, then falls through to the oracle.
315pub fn prove_certify_check_bounded(
316    premises: &[ProofExpr],
317    goal: &ProofExpr,
318    max_depth: usize,
319) -> VerifiedProof {
320    prove_certify_check_bounded_with_defs(premises, goal, &[], max_depth)
321}
322
323/// The depth-bounded pipeline with user definitions (Rung 0a). Definitions are
324/// validated (recursion + lowering) up front, registered as δ-unfoldable kernel
325/// definitions in the context, then the goal is proved and kernel-checked. The
326/// engine still treats the definiendum opaquely during *search* (Stride 3 adds
327/// expand-for-search); δ reconciles the certified term with the folded goal type
328/// at the `finish_check` root.
329pub fn prove_certify_check_bounded_with_defs(
330    premises: &[ProofExpr],
331    goal: &ProofExpr,
332    definitions: &[Definition],
333    max_depth: usize,
334) -> VerifiedProof {
335    // The entire search + certify + kernel-check pipeline runs on ONE large-stack
336    // thread, so a legitimately deep proof never overflows the native stack and the
337    // common (shallow) case pays a single thread spawn.
338    on_big_stack(|| {
339        prove_certify_check_bounded_with_defs_inner(premises, goal, definitions, max_depth)
340    })
341}
342
343fn prove_certify_check_bounded_with_defs_inner(
344    premises: &[ProofExpr],
345    goal: &ProofExpr,
346    definitions: &[Definition],
347    max_depth: usize,
348) -> VerifiedProof {
349    let abstracted = abstract_definitions(definitions);
350    let definitions = &abstracted[..];
351    if let Err(e) = validate_definitions(definitions) {
352        return definition_error(e);
353    }
354
355    // Expand-for-search: the backward chainer treats a definiendum opaquely, so
356    // δ-expand defined predicates in the premises and goal before search — the
357    // engine then proves over ordinary predicates. The goal *type* stays FOLDED
358    // (abstracted from the ORIGINAL goal), so the certified proposition is still
359    // `glorp(A)`, reconciled to its unfolding by δ at the `finish_check` root.
360    //
361    // FAST PATH: with no definitions, the originals pass through untouched — no
362    // expansion walk, no clone — so ordinary theorems pay nothing for Rung 0a.
363    let expanded: Option<(Vec<ProofExpr>, ProofExpr)> = if definitions.is_empty() {
364        None
365    } else {
366        let defmap: HashMap<&str, &Definition> =
367            definitions.iter().map(|d| (d.name.as_str(), d)).collect();
368        let ep = premises
369            .iter()
370            .map(|p| expand_defs_in_expr(p, &defmap, 0))
371            .collect();
372        let eg = expand_defs_in_expr(goal, &defmap, 0);
373        Some((ep, eg))
374    };
375    let (search_premises, search_goal): (&[ProofExpr], &ProofExpr) = match &expanded {
376        Some((ep, eg)) => (ep, eg),
377        None => (premises, goal),
378    };
379
380    // Build the context and hypotheses from the (expanded) search premises so the
381    // certifier's PremiseMatch leaves resolve.
382    let (kernel_ctx, flat_premises, prepared_goal, names) =
383        prepare_ctx_with_defs(search_premises, search_goal, definitions);
384    // Folded goal type: when nothing was expanded, `prepared_goal` is already the
385    // folded form; otherwise re-abstract the ORIGINAL goal (the definiendum stays
386    // a citable node).
387    let abstracted_goal = if expanded.is_none() {
388        prepared_goal
389    } else {
390        BackwardChainer::new().abstract_all_events(goal)
391    };
392
393    // === Prove ===
394    let mut engine = BackwardChainer::new();
395    engine.set_max_depth(max_depth);
396    // The premises of a THEOREM are the kernel hypotheses registered just above, whose types
397    // mention this statement's free variables as context LOCALS. An instance of one is a
398    // proposition no context carries, so a search that used it would hand `finish_check` a
399    // tree the kernel must refuse. Read them as stated — see `PremiseVariables`.
400    engine.set_premise_variables(crate::PremiseVariables::Local);
401    for premise in &flat_premises {
402        engine.add_axiom(premise.clone());
403    }
404    // The engine searches over event-ABSTRACTED premises, so the goal must be
405    // abstracted to the same form (`Alice admires Bob` ⇒ `admire(Alice, Bob)`).
406    let search_goal = engine.abstract_all_events(search_goal);
407    let derivation = match engine.prove(search_goal) {
408        Ok(d) => d,
409        Err(e) => {
410            return VerifiedProof {
411                derivation: None,
412                proof_term: None,
413                kernel_ctx,
414                verified: false,
415                verification_error: Some(format!("Proof search failed: {}", e)),
416            };
417        }
418    };
419
420    finish_check(kernel_ctx, &names, &abstracted_goal, derivation)
421}
422
423/// Certify and kernel-check a derivation built EXTERNALLY (e.g. by the fast grid
424/// solver) against `premises ⊢ goal`, WITHOUT running the backward chainer. The
425/// trust guarantee is identical to [`prove_certify_check`]: `verified` is true only
426/// when the certifier produced a kernel term whose inferred type IS the goal type.
427/// So an external solver sits OUTSIDE the trusted base — it hands us a
428/// `DerivationTree`, the kernel re-checks it, and a wrong tree yields
429/// `verified == false`, never a false claim.
430pub fn check_derivation(
431    premises: &[ProofExpr],
432    goal: &ProofExpr,
433    derivation: DerivationTree,
434) -> VerifiedProof {
435    check_derivation_with_defs(premises, goal, &[], derivation)
436}
437
438/// Like [`check_derivation`] but with user [`Definition`]s in scope (Rung 0a), so
439/// an externally-built derivation of a definiens can certify against a goal
440/// stated with the definiendum — δ reconciles them at the root.
441pub fn check_derivation_with_defs(
442    premises: &[ProofExpr],
443    goal: &ProofExpr,
444    definitions: &[Definition],
445    derivation: DerivationTree,
446) -> VerifiedProof {
447    on_big_stack(|| check_derivation_with_defs_inner(premises, goal, definitions, derivation))
448}
449
450/// A kernel context prepared ONCE from a scope, against which many candidate derivations can
451/// then be checked — the reusable half of [`check_derivation`].
452///
453/// `check_derivation` rebuilds the standard library, the premise hypotheses and every
454/// referenced symbol on every call. That is right for a one-shot trust door and wrong for a
455/// SEARCH: [`crate::tactic::ProofState::by_rule`] proposes one node per candidate premise
456/// tuple and must ask the kernel about each of them. The scope does not change between those
457/// questions, so it is built once and the per-question cost is the certification itself.
458///
459/// This is the same check `check_derivation` performs — certify, infer, compare to the goal —
460/// so a tactic that consults it before reporting success cannot hand `qed` a tree the kernel
461/// will refuse.
462pub struct ScopedChecker {
463    ctx: Context,
464    goal: ProofExpr,
465    names: KernelNames,
466}
467
468impl ScopedChecker {
469    /// Prepare the context for a goal and the facts in scope.
470    pub fn new(premises: &[ProofExpr], goal: &ProofExpr) -> Self {
471        let (ctx, _flat, abstracted_goal, names) = prepare_ctx_with_defs(premises, goal, &[]);
472        Self {
473            ctx,
474            goal: abstracted_goal,
475            names,
476        }
477    }
478
479    /// Does this derivation certify as a proof of the scope's goal?
480    pub fn certifies(&self, derivation: DerivationTree) -> bool {
481        on_big_stack(|| {
482            finish_check(self.ctx.clone(), &self.names, &self.goal, derivation).verified
483        })
484    }
485}
486
487fn check_derivation_with_defs_inner(
488    premises: &[ProofExpr],
489    goal: &ProofExpr,
490    definitions: &[Definition],
491    derivation: DerivationTree,
492) -> VerifiedProof {
493    let abstracted = abstract_definitions(definitions);
494    let definitions = &abstracted[..];
495    if let Err(e) = validate_definitions(definitions) {
496        return definition_error(e);
497    }
498    let (kernel_ctx, _flat_premises, abstracted_goal, names) =
499        prepare_ctx_with_defs(premises, goal, definitions);
500    finish_check(kernel_ctx, &names, &abstracted_goal, derivation)
501}
502
503/// Build the kernel context shared by [`prove_certify_check_bounded`] and
504/// [`check_derivation`]: register the standard library, any user [`Definition`]s
505/// (Rung 0a), the event-ABSTRACTED, conjunction-SPLIT premises and what their
506/// definite descriptions presuppose as hypotheses `h1, h2, …`, and every
507/// predicate/constant referenced, each predicate under its [`KernelNames`] name.
508/// Returns the context, the flattened premises (presuppositions last), the
509/// abstracted goal, and the kernel names the goal and derivation are read with.
510fn prepare_ctx_with_defs(
511    premises: &[ProofExpr],
512    goal: &ProofExpr,
513    definitions: &[Definition],
514) -> (Context, Vec<ProofExpr>, ProofExpr, KernelNames) {
515    let mut kernel_ctx = StandardLibrary::context().clone();
516
517    // The search, the hypotheses, and the goal type must all live in ONE
518    // language: the engine's event-ABSTRACTED form (∃e(Lie(e) ∧ Agent(e, m))
519    // ↦ lie(m)). Hypotheses registered in the raw event form could never be
520    // found by the certifier, because derivation leaves cite abstracted
521    // conclusions. Premises are also split at top-level conjunctions (the
522    // standard sequent move: Γ, A ∧ B ⊢ φ iff Γ, A, B ⊢ φ) so a projected
523    // presupposition conjunct is an exactly-matchable hypothesis.
524    fn split_conjuncts(expr: &ProofExpr, out: &mut Vec<ProofExpr>) {
525        if let ProofExpr::And(l, r) = expr {
526            split_conjuncts(l, out);
527            split_conjuncts(r, out);
528        } else {
529            out.push(expr.clone());
530        }
531    }
532    let engine_for_abstraction = BackwardChainer::new();
533    let mut flat_premises = Vec::new();
534    for premise in premises {
535        let abstracted = engine_for_abstraction.abstract_all_events(premise);
536        // Biconditional elimination: rewrite `P ↔ Q` premises into `(P→Q) ∧ (Q→P)`
537        // (the kernel has no `Iff` type), so either direction is usable by the
538        // existing implication + modus-ponens machinery after conjunction split.
539        split_conjuncts(&expand_iff(&abstracted), &mut flat_premises);
540    }
541    let abstracted_goal = engine_for_abstraction.abstract_all_events(goal);
542
543    // Register predicates and constants referenced by premises and goal.
544    let mut collector = SymbolCollector::new();
545    for premise in &flat_premises {
546        collector.collect(premise);
547    }
548    collector.collect(&abstracted_goal);
549    // What the problem's definite descriptions presuppose is a premise the engine searches with, so
550    // it is a hypothesis the certifier can cite. Its symbols are the description's own, collected.
551    let presupposed = collector.presuppositions(&flat_premises);
552    flat_premises.extend(presupposed);
553    // Definiens bodies reference atomic predicates (and constants) that must be
554    // registered opaquely too, BEFORE the definitions below, so each definition
555    // body type-checks the moment it is registered. A definiendum is never
556    // registered opaquely: it is collected from an unexpanded goal or premise
557    // exactly like an atom, but it is the δ-unfoldable definition registered
558    // below, and an opaque declaration of the same name would displace it. It is
559    // noted as a predicate even where the δ-expanded premises no longer apply it,
560    // so the kernel names it like any other.
561    for def in definitions {
562        collector.collect(&def.definiens);
563        collector.collect_definiendum(&def.name, def.params.len());
564    }
565    collector.settle_sorts();
566    let names = collector.kernel_names(|name| kernel_ctx.get_global(name).is_some());
567    let definienda: HashSet<&str> = definitions.iter().map(|d| d.name.as_str()).collect();
568    // Inductive-domain predicates first (the induction motive needs `P : Ind → Prop`,
569    // e.g. `Nat → Prop` or `List → Prop`); the generic `Entity` registration below is
570    // idempotent and skips them.
571    for (name, ind) in collector.inductive_predicates() {
572        if definienda.contains(name.as_str()) {
573            continue;
574        }
575        let name = names.predicate(name);
576        if kernel_ctx.get_global(name).is_none() {
577            kernel_ctx.add_declaration(
578                name,
579                Term::Pi {
580                    param: "_".to_string(),
581                    param_type: Box::new(Term::Global(ind.to_string())),
582                    body_type: Box::new(Term::Sort(Universe::Prop)),
583                },
584            );
585        }
586    }
587    for (name, arity) in collector.predicates() {
588        if definienda.contains(name.as_str()) {
589            continue;
590        }
591        register_predicate(&mut kernel_ctx, names.predicate(name), arity);
592    }
593    let int_valued: HashSet<String> = collector
594        .functions()
595        .filter(|(n, _)| collector.is_int_valued(n))
596        .map(|(n, _)| n.clone())
597        .collect();
598    for (name, arity) in collector.functions() {
599        register_function(
600            &mut kernel_ctx,
601            name,
602            arity,
603            int_valued.contains(name),
604            &collector.int_domain(name),
605        );
606    }
607    // Temporal modalities `Op : Prop → Prop` (`Past`, `Future`, …), so a tensed
608    // proposition `Past(P)` type-checks as a distinct proposition from `P`.
609    for name in collector.modalities() {
610        register_modality(&mut kernel_ctx, name);
611    }
612    // Atoms in arithmetic/comparison positions are `Int`, declared before the
613    // generic `Entity` constants so `register_constant` skips them.
614    for name in collector.int_atoms() {
615        if kernel_ctx.get_global(name).is_none() {
616            kernel_ctx.add_declaration(name, Term::Global("Int".to_string()));
617        }
618    }
619    // FREE proof-variables are kernel LOCALS (see `free_variables`), registered before the
620    // hypothesis types below so a premise mentioning one type-checks.
621    for (name, domain) in collector.free_variables() {
622        if kernel_ctx.get(name).is_none() {
623            kernel_ctx.add(name, Term::Global(domain.to_string()));
624        }
625    }
626    // Definition parameters are λ-bound in the registered body, not constants;
627    // skip them so the definiens does not leak a spurious `p : Entity` global.
628    let param_names: HashSet<&str> = definitions
629        .iter()
630        .flat_map(|d| d.params.iter().map(String::as_str))
631        .collect();
632    for name in collector.constants() {
633        if param_names.contains(name.as_str()) {
634            continue;
635        }
636        register_constant(&mut kernel_ctx, name);
637    }
638
639    // Rung 0a: register user definitions as δ-unfoldable kernel definitions
640    // (with a body) rather than opaque axioms — after every atom a definiens
641    // mentions is declared, so the kernel checks each body here and now instead
642    // of holding it as a pending obligation. `validate_definitions` already
643    // rejected recursive / unlowerable definitions, so registration cannot loop.
644    for def in definitions {
645        let kernel_def = Definition {
646            name: names.predicate(&def.name).to_string(),
647            params: def.params.clone(),
648            definiens: names.expr(&def.definiens).into_owned(),
649        };
650        register_definition(&mut kernel_ctx, &kernel_def);
651    }
652
653    for (i, premise) in flat_premises.iter().enumerate() {
654        if let Ok(hyp_type) = proof_expr_to_type_ctx(&names.expr(premise), &kernel_ctx) {
655            let hyp_name = format!("h{}", i + 1);
656            kernel_ctx.add_declaration(&hyp_name, hyp_type);
657        }
658    }
659
660    // Also register each original CONJUNCTIVE premise as a WHOLE hypothesis, in
661    // addition to its split conjuncts. A derivation that references the conjunction
662    // itself — e.g. a tactic `cases`/`ConjunctionElim` projecting `A` out of `A ∧ B`
663    // — then resolves, while the search keeps using the flat conjuncts it prefers.
664    for (i, premise) in premises.iter().enumerate() {
665        let whole = expand_iff(&engine_for_abstraction.abstract_all_events(premise));
666        if matches!(whole, ProofExpr::And(_, _)) {
667            if let Ok(hyp_type) = proof_expr_to_type(&names.expr(&whole)) {
668                kernel_ctx.add_declaration(&format!("hw{}", i + 1), hyp_type);
669            }
670        }
671    }
672
673    (kernel_ctx, flat_premises, abstracted_goal, names)
674}
675
676/// Certify `derivation` and require its inferred kernel type to be the goal type —
677/// the trust core shared by the prove and check entries.
678/// Run `f` on a thread with a large stack. Proof search AND certification both
679/// recurse to a depth proportional to the proof: a long chain re-derived from the
680/// axioms is legitimately deep, so the default ~8 MB native stack is not enough.
681/// The `max_depth` bound still terminates search and the loop detector still prunes
682/// regress — this only removes the *native*-stack ceiling so a deep, finite proof
683/// completes instead of aborting (the standard recursive-descent remedy).
684pub(crate) fn on_big_stack<T: Send>(f: impl FnOnce() -> T + Send) -> T {
685    // wasm has no threads, so `spawn_scoped` would return `Unsupported` and abort every in-browser
686    // proof. Run inline there — the `max_depth` bound and loop detector still terminate search; only
687    // the *native* ~8 MB stack ceiling needs the worker thread, and wasm sizes its stack at build
688    // time instead. The browser links this crate, so this path must never spawn.
689    #[cfg(target_arch = "wasm32")]
690    {
691        f()
692    }
693    #[cfg(not(target_arch = "wasm32"))]
694    {
695        std::thread::scope(|s| {
696            std::thread::Builder::new()
697                .stack_size(32 * 1024 * 1024)
698                .spawn_scoped(s, f)
699                .expect("spawn proof thread")
700                .join()
701                .expect("proof thread panicked")
702        })
703    }
704}
705
706fn finish_check(
707    kernel_ctx: Context,
708    names: &KernelNames,
709    abstracted_goal: &ProofExpr,
710    derivation: DerivationTree,
711) -> VerifiedProof {
712    let trace = std::env::var("LOGOS_TRACE").is_ok();
713    // === Certify ===
714    let t_cert = trace.then(std::time::Instant::now);
715    let proof_term = {
716        let cert_ctx = CertificationContext::new(&kernel_ctx);
717        match certify(&names.tree(&derivation), &cert_ctx) {
718            Ok(t) => t,
719            Err(e) => {
720                return VerifiedProof {
721                    derivation: Some(derivation),
722                    proof_term: None,
723                    kernel_ctx,
724                    verified: false,
725                    verification_error: Some(format!("Certification failed: {}", e)),
726                };
727            }
728        }
729    };
730    if let Some(t_cert) = t_cert {
731        eprintln!(
732            "[cert] certify(build) {:.2?} → {} kernel-term nodes",
733            t_cert.elapsed(),
734            count_term_nodes(&proof_term)
735        );
736    }
737
738    // === Kernel type-check ===
739    // The term must not merely be well-typed — its type must be the goal.
740    // Otherwise a certifier that produced a well-formed proof of the *wrong*
741    // proposition would be wrongly accepted. We compute the goal's kernel type
742    // and require the inferred type to match it (up to definitional equality).
743    let t_infer = trace.then(std::time::Instant::now);
744    let inferred = match infer_type(&kernel_ctx, &proof_term) {
745        Ok(t) => t,
746        Err(e) => {
747            return VerifiedProof {
748                derivation: Some(derivation),
749                proof_term: None,
750                kernel_ctx,
751                verified: false,
752                verification_error: Some(format!("Type check failed: {}", e)),
753            };
754        }
755    };
756    if let Some(t_infer) = t_infer {
757        eprintln!("[cert] infer_type(check) {:.2?}", t_infer.elapsed());
758    }
759
760    let goal_type = match proof_expr_to_type_ctx(&names.expr(abstracted_goal), &kernel_ctx) {
761        Ok(t) => t,
762        Err(e) => {
763            return VerifiedProof {
764                derivation: Some(derivation),
765                proof_term: None,
766                kernel_ctx,
767                verified: false,
768                verification_error: Some(format!(
769                    "Cannot express the goal as a kernel type: {}",
770                    e
771                )),
772            };
773        }
774    };
775
776    if !is_subtype(&kernel_ctx, &inferred, &goal_type) {
777        return VerifiedProof {
778            derivation: Some(derivation),
779            proof_term: None,
780            kernel_ctx,
781            verified: false,
782            verification_error: Some(format!(
783                "Proof term proves a different proposition: inferred {:?}, goal {:?}",
784                inferred, goal_type
785            )),
786        };
787    }
788
789    // === Independent re-check (R1, the de Bruijn criterion) ===
790    // A second, independently-written kernel (a de Bruijn checker, distinct from
791    // `infer_type` above) must concur. `Agreed` is two-kernel verification; an honest
792    // `Incomplete` (a fragment the re-checker does not cover, e.g. a δ-conversion it keeps
793    // opaque) leaves the main kernel authoritative. Only a genuine `Disagree` — one kernel
794    // accepts, the other rejects, or they infer different types — rejects the proof: that
795    // is exactly the soundness alarm a second kernel exists to raise.
796    // The re-checker translates to de Bruijn indices and has no notion of a context's LOCAL
797    // bindings, so a term mentioning a statement's FREE variable (`∃m. m = n + 1`, Lean's
798    // `variable (n : Int)`) is rejected by it as "unbound local variable" even though the main
799    // kernel — which does consult `bindings` — accepted it. Closing the term over exactly those
800    // locals gives the two kernels the same CLOSED object to check, and the closure's type is
801    // the universal quantification of the theorem, so agreement on it is strictly stronger than
802    // agreement on the open judgement. The stored `proof_term` stays the open one: it is what
803    // `is_subtype` compared against the goal, and what the axiom footprint is read from.
804    // Closing the TERM is necessary and was not sufficient: a hypothesis registered from a
805    // premise that mentions a free variable has a TYPE mentioning it too (`h3 : P n`), and the
806    // re-checker converts a declaration's type to de Bruijn in an EMPTY scope — so it reported
807    // `unbound local variable 'n'` about a proof the main kernel had just accepted, and
808    // `double_check` called that a DISAGREEMENT. See [`recheck_view`].
809    let (recheck_ctx, closed) = match recheck_view(&kernel_ctx, &proof_term) {
810        Some(pair) => pair,
811        None => (
812            kernel_ctx.clone(),
813            close_over_context_locals(&kernel_ctx, &proof_term),
814        ),
815    };
816    if let DoubleCheck::Disagree(why) = double_check(&recheck_ctx, &closed) {
817        return VerifiedProof {
818            derivation: Some(derivation),
819            proof_term: None,
820            kernel_ctx,
821            verified: false,
822            verification_error: Some(format!("Independent re-checker disagreement: {}", why)),
823        };
824    }
825
826    VerifiedProof {
827        derivation: Some(derivation),
828        proof_term: Some(proof_term),
829        kernel_ctx,
830        verified: true,
831        verification_error: None,
832    }
833}
834
835/// The RE-CHECKER'S VIEW of a proof: every context LOCAL the proof depends on promoted to an
836/// opaque DECLARATION, and every `Var` naming one rewritten to the matching `Global` — in the
837/// proof term AND in the declaration types that mention it. `None` when no local is involved,
838/// which is the ordinary case and costs nothing.
839///
840/// [`close_over_context_locals`] closes the TERM, and that is not enough. A premise that
841/// mentions a statement's free variable is registered as a hypothesis whose TYPE mentions it
842/// too — `h3 : P n` — and the re-checker lowers a declaration's type to de Bruijn in an EMPTY
843/// scope, so it rejects `unbound local variable 'n'` about a proof the main kernel (which
844/// consults `bindings`) has just accepted. `double_check` then reports a DISAGREEMENT, and a
845/// disagreement is the SOUNDNESS ALARM a second kernel exists to raise: raising it on a valid
846/// proof is the one answer that is wrong either way. Measured on `induction n` over a free
847/// local, whose premises are the induction principle and whose goal is `P n`.
848///
849/// Promotion rather than λ-closure is what reaches the types. A local of a closed type is
850/// interchangeable with an opaque constant of that type — it is exactly what Lean's
851/// `variable (n : Nat)` is — so the two kernels are handed the same CLOSED object in a context
852/// where nothing is a local at all, and neither has to know what a local is.
853fn recheck_view(ctx: &Context, term: &Term) -> Option<(Context, Term)> {
854    // Which locals can be reached: the ones the TERM mentions, plus the ones mentioned by the
855    // type of any global the term cites (that is where a hypothesis about a free variable is).
856    let mut names = BTreeSet::new();
857    collect_free_kernel_vars(term, &mut Vec::new(), &mut names);
858    let mut globals = Vec::new();
859    collect_global_names(term, &mut globals);
860    for g in &globals {
861        if let Some(ty) = ctx.get_global(g) {
862            collect_free_kernel_vars(ty, &mut Vec::new(), &mut names);
863        }
864    }
865    names.retain(|n| ctx.get(n).is_some());
866    if names.is_empty() {
867        return None;
868    }
869
870    let mut out = ctx.clone();
871    for name in &names {
872        if let Some(ty) = ctx.get(name) {
873            out.add_declaration(name, ty.clone());
874        }
875    }
876    let rewritten: Vec<(String, Term)> = ctx
877        .iter_declarations()
878        .filter_map(|(decl, ty)| {
879            let fresh = vars_to_globals(ty, &names, &mut Vec::new());
880            (fresh != *ty).then(|| (decl.to_string(), fresh))
881        })
882        .collect();
883    for (decl, ty) in rewritten {
884        out.add_declaration(&decl, ty);
885    }
886    Some((out, vars_to_globals(term, &names, &mut Vec::new())))
887}
888
889/// Rewrite every free `Var(n)` with `n` in `names` to `Global(n)`. A binder of the same name
890/// SHADOWS the local, so `bound` is tracked exactly as [`collect_free_kernel_vars`] tracks it —
891/// the eliminator's own `λn` must keep binding its own `n`.
892fn vars_to_globals(term: &Term, names: &BTreeSet<String>, bound: &mut Vec<String>) -> Term {
893    match term {
894        Term::Var(name) => {
895            if names.contains(name) && !bound.iter().any(|b| b == name) {
896                Term::Global(name.clone())
897            } else {
898                term.clone()
899            }
900        }
901        Term::App(f, a) => Term::App(
902            Box::new(vars_to_globals(f, names, bound)),
903            Box::new(vars_to_globals(a, names, bound)),
904        ),
905        Term::Pi {
906            param,
907            param_type,
908            body_type,
909        } => {
910            let dom = vars_to_globals(param_type, names, bound);
911            bound.push(param.clone());
912            let cod = vars_to_globals(body_type, names, bound);
913            bound.pop();
914            Term::Pi {
915                param: param.clone(),
916                param_type: Box::new(dom),
917                body_type: Box::new(cod),
918            }
919        }
920        Term::Lambda {
921            param,
922            param_type,
923            body,
924        } => {
925            let dom = vars_to_globals(param_type, names, bound);
926            bound.push(param.clone());
927            let inner = vars_to_globals(body, names, bound);
928            bound.pop();
929            Term::Lambda {
930                param: param.clone(),
931                param_type: Box::new(dom),
932                body: Box::new(inner),
933            }
934        }
935        Term::Match {
936            discriminant,
937            motive,
938            cases,
939        } => Term::Match {
940            discriminant: Box::new(vars_to_globals(discriminant, names, bound)),
941            motive: Box::new(vars_to_globals(motive, names, bound)),
942            cases: cases
943                .iter()
944                .map(|c| vars_to_globals(c, names, bound))
945                .collect(),
946        },
947        Term::Fix { name, body } => {
948            bound.push(name.clone());
949            let inner = vars_to_globals(body, names, bound);
950            bound.pop();
951            Term::Fix {
952                name: name.clone(),
953                body: Box::new(inner),
954            }
955        }
956        Term::MutualFix { defs, index } => {
957            for (n, _) in defs {
958                bound.push(n.clone());
959            }
960            let out = defs
961                .iter()
962                .map(|(n, b)| (n.clone(), vars_to_globals(b, names, bound)))
963                .collect();
964            for _ in defs {
965                bound.pop();
966            }
967            Term::MutualFix {
968                defs: out,
969                index: *index,
970            }
971        }
972        Term::Let {
973            name,
974            ty,
975            value,
976            body,
977        } => {
978            let t = vars_to_globals(ty, names, bound);
979            let v = vars_to_globals(value, names, bound);
980            bound.push(name.clone());
981            let b = vars_to_globals(body, names, bound);
982            bound.pop();
983            Term::Let {
984                name: name.clone(),
985                ty: Box::new(t),
986                value: Box::new(v),
987                body: Box::new(b),
988            }
989        }
990        Term::Annotated { annotation, term } => Term::Annotated {
991            annotation: annotation.clone(),
992            term: Box::new(vars_to_globals(term, names, bound)),
993        },
994        Term::Sort(_) | Term::Global(_) | Term::Const { .. } | Term::Lit(_) | Term::Hole => {
995            term.clone()
996        }
997    }
998}
999
1000/// The UNIVERSAL CLOSURE of a proof term: `term` wrapped in a λ for every LOCAL binding of
1001/// `ctx` that occurs free in it, so the result is closed.
1002///
1003/// A statement may mention variables free — Lean's `variable (n : Int)`, our
1004/// `∃m. m = n + 1` — and the certifier lowers those to `Term::Var`, which the main kernel
1005/// resolves through the context's `bindings`. The independent RE-CHECKER translates to de
1006/// Bruijn indices and has no notion of a context's locals at all, so it rejects any such term
1007/// as "unbound local variable" and `double_check` reports a disagreement about a proof both
1008/// kernels would accept in closed form. Closing the term hands them the same closed object;
1009/// its type is the theorem's universal quantification, so agreement on it is strictly stronger
1010/// than agreement on the open judgement.
1011///
1012/// Order is the deterministic sorted order of the names; every such binding's type is a closed
1013/// `Global` (`Int`/`Entity`), so the binders are independent and the order does not matter.
1014pub fn close_over_context_locals(ctx: &Context, term: &Term) -> Term {
1015    let mut free = std::collections::BTreeSet::new();
1016    collect_free_kernel_vars(term, &mut Vec::new(), &mut free);
1017    let mut out = term.clone();
1018    for name in free.iter().rev() {
1019        let Some(ty) = ctx.get(name) else { continue };
1020        out = Term::Lambda {
1021            param: (*name).clone(),
1022            param_type: Box::new(ty.clone()),
1023            body: Box::new(out),
1024        };
1025    }
1026    out
1027}
1028
1029/// Every `Term::Var` of `term` that no enclosing binder introduces.
1030fn collect_free_kernel_vars(
1031    term: &Term,
1032    bound: &mut Vec<String>,
1033    out: &mut std::collections::BTreeSet<String>,
1034) {
1035    match term {
1036        Term::Var(name) => {
1037            if !bound.iter().any(|b| b == name) {
1038                out.insert(name.clone());
1039            }
1040        }
1041        Term::App(f, a) => {
1042            collect_free_kernel_vars(f, bound, out);
1043            collect_free_kernel_vars(a, bound, out);
1044        }
1045        Term::Pi {
1046            param,
1047            param_type,
1048            body_type,
1049        } => {
1050            collect_free_kernel_vars(param_type, bound, out);
1051            bound.push(param.clone());
1052            collect_free_kernel_vars(body_type, bound, out);
1053            bound.pop();
1054        }
1055        Term::Lambda {
1056            param,
1057            param_type,
1058            body,
1059        } => {
1060            collect_free_kernel_vars(param_type, bound, out);
1061            bound.push(param.clone());
1062            collect_free_kernel_vars(body, bound, out);
1063            bound.pop();
1064        }
1065        Term::Match {
1066            discriminant,
1067            motive,
1068            cases,
1069        } => {
1070            collect_free_kernel_vars(discriminant, bound, out);
1071            collect_free_kernel_vars(motive, bound, out);
1072            for c in cases {
1073                collect_free_kernel_vars(c, bound, out);
1074            }
1075        }
1076        Term::Fix { name, body } => {
1077            bound.push(name.clone());
1078            collect_free_kernel_vars(body, bound, out);
1079            bound.pop();
1080        }
1081        _ => {}
1082    }
1083}
1084
1085/// The result of checking a rule set for an internal contradiction.
1086///
1087/// `inconsistent == true` is never a bare verdict: it is backed by `proof_term`,
1088/// a kernel term of type `False` that re-checks under [`infer_type`] in
1089/// `kernel_ctx`. `conflicting_premises` names the input premises (by index) that
1090/// the proof of ⊥ actually used — the rules that clash.
1091pub struct ConflictReport {
1092    /// True iff the premises are jointly inconsistent *and* a kernel-checked
1093    /// proof of `False` was produced.
1094    pub inconsistent: bool,
1095    /// The kernel proof of `False`, present only when `inconsistent`.
1096    pub proof_term: Option<Term>,
1097    /// The kernel context the proof term checks in.
1098    pub kernel_ctx: Context,
1099    /// Indices (into the input `premises`) of the premises the proof used.
1100    pub conflicting_premises: Vec<usize>,
1101    /// Why detection failed to certify, if a contradiction was sketched but not
1102    /// kernel-checked (or none was found).
1103    pub error: Option<String>,
1104}
1105
1106/// Detect whether `premises` are jointly inconsistent, returning a
1107/// kernel-checked proof of `False` and the indices of the clashing premises.
1108///
1109/// This is verified conflict detection: where an SMT-only tool returns "unsat",
1110/// this returns a certificate anyone can re-check, plus *which* rules conflict.
1111/// A consistent rule set yields `inconsistent == false` with no proof — no false
1112/// alarms.
1113pub fn detect_conflict(premises: &[ProofExpr]) -> ConflictReport {
1114    let falsum = ProofExpr::Atom("⊥".to_string());
1115    let outcome = prove_certify_check(premises, &falsum);
1116
1117    if !outcome.verified {
1118        return ConflictReport {
1119            inconsistent: false,
1120            proof_term: None,
1121            kernel_ctx: outcome.kernel_ctx,
1122            conflicting_premises: Vec::new(),
1123            error: outcome.verification_error,
1124        };
1125    }
1126
1127    // Collect which premises the derivation actually referenced. Every premise
1128    // enters the proof as a `PremiseMatch` leaf (directly, or as the source of a
1129    // `UniversalInst`); we match those leaf conclusions back to the inputs.
1130    let mut used: Vec<usize> = Vec::new();
1131    if let Some(derivation) = &outcome.derivation {
1132        let mut leaves: Vec<&ProofExpr> = Vec::new();
1133        collect_premise_leaves(derivation, &mut leaves);
1134        for (i, premise) in premises.iter().enumerate() {
1135            if leaves.iter().any(|leaf| *leaf == premise) && !used.contains(&i) {
1136                used.push(i);
1137            }
1138        }
1139    }
1140
1141    ConflictReport {
1142        inconsistent: true,
1143        proof_term: outcome.proof_term,
1144        kernel_ctx: outcome.kernel_ctx,
1145        conflicting_premises: used,
1146        error: None,
1147    }
1148}
1149
1150/// Collect the conclusions of every `PremiseMatch` leaf in a derivation — the
1151/// premises (and instantiation sources) the proof draws on.
1152fn collect_premise_leaves<'a>(tree: &'a DerivationTree, out: &mut Vec<&'a ProofExpr>) {
1153    if matches!(tree.rule, crate::InferenceRule::PremiseMatch) {
1154        out.push(&tree.conclusion);
1155    }
1156    for premise in &tree.premises {
1157        collect_premise_leaves(premise, out);
1158    }
1159}
1160
1161// =============================================================================
1162// Symbol registration (proof + kernel only — no language dep)
1163// =============================================================================
1164
1165/// Register a predicate `P : Entity → … → Entity → Prop` of the given arity
1166/// (idempotent). Arity 0 registers a propositional constant `P : Prop`.
1167#[doc(hidden)]
1168fn count_term_nodes(t: &Term) -> usize {
1169    match t {
1170        Term::App(f, a) => 1 + count_term_nodes(f) + count_term_nodes(a),
1171        Term::Pi {
1172            param_type,
1173            body_type,
1174            ..
1175        } => 1 + count_term_nodes(param_type) + count_term_nodes(body_type),
1176        Term::Lambda {
1177            param_type, body, ..
1178        } => 1 + count_term_nodes(param_type) + count_term_nodes(body),
1179        Term::Match {
1180            discriminant,
1181            motive,
1182            cases,
1183        } => {
1184            1 + count_term_nodes(discriminant)
1185                + count_term_nodes(motive)
1186                + cases.iter().map(count_term_nodes).sum::<usize>()
1187        }
1188        Term::Fix { body, .. } => 1 + count_term_nodes(body),
1189        _ => 1,
1190    }
1191}
1192
1193fn register_predicate(ctx: &mut Context, name: &str, arity: usize) {
1194    if ctx.get_global(name).is_some() {
1195        return;
1196    }
1197    let mut ty = Term::Sort(Universe::Prop);
1198    for _ in 0..arity {
1199        ty = Term::Pi {
1200            param: "_".to_string(),
1201            param_type: Box::new(Term::Global("Entity".to_string())),
1202            body_type: Box::new(ty),
1203        };
1204    }
1205    ctx.add_declaration(name, ty);
1206}
1207
1208/// Register a function symbol of the given arity (idempotent): an argument position the
1209/// statement passes an `Int` (`int_domain`, settled by [`SymbolCollector::settle_sorts`])
1210/// takes `Int` and every other `Entity`, and the result is `Int` when `int_valued` and
1211/// `Entity` otherwise. Unlike a predicate, a function is term-valued, so `f(a)` can be
1212/// compared by equality and rewritten under congruence.
1213fn register_function(
1214    ctx: &mut Context,
1215    name: &str,
1216    arity: usize,
1217    int_valued: bool,
1218    int_domain: &std::collections::BTreeSet<usize>,
1219) {
1220    if ctx.get_global(name).is_some() {
1221        return;
1222    }
1223    let mut ty = Term::Global(if int_valued { "Int" } else { "Entity" }.to_string());
1224    for position in (0..arity).rev() {
1225        let domain = if int_domain.contains(&position) {
1226            "Int"
1227        } else {
1228            "Entity"
1229        };
1230        ty = Term::Pi {
1231            param: "_".to_string(),
1232            param_type: Box::new(Term::Global(domain.to_string())),
1233            body_type: Box::new(ty),
1234        };
1235    }
1236    ctx.add_declaration(name, ty);
1237}
1238
1239/// Register a constant `c : Entity` (idempotent).
1240fn register_constant(ctx: &mut Context, name: &str) {
1241    if ctx.get_global(name).is_some() {
1242        return;
1243    }
1244    ctx.add_declaration(name, Term::Global("Entity".to_string()));
1245}
1246
1247/// Register a temporal modality `Op : Prop → Prop` (idempotent). A tensed
1248/// proposition `Past(P)` lowers to `(Op P)`, distinct from `P`, so a modus-tollens
1249/// chain over tensed premises certifies.
1250fn register_modality(ctx: &mut Context, name: &str) {
1251    if ctx.get_global(name).is_some() {
1252        return;
1253    }
1254    ctx.add_declaration(
1255        name,
1256        Term::Pi {
1257            param: "_".to_string(),
1258            param_type: Box::new(Term::Sort(Universe::Prop)),
1259            body_type: Box::new(Term::Sort(Universe::Prop)),
1260        },
1261    );
1262}
1263
1264/// A failed-verification result carrying a definition-level error message.
1265fn definition_error(message: String) -> VerifiedProof {
1266    VerifiedProof {
1267        derivation: None,
1268        proof_term: None,
1269        kernel_ctx: Context::new(),
1270        verified: false,
1271        verification_error: Some(message),
1272    }
1273}
1274
1275/// Abstract neo-Davidsonian events in each definiens into first-order form — the
1276/// SAME transformation premises and goals get in [`prepare_ctx_with_defs`]. A
1277/// definiens over a verb (`someone admires x` ⇒ a `NeoEvent`) becomes an ordinary
1278/// predicate the kernel can type and the engine can match against the theorem's
1279/// (also-abstracted) events.
1280fn abstract_definitions(definitions: &[Definition]) -> Vec<Definition> {
1281    let abstractor = BackwardChainer::new();
1282    definitions
1283        .iter()
1284        .map(|d| Definition {
1285            name: d.name.clone(),
1286            params: d.params.clone(),
1287            definiens: abstractor.abstract_all_events(&d.definiens),
1288        })
1289        .collect()
1290}
1291
1292/// Reject definitions that cannot be soundly registered (Rung 0a guards):
1293/// self-recursive definienda (δ-unfolding would not terminate) and definiens
1294/// bodies the kernel lowering cannot type. Surfacing these up front gives a
1295/// clear message instead of a silent opaque fallback or a fuel-capped failure.
1296///
1297/// Mutual recursion *across* definitions is a Rung 0b (library DAG) concern and
1298/// is not yet detected here; the kernel's normalize fuel cap is the backstop —
1299/// an unguarded cycle fails the proof, it never hangs or returns a false proof.
1300fn validate_definitions(definitions: &[Definition]) -> Result<(), String> {
1301    if definitions.is_empty() {
1302        return Ok(());
1303    }
1304    for def in definitions {
1305        if let Err(e) = proof_expr_to_type(&def.definiens) {
1306            return Err(format!("cannot lower definition `{}`: {:?}", def.name, e));
1307        }
1308    }
1309    // δ-unfolding a cycle (self or mutual) would not terminate. The def→def graph
1310    // catches both; `find_definition_cycle` returns the offending names.
1311    if let Some(cycle) = find_definition_cycle(definitions) {
1312        return Err(format!(
1313            "circular definition among {{{}}}: a definition may not recursively refer \
1314             to itself, directly or transitively",
1315            cycle.join(", ")
1316        ));
1317    }
1318    Ok(())
1319}
1320
1321/// Register one definition as a δ-unfoldable kernel definition:
1322/// `name : Entity → … → Prop := λ(p₁:Entity)…λ(pₙ:Entity). <definiens>`.
1323///
1324/// The definiens lowers its parameters to `Global(p)` (constants), but a kernel
1325/// `Lambda` binds `Var(p)` — so we rewrite `Global(p) → Var(p)` for each
1326/// parameter before abstracting. Assumes [`validate_definitions`] has passed.
1327fn register_definition(ctx: &mut Context, def: &Definition) {
1328    if ctx.get_global(&def.name).is_some() {
1329        return;
1330    }
1331    let mut body = match proof_expr_to_type(&def.definiens) {
1332        Ok(b) => b,
1333        Err(_) => {
1334            // Defensive: validation should have caught this. Keep the context
1335            // well-formed by registering the definiendum as an opaque predicate.
1336            register_predicate(ctx, &def.name, def.params.len());
1337            return;
1338        }
1339    };
1340    for p in &def.params {
1341        body = subst_global_to_var(body, p);
1342    }
1343    // Abstract innermost-last so parameters bind left-to-right.
1344    for p in def.params.iter().rev() {
1345        body = Term::Lambda {
1346            param: p.clone(),
1347            param_type: Box::new(Term::Global("Entity".to_string())),
1348            body: Box::new(body),
1349        };
1350    }
1351    let mut ty = Term::Sort(Universe::Prop);
1352    for _ in &def.params {
1353        ty = Term::Pi {
1354            param: "_".to_string(),
1355            param_type: Box::new(Term::Global("Entity".to_string())),
1356            body_type: Box::new(ty),
1357        };
1358    }
1359    ctx.add_definition(def.name.clone(), ty, body);
1360}
1361
1362/// Rewrite every free `Global(name)` in `term` to `Var(name)` — used to turn a
1363/// definiens parameter (lowered as a global constant) into a bindable variable
1364/// before λ-abstraction.
1365fn subst_global_to_var(term: Term, name: &str) -> Term {
1366    match term {
1367        Term::Global(n) => {
1368            if n == name {
1369                Term::Var(n)
1370            } else {
1371                Term::Global(n)
1372            }
1373        }
1374        Term::App(f, a) => Term::App(
1375            Box::new(subst_global_to_var(*f, name)),
1376            Box::new(subst_global_to_var(*a, name)),
1377        ),
1378        Term::Pi {
1379            param,
1380            param_type,
1381            body_type,
1382        } => Term::Pi {
1383            param,
1384            param_type: Box::new(subst_global_to_var(*param_type, name)),
1385            body_type: Box::new(subst_global_to_var(*body_type, name)),
1386        },
1387        Term::Lambda {
1388            param,
1389            param_type,
1390            body,
1391        } => Term::Lambda {
1392            param,
1393            param_type: Box::new(subst_global_to_var(*param_type, name)),
1394            body: Box::new(subst_global_to_var(*body, name)),
1395        },
1396        Term::Match {
1397            discriminant,
1398            motive,
1399            cases,
1400        } => Term::Match {
1401            discriminant: Box::new(subst_global_to_var(*discriminant, name)),
1402            motive: Box::new(subst_global_to_var(*motive, name)),
1403            cases: cases
1404                .into_iter()
1405                .map(|c| subst_global_to_var(c, name))
1406                .collect(),
1407        },
1408        Term::Fix {
1409            name: fix_name,
1410            body,
1411        } => Term::Fix {
1412            name: fix_name,
1413            body: Box::new(subst_global_to_var(*body, name)),
1414        },
1415        other => other,
1416    }
1417}
1418
1419/// Collect, into `out`, every predicate name in `expr` that is one of the
1420/// `defined` names — i.e. the definitions this expression directly *uses*. Walks
1421/// the propositional structure (predicates are δ-expanded only in predicate
1422/// position, so that is exactly what we scan). Deduplicated, insertion-ordered.
1423fn collect_defined_predicates(expr: &ProofExpr, defined: &HashSet<&str>, out: &mut Vec<String>) {
1424    match expr {
1425        ProofExpr::Predicate { name, .. } => {
1426            if defined.contains(name.as_str()) && !out.iter().any(|n| n == name) {
1427                out.push(name.clone());
1428            }
1429        }
1430        ProofExpr::And(l, r)
1431        | ProofExpr::Or(l, r)
1432        | ProofExpr::Implies(l, r)
1433        | ProofExpr::Iff(l, r) => {
1434            collect_defined_predicates(l, defined, out);
1435            collect_defined_predicates(r, defined, out);
1436        }
1437        ProofExpr::Not(p) => collect_defined_predicates(p, defined, out),
1438        ProofExpr::ForAll { body, .. } | ProofExpr::Exists { body, .. } => {
1439            collect_defined_predicates(body, defined, out)
1440        }
1441        _ => {}
1442    }
1443}
1444
1445/// The direct def→def `uses` edges: for each definition, the OTHER definitions
1446/// its definiens references. O(total definiens size); membership is O(1).
1447fn def_edges(definitions: &[Definition]) -> Vec<(String, Vec<String>)> {
1448    let defined: HashSet<&str> = definitions.iter().map(|d| d.name.as_str()).collect();
1449    definitions
1450        .iter()
1451        .map(|d| {
1452            let mut uses = Vec::new();
1453            collect_defined_predicates(&d.definiens, &defined, &mut uses);
1454            (d.name.clone(), uses)
1455        })
1456        .collect()
1457}
1458
1459/// Detect a cycle (self-loop or mutual) in the def→def `uses` graph via Kahn's
1460/// topological elimination: if not every node can be peeled to zero in-degree,
1461/// the residual nodes form/feed cycles. Returns those names (sorted), or `None`
1462/// for a DAG. O(V + E).
1463fn find_definition_cycle(definitions: &[Definition]) -> Option<Vec<String>> {
1464    let edges = def_edges(definitions);
1465    let adj: HashMap<&str, &[String]> = edges
1466        .iter()
1467        .map(|(n, u)| (n.as_str(), u.as_slice()))
1468        .collect();
1469
1470    let mut indeg: HashMap<&str, usize> = adj.keys().map(|n| (*n, 0usize)).collect();
1471    for deps in adj.values() {
1472        for d in deps.iter() {
1473            if let Some(c) = indeg.get_mut(d.as_str()) {
1474                *c += 1;
1475            }
1476        }
1477    }
1478
1479    let mut queue: Vec<&str> = indeg
1480        .iter()
1481        .filter(|(_, &c)| c == 0)
1482        .map(|(n, _)| *n)
1483        .collect();
1484    let mut removed = 0usize;
1485    while let Some(n) = queue.pop() {
1486        removed += 1;
1487        if let Some(deps) = adj.get(n) {
1488            for d in deps.iter() {
1489                if let Some(c) = indeg.get_mut(d.as_str()) {
1490                    *c -= 1;
1491                    if *c == 0 {
1492                        queue.push(d.as_str());
1493                    }
1494                }
1495            }
1496        }
1497    }
1498
1499    if removed == adj.len() {
1500        None
1501    } else {
1502        let mut cyclic: Vec<String> = indeg
1503            .iter()
1504            .filter(|(_, &c)| c > 0)
1505            .map(|(n, _)| n.to_string())
1506            .collect();
1507        cyclic.sort();
1508        Some(cyclic)
1509    }
1510}
1511
1512/// The `uses` dependency graph among definitions and from a theorem to its
1513/// definitions — the Rung 0b graph seed (each node a definition/theorem, each
1514/// edge a `uses`). Direct edges only; transitive use is a query over this. This
1515/// is the structure a `mathscrapes` node/edge compiles into.
1516#[derive(Debug, Clone, Default)]
1517pub struct DependencyGraph {
1518    /// definiendum name → the defined names its definiens directly uses.
1519    pub def_uses: Vec<(String, Vec<String>)>,
1520    /// the defined names the theorem's premises + goal directly use.
1521    pub theorem_uses: Vec<String>,
1522}
1523
1524/// Build the [`DependencyGraph`] for a set of definitions plus a theorem
1525/// (premises + goal), recording which definitions each definiens uses and which
1526/// the theorem uses. Pure, allocation-light, O(total expression size).
1527pub fn dependency_graph(
1528    definitions: &[Definition],
1529    premises: &[ProofExpr],
1530    goal: &ProofExpr,
1531) -> DependencyGraph {
1532    let defined: HashSet<&str> = definitions.iter().map(|d| d.name.as_str()).collect();
1533    let def_uses = def_edges(definitions);
1534    let mut theorem_uses = Vec::new();
1535    for p in premises {
1536        collect_defined_predicates(p, &defined, &mut theorem_uses);
1537    }
1538    collect_defined_predicates(goal, &defined, &mut theorem_uses);
1539    DependencyGraph {
1540        def_uses,
1541        theorem_uses,
1542    }
1543}
1544
1545/// Maximum δ-expansion depth for expand-for-search — a backstop against an
1546/// accidental cross-definition cycle (self-recursion is already rejected by
1547/// [`validate_definitions`]; cross-def cycle detection is a Rung 0b concern).
1548const MAX_EXPANSION_DEPTH: usize = 64;
1549
1550/// δ-expand every defined predicate in `expr`: replace `def(args)` with its
1551/// definiens (parameters substituted by `args`), recursively, so the result is
1552/// stated purely in terms of undefined predicates the backward chainer can
1553/// search over. Non-defined predicates and all other nodes are walked
1554/// structurally. The identity when `defs` is empty.
1555fn expand_defs_in_expr(
1556    expr: &ProofExpr,
1557    defs: &HashMap<&str, &Definition>,
1558    depth: usize,
1559) -> ProofExpr {
1560    if depth >= MAX_EXPANSION_DEPTH {
1561        return expr.clone();
1562    }
1563    match expr {
1564        ProofExpr::Predicate { name, args, .. } => {
1565            if let Some(def) = defs.get(name.as_str()) {
1566                if def.params.len() == args.len() {
1567                    let substituted = substitute_params(&def.definiens, &def.params, args);
1568                    return expand_defs_in_expr(&substituted, defs, depth + 1);
1569                }
1570            }
1571            expr.clone()
1572        }
1573        ProofExpr::And(l, r) => ProofExpr::And(
1574            Box::new(expand_defs_in_expr(l, defs, depth)),
1575            Box::new(expand_defs_in_expr(r, defs, depth)),
1576        ),
1577        ProofExpr::Or(l, r) => ProofExpr::Or(
1578            Box::new(expand_defs_in_expr(l, defs, depth)),
1579            Box::new(expand_defs_in_expr(r, defs, depth)),
1580        ),
1581        ProofExpr::Implies(l, r) => ProofExpr::Implies(
1582            Box::new(expand_defs_in_expr(l, defs, depth)),
1583            Box::new(expand_defs_in_expr(r, defs, depth)),
1584        ),
1585        ProofExpr::Iff(l, r) => ProofExpr::Iff(
1586            Box::new(expand_defs_in_expr(l, defs, depth)),
1587            Box::new(expand_defs_in_expr(r, defs, depth)),
1588        ),
1589        ProofExpr::Not(p) => ProofExpr::Not(Box::new(expand_defs_in_expr(p, defs, depth))),
1590        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
1591            variable: variable.clone(),
1592            body: Box::new(expand_defs_in_expr(body, defs, depth)),
1593        },
1594        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
1595            variable: variable.clone(),
1596            body: Box::new(expand_defs_in_expr(body, defs, depth)),
1597        },
1598        other => other.clone(),
1599    }
1600}
1601
1602/// Substitute a definition's parameters with the actual arguments throughout its
1603/// definiens, when δ-expanding a definition occurrence.
1604fn substitute_params(expr: &ProofExpr, params: &[String], args: &[ProofTerm]) -> ProofExpr {
1605    match expr {
1606        ProofExpr::Predicate {
1607            name,
1608            args: pargs,
1609            world,
1610        } => ProofExpr::Predicate {
1611            name: name.clone(),
1612            args: pargs.iter().map(|t| subst_term(t, params, args)).collect(),
1613            world: world.clone(),
1614        },
1615        ProofExpr::And(l, r) => ProofExpr::And(
1616            Box::new(substitute_params(l, params, args)),
1617            Box::new(substitute_params(r, params, args)),
1618        ),
1619        ProofExpr::Or(l, r) => ProofExpr::Or(
1620            Box::new(substitute_params(l, params, args)),
1621            Box::new(substitute_params(r, params, args)),
1622        ),
1623        ProofExpr::Implies(l, r) => ProofExpr::Implies(
1624            Box::new(substitute_params(l, params, args)),
1625            Box::new(substitute_params(r, params, args)),
1626        ),
1627        ProofExpr::Iff(l, r) => ProofExpr::Iff(
1628            Box::new(substitute_params(l, params, args)),
1629            Box::new(substitute_params(r, params, args)),
1630        ),
1631        ProofExpr::Not(p) => ProofExpr::Not(Box::new(substitute_params(p, params, args))),
1632        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
1633            variable: variable.clone(),
1634            body: Box::new(substitute_params(body, params, args)),
1635        },
1636        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
1637            variable: variable.clone(),
1638            body: Box::new(substitute_params(body, params, args)),
1639        },
1640        ProofExpr::Identity(l, r) => {
1641            ProofExpr::Identity(subst_term(l, params, args), subst_term(r, params, args))
1642        }
1643        other => other.clone(),
1644    }
1645}
1646
1647/// Rewrite biconditionals into their two implications: `P ↔ Q` becomes
1648/// `(P → Q) ∧ (Q → P)`. Applied to premises so biconditional elimination falls
1649/// out of the existing implication + conjunction machinery (the kernel has no
1650/// `Iff` type). Recurses through the propositional structure.
1651fn expand_iff(expr: &ProofExpr) -> ProofExpr {
1652    match expr {
1653        ProofExpr::Iff(p, q) => {
1654            let p = expand_iff(p);
1655            let q = expand_iff(q);
1656            ProofExpr::And(
1657                Box::new(ProofExpr::Implies(Box::new(p.clone()), Box::new(q.clone()))),
1658                Box::new(ProofExpr::Implies(Box::new(q), Box::new(p))),
1659            )
1660        }
1661        ProofExpr::And(l, r) => ProofExpr::And(Box::new(expand_iff(l)), Box::new(expand_iff(r))),
1662        ProofExpr::Or(l, r) => ProofExpr::Or(Box::new(expand_iff(l)), Box::new(expand_iff(r))),
1663        ProofExpr::Implies(l, r) => {
1664            ProofExpr::Implies(Box::new(expand_iff(l)), Box::new(expand_iff(r)))
1665        }
1666        ProofExpr::Not(p) => ProofExpr::Not(Box::new(expand_iff(p))),
1667        ProofExpr::ForAll { variable, body } => ProofExpr::ForAll {
1668            variable: variable.clone(),
1669            body: Box::new(expand_iff(body)),
1670        },
1671        ProofExpr::Exists { variable, body } => ProofExpr::Exists {
1672            variable: variable.clone(),
1673            body: Box::new(expand_iff(body)),
1674        },
1675        other => other.clone(),
1676    }
1677}
1678
1679/// Substitute a parameter with its argument inside a single term. Parameters lower
1680/// to `Constant`s and quantifier-bound variables are `Variable`/`BoundVarRef`, so
1681/// substituting ONLY `Constant`s can never capture a bound variable — even when a
1682/// definiens' quantifier reuses a parameter's name (`∀x … admire(x, x_param)`).
1683fn subst_term(term: &ProofTerm, params: &[String], args: &[ProofTerm]) -> ProofTerm {
1684    match term {
1685        ProofTerm::Constant(n) => match params.iter().position(|p| p == n) {
1686            Some(i) => args[i].clone(),
1687            None => term.clone(),
1688        },
1689        ProofTerm::Function(name, fargs) => ProofTerm::Function(
1690            name.clone(),
1691            fargs.iter().map(|t| subst_term(t, params, args)).collect(),
1692        ),
1693        ProofTerm::Group(ts) => {
1694            ProofTerm::Group(ts.iter().map(|t| subst_term(t, params, args)).collect())
1695        }
1696        // Bound variables (∀/∃) are never parameters — leave them untouched.
1697        ProofTerm::Variable(_) | ProofTerm::BoundVarRef(_) => term.clone(),
1698    }
1699}